feat: align frontend document and rule management flows
This commit is contained in:
+23
-15
@@ -60,17 +60,23 @@ export async function loader({ request }: LoaderFunctionArgs) {
|
||||
|
||||
if (routesResult.success && routesResult.data) {
|
||||
// 查找 '/settings' 路由及其子路由
|
||||
const settingsRoute = routesResult.data.find(route => route.path === '/settings');
|
||||
if (settingsRoute) {
|
||||
hasSettingsAccess = true;
|
||||
// 提取子路由信息(仅 path 和 title)
|
||||
if (settingsRoute.children && settingsRoute.children.length > 0) {
|
||||
settingsChildren = settingsRoute.children.map(child => ({
|
||||
path: child.path,
|
||||
title: child.title
|
||||
}));
|
||||
}
|
||||
}
|
||||
const settingsRoute = routesResult.data.find(route => route.path === '/settings');
|
||||
if (settingsRoute) {
|
||||
hasSettingsAccess = true;
|
||||
// 提取子路由信息(仅 path 和 title)
|
||||
if (settingsRoute.children && settingsRoute.children.length > 0) {
|
||||
settingsChildren = settingsRoute.children
|
||||
.map(child => ({
|
||||
path: child.path,
|
||||
title: child.title
|
||||
}))
|
||||
.sort((a, b) => {
|
||||
if (a.path === '/rule-groups') return -1;
|
||||
if (b.path === '/rule-groups') return 1;
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否存在顶级路由 '/cross-checking'
|
||||
// 🔒 交叉评查访问控制:
|
||||
@@ -291,10 +297,12 @@ export default function Index() {
|
||||
}
|
||||
|
||||
// 跳转到第一个子路由
|
||||
const firstChildPath = loaderData.settingsChildren[0].path;
|
||||
console.log(`📌 [Index] 系统设置:跳转到第一个子路由 ${firstChildPath}`);
|
||||
navigate(firstChildPath);
|
||||
};
|
||||
const preferredSettingsPath =
|
||||
loaderData.settingsChildren.find((child: { path: string; title: string }) => child.path === '/rule-groups')?.path ||
|
||||
loaderData.settingsChildren[0].path;
|
||||
console.log(`📌 [Index] 系统设置:跳转到首选子路由 ${preferredSettingsPath}`);
|
||||
navigate(preferredSettingsPath);
|
||||
};
|
||||
|
||||
// 处理进入交叉评查
|
||||
const handleEnterCrossChecking = () => {
|
||||
|
||||
@@ -22,10 +22,10 @@ export const links = () => [
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => {
|
||||
return [
|
||||
{ title: `${data?.template.title || '合同模板详情'} - 智慧法务` },
|
||||
{ title: `${data?.template.title || '模板详情'} - 合同管理 - 智慧法务` },
|
||||
{
|
||||
name: 'description',
|
||||
content: data?.template.description || '查看合同模板详细信息'
|
||||
content: data?.template.description || '查看合同管理模块中的模板详细信息'
|
||||
}
|
||||
];
|
||||
};
|
||||
@@ -537,4 +537,4 @@ export default function ContractTemplateDetail() {
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,10 +15,10 @@ export const links = () => [
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: '合同模板列表 - 智慧法务' },
|
||||
{ title: '模板列表 - 合同管理 - 智慧法务' },
|
||||
{
|
||||
name: 'description',
|
||||
content: '浏览和管理所有合同模板,按分类查看各种类型的合同模板。'
|
||||
content: '浏览合同管理模块下的模板列表,按分类查看和使用合同模板。'
|
||||
}
|
||||
];
|
||||
};
|
||||
@@ -238,7 +238,7 @@ export default function ContractTemplateList() {
|
||||
<div className="result-header">
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold mb-2">
|
||||
{currentCategory === '全部' ? '合同模板库' : `${currentCategory}模板`}
|
||||
{currentCategory === '全部' ? '合同管理' : `${currentCategory}模板`}
|
||||
</h2>
|
||||
<div className="result-info">
|
||||
共 <span className="result-count">{total}</span> 个模板
|
||||
@@ -307,4 +307,4 @@ export default function ContractTemplateList() {
|
||||
// 面包屑导航配置
|
||||
export const handle = {
|
||||
breadcrumb: "合同列表"
|
||||
};
|
||||
};
|
||||
|
||||
@@ -12,17 +12,17 @@ export const links = () => [
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: 'AI智能合同模板搜索 - 智慧法务' },
|
||||
{ title: '模板搜索 - 合同管理 - 智慧法务' },
|
||||
{
|
||||
name: 'description',
|
||||
content: '使用AI智能搜索快速找到最适合的合同模板,支持自然语言描述搜索。'
|
||||
content: '在合同管理模块中使用智能检索快速找到合适的合同模板。'
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
// 面包屑导航配置
|
||||
export const handle = {
|
||||
breadcrumb: "智能搜索"
|
||||
breadcrumb: "模板搜索"
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -117,4 +117,4 @@ export default function ContractTemplateSearchIndex() {
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,10 +17,10 @@ export const links = () => [
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: '搜索结果 - AI智能合同模板搜索 - 智慧法务' },
|
||||
{ title: '模板搜索结果 - 合同管理 - 智慧法务' },
|
||||
{
|
||||
name: 'description',
|
||||
content: 'AI智能搜索合同模板结果,快速找到最适合的模板。'
|
||||
content: '查看合同管理模块的模板搜索结果,快速定位合适模板。'
|
||||
}
|
||||
];
|
||||
};
|
||||
@@ -323,4 +323,4 @@ export default function ContractTemplateSearchResults() {
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export function links() {
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: "文档类型管理 - 中国烟草AI合同及卷宗审核系统" },
|
||||
{ name: "description", content: "管理文档类型及其规则集绑定" },
|
||||
{ name: "description", content: "管理文档类型及其汇总规则集绑定" },
|
||||
];
|
||||
};
|
||||
|
||||
@@ -104,7 +104,7 @@ export default function DocumentTypesIndex() {
|
||||
<th>编码</th>
|
||||
<th>名称</th>
|
||||
<th>入口模块</th>
|
||||
<th>规则集</th>
|
||||
<th>汇总规则集</th>
|
||||
<th>状态</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
type EntryModuleOption,
|
||||
type RuleSetOption,
|
||||
} from "~/api/document-types/document-types";
|
||||
import { getDocumentSubtypeGroups, type DocumentSubtypeGroup } from "~/api/files/files-upload";
|
||||
import newStyles from "~/styles/pages/document-types_new.css?url";
|
||||
|
||||
export function links() {
|
||||
@@ -30,6 +31,7 @@ interface LoaderData {
|
||||
entryModules: EntryModuleOption[];
|
||||
ruleSets: RuleSetOption[];
|
||||
editType: DocumentType | null;
|
||||
runtimeSubtypeGroups: DocumentSubtypeGroup[];
|
||||
frontendJWT?: string | null;
|
||||
}
|
||||
|
||||
@@ -45,12 +47,19 @@ export async function loader({ request }: LoaderFunctionArgs) {
|
||||
]);
|
||||
|
||||
let editType: DocumentType | null = null;
|
||||
let runtimeSubtypeGroups: DocumentSubtypeGroup[] = [];
|
||||
if (editId) {
|
||||
const res = await getDocumentType(parseInt(editId), frontendJWT);
|
||||
editType = res.data || null;
|
||||
if (editType?.id) {
|
||||
const groupsRes = await getDocumentSubtypeGroups(editType.id, frontendJWT, editType.entryModuleId || undefined);
|
||||
if ("data" in groupsRes && groupsRes.data) {
|
||||
runtimeSubtypeGroups = groupsRes.data;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { entryModules: modulesRes.data || [], ruleSets: setsRes.data || [], editType, frontendJWT };
|
||||
return { entryModules: modulesRes.data || [], ruleSets: setsRes.data || [], editType, runtimeSubtypeGroups, frontendJWT };
|
||||
}
|
||||
|
||||
export default function DocumentTypeNew() {
|
||||
@@ -69,6 +78,8 @@ export default function DocumentTypeNew() {
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
const selectedModule = loaderData.entryModules.find((m) => m.id === entryModuleId);
|
||||
const runtimeSubtypeGroups = loaderData.runtimeSubtypeGroups || [];
|
||||
const ruleSetsReadonly = isEdit && runtimeSubtypeGroups.length > 0;
|
||||
const selectedRuleSets = loaderData.ruleSets.filter((rs) => selectedRuleSetIds.includes(rs.id));
|
||||
const selectedUnavailableRuleSets = selectedRuleSets.filter((rs) => !rs.hasUsableVersion);
|
||||
const normalizedRuleSetKeyword = ruleSetKeyword.trim().toLowerCase();
|
||||
@@ -102,7 +113,7 @@ export default function DocumentTypeNew() {
|
||||
if (!code.trim()) errs.code = "编码不能为空";
|
||||
else if (!/^[a-zA-Z][a-zA-Z0-9_.]*$/.test(code.trim())) errs.code = "编码格式:字母开头,可含字母数字._";
|
||||
if (!name.trim()) errs.name = "名称不能为空";
|
||||
if (selectedUnavailableRuleSets.length > 0) {
|
||||
if (!ruleSetsReadonly && selectedUnavailableRuleSets.length > 0) {
|
||||
errs.ruleSetIds = "已选择的规则集中包含不可用于上传评查的项,请先确认可用规则数是否正常";
|
||||
}
|
||||
setErrors(errs);
|
||||
@@ -126,7 +137,7 @@ export default function DocumentTypeNew() {
|
||||
name: name.trim(),
|
||||
description: description.trim(),
|
||||
entryModuleId,
|
||||
ruleSetIds: selectedRuleSetIds,
|
||||
...(ruleSetsReadonly ? {} : { ruleSetIds: selectedRuleSetIds }),
|
||||
};
|
||||
const res = await updateDocumentType(editType.id, dto, loaderData.frontendJWT ?? undefined);
|
||||
if (res.error) { toastService.error(res.error); return; }
|
||||
@@ -161,7 +172,7 @@ export default function DocumentTypeNew() {
|
||||
{isEdit ? `编辑文档类型 — ${editType?.code}` : "新建文档类型"}
|
||||
</h2>
|
||||
<p className="page-subtitle">
|
||||
为上传入口绑定清晰的文档语义、规则集和处理流向,减少后续抽取与评查配置分散的问题。
|
||||
为上传入口绑定清晰的文档语义、汇总规则集和处理流向;实际运行时仍以评查点分组页中的“二级分组 → 规则集”绑定为准。
|
||||
</p>
|
||||
</div>
|
||||
<div className="header-overview">
|
||||
@@ -299,15 +310,62 @@ export default function DocumentTypeNew() {
|
||||
<span>{selectedModule?.name || "未绑定入口模块,上传入口不会主动露出此类型"}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isEdit ? (
|
||||
<div className="rule-set-warning">
|
||||
<i className="ri-node-tree"></i>
|
||||
<div>
|
||||
<strong>当前运行链路摘要</strong>
|
||||
<span>
|
||||
{runtimeSubtypeGroups.length > 0
|
||||
? `当前文档类型在评查点分组中已挂到 ${runtimeSubtypeGroups.length} 个二级分组;上传时会先按入口模块和子类型命中,再决定实际规则集。`
|
||||
: "当前文档类型还没有在评查点分组中挂到任何二级分组,上传时无法形成完整的新链路。"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{isEdit && runtimeSubtypeGroups.length > 0 ? (
|
||||
<div className="selected-rule-sets-panel">
|
||||
<div className="selected-panel-header">
|
||||
<div>
|
||||
<strong>已关联的运行子类型</strong>
|
||||
<span>这里只展示实际会命中的二级分组,最终规则仍以分组页绑定为准。</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="selected-rule-grid">
|
||||
{runtimeSubtypeGroups.map((group) => (
|
||||
<div key={group.id} className="selected-rule-card">
|
||||
<div className="selected-rule-main">
|
||||
<strong>{group.displayName || group.name}</strong>
|
||||
<span>{group.rootGroupName || "未归属一级分组"}{group.entryModuleName ? ` · ${group.entryModuleName}` : ""}</span>
|
||||
</div>
|
||||
<span className="selected-rule-meta">{group.code}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
<section className="form-section">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<span className="section-kicker">Step 03</span>
|
||||
<h3>关联规则集</h3>
|
||||
<h3>汇总规则集</h3>
|
||||
</div>
|
||||
<p>这里展示的是文档类型维度的汇总规则集,用于兼容旧页面与快速总览;如果同一文档类型拆成多个二级分组,实际上传命中仍以分组页配置为准。</p>
|
||||
</div>
|
||||
|
||||
<div className="rule-set-warning">
|
||||
<i className={ruleSetsReadonly ? "ri-lock-line" : "ri-information-line"}></i>
|
||||
<div>
|
||||
<strong>{ruleSetsReadonly ? "当前已收口为只读汇总" : "这是汇总视图,不是最终运行绑定"}</strong>
|
||||
<span>
|
||||
{ruleSetsReadonly
|
||||
? "当前文档类型已经接入评查点分组新链路。这里仅展示汇总结果,不再作为最终运行绑定编辑入口;请到“评查点分组管理”维护二级分组下的实际规则集。"
|
||||
: "当一个文档类型下存在多个二级分组时,这里看到的是所有二级分组规则集的并集汇总;具体到某次上传,只会命中所选子类型下的规则集。"}
|
||||
</span>
|
||||
</div>
|
||||
<p>规则集会直接影响上传后的评查范围,建议按业务场景精确绑定,不要泛滥勾选。</p>
|
||||
</div>
|
||||
|
||||
<div className="rule-set-toolbar">
|
||||
@@ -316,7 +374,11 @@ export default function DocumentTypeNew() {
|
||||
<i className="ri-checkbox-circle-line"></i>
|
||||
已选择 {selectedRuleSetIds.length} / {loaderData.ruleSets.length}
|
||||
</span>
|
||||
<span className="form-hint">勾选后,该文档类型上传时会自动加载对应规则集执行评查</span>
|
||||
<span className="form-hint">
|
||||
{ruleSetsReadonly
|
||||
? "当前只读展示的是文档类型层汇总结果;上传时将优先按入口模块下命中的二级分组执行评查。"
|
||||
: "这里用于维护文档类型层的汇总结果;上传时若已拆分子类型,后端会优先按二级分组绑定执行评查。"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="rule-set-search">
|
||||
<i className="ri-search-line"></i>
|
||||
@@ -328,6 +390,17 @@ export default function DocumentTypeNew() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{ruleSetsReadonly ? (
|
||||
<div className="readonly-guide-card">
|
||||
<div>
|
||||
<strong>如需调整实际运行规则</strong>
|
||||
<span>请进入“评查点分组管理”,在对应一级分组 / 二级分组下编辑规则集绑定。</span>
|
||||
</div>
|
||||
<Button type="default" onClick={() => navigate("/rule-groups")} disabled={saving}>
|
||||
打开评查点分组
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
{selectedUnavailableRuleSets.length > 0 && (
|
||||
<div className="rule-set-warning">
|
||||
<i className="ri-error-warning-line"></i>
|
||||
@@ -365,6 +438,7 @@ export default function DocumentTypeNew() {
|
||||
type="checkbox"
|
||||
checked={selectedRuleSetIds.includes(rs.id)}
|
||||
onChange={() => toggleRuleSet(rs.id)}
|
||||
disabled={ruleSetsReadonly}
|
||||
/>
|
||||
</div>
|
||||
<div className="rule-set-content">
|
||||
@@ -497,7 +571,7 @@ export default function DocumentTypeNew() {
|
||||
<ul className="guide-list">
|
||||
<li>编码保持稳定,不要混入显示文案,便于后端接口与权限配置长期复用。</li>
|
||||
<li>描述尽量写业务边界,例如“主合同”“补充协议”“付款附件”等,避免上传误选。</li>
|
||||
<li>规则集宁可精简,也不要把无关规则打包给所有文档类型,避免误报过多。</li>
|
||||
<li>{ruleSetsReadonly ? "当前类型的实际运行规则请统一在评查点分组页维护,避免这里和分组页双写冲突。" : "规则集宁可精简,也不要把无关规则打包给所有文档类型,避免误报过多。"}</li>
|
||||
</ul>
|
||||
</Card>
|
||||
</aside>
|
||||
|
||||
@@ -517,6 +517,12 @@ export default function DocumentEdit() {
|
||||
<i className="ri-file-list-line"></i>
|
||||
<span>{getDocumentTypeName(documentData.type)}</span>
|
||||
</div>
|
||||
{documentData.groupName && (
|
||||
<div className="meta-item">
|
||||
<i className="ri-git-merge-line"></i>
|
||||
<span>子类型:{documentData.groupName}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="meta-item">
|
||||
<i className="ri-time-line"></i>
|
||||
<span>{documentData.uploadTime}</span>
|
||||
@@ -568,6 +574,20 @@ export default function DocumentEdit() {
|
||||
/>
|
||||
<div className="text-sm text-secondary mt-1">如无编号可留空</div>
|
||||
</div>
|
||||
|
||||
{documentData.groupName && (
|
||||
<div className="form-group">
|
||||
<label className="form-label">子类型</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-input"
|
||||
value={documentData.groupName}
|
||||
disabled
|
||||
readOnly
|
||||
/>
|
||||
<div className="text-sm text-secondary mt-1">子类型由上传时命中的二级分组决定,当前页面仅展示不可修改。</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="audit-status" className="form-label">审核状态 <span className="text-red-500">*</span></label>
|
||||
|
||||
+103
-62
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { Fragment, useState, useEffect, useRef, useCallback } from "react";
|
||||
import { useSearchParams, useLoaderData, useFetcher, useNavigate,Link } from "@remix-run/react";
|
||||
import { type MetaFunction, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node";
|
||||
import { Card } from "~/components/ui/Card";
|
||||
@@ -13,6 +13,7 @@ import { TableRowSkeleton, LoadingIndicator, NumberSkeleton } from '~/components
|
||||
import documentsIndexStyles from "~/styles/pages/documents_index.css?url";
|
||||
import documentVersionStyles from "~/styles/components/document-version.css?url";
|
||||
import { getDocumentTypesByIds, deleteDocument, getDocumentsListFromAPI, type DocumentUI, type DocumentVersionUI } from "~/api/files/documents";
|
||||
import { getDocumentTypes } from "~/api/document-types/document-types";
|
||||
// import { IssuesDiff } from "~/components/ui/IssuesDiff";
|
||||
import { ResultStats } from "~/components/ui/ResultStats";
|
||||
import { updateDocumentAuditStatus } from "~/api/evaluation_points/rules-files";
|
||||
@@ -57,7 +58,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
// label: type.name
|
||||
// }));
|
||||
|
||||
// 初始返回空数据,将在客户端根据 sessionStorage 中的 documentTypeIds 加载实际数据
|
||||
// 初始返回空数据,客户端会根据入口模块/类型作用域加载实际数据
|
||||
return Response.json({
|
||||
documents: [],
|
||||
total: 0,
|
||||
@@ -76,6 +77,11 @@ interface ActionResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface DocumentListScope {
|
||||
selectedModuleId: number | null;
|
||||
documentTypeIds: number[];
|
||||
}
|
||||
|
||||
// 审核状态筛选选项
|
||||
const auditStatusOptions = [
|
||||
// { value: "", label: "全部" },
|
||||
@@ -186,12 +192,13 @@ export default function DocumentsIndex() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// 权限控制
|
||||
const { hasPermission } = usePermission();
|
||||
const canView = hasPermission('document:document:view');
|
||||
const canUpdate = hasPermission('document:document:update');
|
||||
const { hasAnyPermission } = usePermission();
|
||||
const canView = hasAnyPermission(['documents:list:read', 'documents:detail:read']);
|
||||
const canUpdate = hasAnyPermission(['documents:update:write', 'documents:detail:read', 'documents:list:read']);
|
||||
|
||||
// 存储从 sessionStorage 获取的 documentTypeIds
|
||||
const [documentTypeIds, setDocumentTypeIds] = useState<number[] | null>(null);
|
||||
// 文档列表现在优先走入口模块作用域,documentTypeIds 仅保留兼容旧首页缓存。
|
||||
const [listScope, setListScope] = useState<DocumentListScope>({ selectedModuleId: null, documentTypeIds: [] });
|
||||
const [scopeReady, setScopeReady] = useState(false);
|
||||
|
||||
// 添加页面加载状态管理
|
||||
const [isLoadingData, setIsLoadingData] = useState(true);
|
||||
@@ -275,8 +282,40 @@ export default function DocumentsIndex() {
|
||||
const pageSize = parseInt(searchParams.get("pageSize") || "10", 10);
|
||||
|
||||
|
||||
const readListScopeFromSession = useCallback((): DocumentListScope => {
|
||||
if (typeof window === 'undefined') {
|
||||
return { selectedModuleId: null, documentTypeIds: [] };
|
||||
}
|
||||
|
||||
let selectedModuleId: number | null = null;
|
||||
const selectedModuleIdStr = sessionStorage.getItem('selectedModuleId');
|
||||
if (selectedModuleIdStr) {
|
||||
const parsedModuleId = Number(selectedModuleIdStr);
|
||||
if (Number.isFinite(parsedModuleId) && parsedModuleId > 0) {
|
||||
selectedModuleId = parsedModuleId;
|
||||
}
|
||||
}
|
||||
|
||||
let documentTypeIds: number[] = [];
|
||||
const typeIdsStr = sessionStorage.getItem('documentTypeIds');
|
||||
if (typeIdsStr) {
|
||||
try {
|
||||
const parsedTypeIds = JSON.parse(typeIdsStr);
|
||||
if (Array.isArray(parsedTypeIds)) {
|
||||
documentTypeIds = parsedTypeIds
|
||||
.map((item) => Number(item))
|
||||
.filter((item) => Number.isFinite(item) && item > 0);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析 sessionStorage.documentTypeIds 失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
return { selectedModuleId, documentTypeIds };
|
||||
}, []);
|
||||
|
||||
// 客户端数据请求
|
||||
const fetchData = useCallback(async (typeIds: number[]) => {
|
||||
const fetchData = useCallback(async (scope: DocumentListScope) => {
|
||||
setIsLoadingData(true);
|
||||
loadingBarService.show();
|
||||
|
||||
@@ -290,7 +329,12 @@ export default function DocumentsIndex() {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('🔑 [fetchData] 文档类型IDs:', typeIds);
|
||||
const selectedTypeId = Number(documentType);
|
||||
const scopedTypeIds = documentType && Number.isFinite(selectedTypeId) && selectedTypeId > 0
|
||||
? [selectedTypeId]
|
||||
: scope.documentTypeIds;
|
||||
|
||||
console.log('🔑 [fetchData] 文档列表作用域:', scope);
|
||||
|
||||
// 调用新的 API 函数
|
||||
const result = await getDocumentsListFromAPI({
|
||||
@@ -298,7 +342,8 @@ export default function DocumentsIndex() {
|
||||
pageSize: pageSize,
|
||||
name: search || undefined,
|
||||
documentNumber: documentNumber || undefined,
|
||||
documentTypeIds: documentType ? [parseInt(documentType, 10)] : typeIds, // 如果有单独选择的类型,优先使用
|
||||
documentTypeIds: scopedTypeIds,
|
||||
entryModuleId: scope.selectedModuleId || undefined,
|
||||
auditStatus: auditStatus || undefined,
|
||||
fileStatus: fileStatus || undefined,
|
||||
dateFrom: dateFrom || undefined,
|
||||
@@ -320,14 +365,26 @@ export default function DocumentsIndex() {
|
||||
setDocuments(result.data.documents);
|
||||
setTotal(result.data.total);
|
||||
|
||||
// 获取经过过滤的文档类型列表
|
||||
const filteredTypesResponse = await getDocumentTypesByIds(typeIds, jwtToken);
|
||||
// 文档类型下拉与列表作用域保持一致:优先入口模块,其次兼容旧缓存 typeIds。
|
||||
const filteredTypesResponse = scope.selectedModuleId
|
||||
? await getDocumentTypes({ entry_module_id: scope.selectedModuleId, page: 1, pageSize: 200 }, jwtToken)
|
||||
: await getDocumentTypesByIds(scope.documentTypeIds, jwtToken);
|
||||
|
||||
if (filteredTypesResponse.data?.types?.length) {
|
||||
const typeNameMap = new Map(
|
||||
filteredTypesResponse.data.types.map((type) => [String(type.id), type.name])
|
||||
);
|
||||
const filteredOptions = filteredTypesResponse.data.types.map(type => ({
|
||||
value: type.id,
|
||||
label: type.name
|
||||
}));
|
||||
setFilteredDocumentTypeOptions(filteredOptions);
|
||||
setDocuments(
|
||||
result.data.documents.map((doc) => ({
|
||||
...doc,
|
||||
typeName: typeNameMap.get(doc.type) || doc.typeName,
|
||||
}))
|
||||
);
|
||||
} else {
|
||||
const fallbackOptions = Array.from(
|
||||
new Map(
|
||||
@@ -337,6 +394,7 @@ export default function DocumentsIndex() {
|
||||
).values()
|
||||
);
|
||||
setFilteredDocumentTypeOptions(fallbackOptions);
|
||||
setDocuments(result.data.documents);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -349,41 +407,27 @@ export default function DocumentsIndex() {
|
||||
}
|
||||
}, [search, documentNumber, documentType, auditStatus, fileStatus, dateFrom, dateTo, currentPage, pageSize, loaderData.frontendJWT]);
|
||||
|
||||
// 在组件挂载时从 sessionStorage 获取 documentTypeIds 并加载数据
|
||||
// 在组件挂载时建立页面作用域并加载数据。
|
||||
useEffect(() => {
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
const typeIdsStr = sessionStorage.getItem('documentTypeIds');
|
||||
if (typeIdsStr) {
|
||||
const typeIds = JSON.parse(typeIdsStr) as number[];
|
||||
console.log('📋 [useEffect] 从 sessionStorage 获取文档类型IDs:', typeIds);
|
||||
setDocumentTypeIds(typeIds);
|
||||
|
||||
// 加载数据(fetchData 中会自动获取并设置过滤后的文档类型选项)
|
||||
fetchData(typeIds);
|
||||
} else {
|
||||
console.warn('⚠️ [useEffect] sessionStorage 中没有 documentTypeIds');
|
||||
// 没有 documentTypeIds 时,标记初始化完成但无数据
|
||||
setIsLoadingData(false);
|
||||
setHasInitialized(true);
|
||||
loadingBarService.hide();
|
||||
}
|
||||
}
|
||||
const nextScope = readListScopeFromSession();
|
||||
setListScope(nextScope);
|
||||
setScopeReady(true);
|
||||
} catch (error) {
|
||||
console.error('❌ [useEffect] 获取 sessionStorage 中的 documentTypeIds 失败:', error);
|
||||
console.error('❌ [useEffect] 初始化文档列表作用域失败:', error);
|
||||
// 出错时也标记初始化完成
|
||||
setIsLoadingData(false);
|
||||
setHasInitialized(true);
|
||||
setScopeReady(true);
|
||||
loadingBarService.hide();
|
||||
}
|
||||
}, [fetchData]);
|
||||
}, [readListScopeFromSession]);
|
||||
|
||||
// 监听 URL 参数变化,重新获取数据
|
||||
useEffect(() => {
|
||||
if (documentTypeIds) {
|
||||
fetchData(documentTypeIds);
|
||||
}
|
||||
}, [searchParams, fetchData, documentTypeIds]);
|
||||
if (!scopeReady) return;
|
||||
fetchData(listScope);
|
||||
}, [searchParams, fetchData, listScope, scopeReady]);
|
||||
|
||||
// 监听 documents 数据变化,自动修正不一致的展开状态
|
||||
useEffect(() => {
|
||||
@@ -439,15 +483,13 @@ export default function DocumentsIndex() {
|
||||
if (fetcher.data.result) {
|
||||
toastService.success(fetcher.data.message);
|
||||
// 删除成功后重新加载数据
|
||||
if (documentTypeIds) {
|
||||
fetchData(documentTypeIds);
|
||||
}
|
||||
fetchData(listScope);
|
||||
} else if (fetcher.data.message) {
|
||||
toastService.error(fetcher.data.message);
|
||||
// 删除失败只显示错误信息,不刷新数据
|
||||
}
|
||||
}
|
||||
}, [fetcher.data, fetcher.state, fetchData, documentTypeIds, isDeleting]);
|
||||
}, [fetcher.data, fetcher.state, fetchData, listScope, isDeleting]);
|
||||
|
||||
// 分页处理函数
|
||||
const handlePageChange = (page: number) => {
|
||||
@@ -921,9 +963,7 @@ export default function DocumentsIndex() {
|
||||
setSelectedDocumentVersion(null);
|
||||
|
||||
// 刷新文档列表
|
||||
if (documentTypeIds && documentTypeIds.length > 0) {
|
||||
fetchData(documentTypeIds);
|
||||
}
|
||||
fetchData(listScope);
|
||||
|
||||
} catch (error) {
|
||||
console.error('【附件追加】上传失败:', error);
|
||||
@@ -993,9 +1033,7 @@ export default function DocumentsIndex() {
|
||||
setSelectedDocumentVersion(null);
|
||||
|
||||
// 刷新文档列表
|
||||
if (documentTypeIds && documentTypeIds.length > 0) {
|
||||
fetchData(documentTypeIds);
|
||||
}
|
||||
fetchData(listScope);
|
||||
|
||||
} catch (error) {
|
||||
console.error('【合同模板上传】上传失败:', error);
|
||||
@@ -1178,7 +1216,7 @@ export default function DocumentsIndex() {
|
||||
className="text-xs px-2 py-1 h-7 mr-1 hover:underline"
|
||||
>
|
||||
<i className="ri-eye-line"></i>
|
||||
查看
|
||||
查看详情
|
||||
</Link>
|
||||
)}
|
||||
{/* 修改按钮 - 需要 document:document:view 权限 */}
|
||||
@@ -1316,6 +1354,11 @@ export default function DocumentsIndex() {
|
||||
fileType={record.fileType}
|
||||
colorMode="light"
|
||||
/>
|
||||
{record.groupName && (
|
||||
<span className="text-xs bg-emerald-50 text-emerald-700 border border-emerald-200 px-2 py-[2px] rounded">
|
||||
子类型:{record.groupName}
|
||||
</span>
|
||||
)}
|
||||
{record.isTest && (
|
||||
<span className="text-xs bg-gray-100 text-gray-500 px-1 rounded">测试</span>
|
||||
)}
|
||||
@@ -1379,14 +1422,14 @@ export default function DocumentsIndex() {
|
||||
width:"18%",
|
||||
render: (_: unknown, record: DocumentUI) => (
|
||||
<ResultStats
|
||||
passCount={record.pass_count}
|
||||
warningCount={record.warning_count}
|
||||
errorCount={record.error_count}
|
||||
manualCount={record.manual_count}
|
||||
previousPassCount={record.previous_pass_count}
|
||||
previousWarningCount={record.previous_warning_count}
|
||||
previousErrorCount={record.previous_error_count}
|
||||
previousManualCount={record.previous_manual_count}
|
||||
passCount={record.pass_count ?? null}
|
||||
warningCount={record.warning_count ?? null}
|
||||
errorCount={record.error_count ?? null}
|
||||
manualCount={record.manual_count ?? null}
|
||||
previousPassCount={record.previous_pass_count ?? null}
|
||||
previousWarningCount={record.previous_warning_count ?? null}
|
||||
previousErrorCount={record.previous_error_count ?? null}
|
||||
previousManualCount={record.previous_manual_count ?? null}
|
||||
warningMessages={record.warning_messages}
|
||||
errorMessages={record.error_messages}
|
||||
manualMessages={record.manual_messages}
|
||||
@@ -1436,7 +1479,7 @@ export default function DocumentsIndex() {
|
||||
className="text-xs px-2 py-1 h-7 mr-1 hover:underline"
|
||||
>
|
||||
<i className="ri-eye-line"></i>
|
||||
查看
|
||||
查看详情
|
||||
</Link>
|
||||
)}
|
||||
</>
|
||||
@@ -1547,9 +1590,7 @@ export default function DocumentsIndex() {
|
||||
type="primary"
|
||||
icon="ri-search-line"
|
||||
onClick={() => {
|
||||
if (documentTypeIds) {
|
||||
fetchData(documentTypeIds);
|
||||
}
|
||||
fetchData(listScope);
|
||||
}}
|
||||
className="mr-2"
|
||||
>
|
||||
@@ -1673,7 +1714,7 @@ export default function DocumentsIndex() {
|
||||
</thead>
|
||||
<tbody>
|
||||
{documents.map((doc) => (
|
||||
<>
|
||||
<Fragment key={`doc-group-${doc.id}`}>
|
||||
{/* 主文档行 */}
|
||||
<tr
|
||||
key={doc.id}
|
||||
@@ -1705,7 +1746,7 @@ export default function DocumentsIndex() {
|
||||
>
|
||||
{columns.map((col, index) => (
|
||||
<td key={col.key || index} className="px-4 py-3 text-sm">
|
||||
{col.render ? col.render(null, doc, index) : (doc as any)[col.key]}
|
||||
{col.render ? col.render(null, doc) : (doc as any)[col.key]}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
@@ -1738,7 +1779,7 @@ export default function DocumentsIndex() {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
</Fragment>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
+19
-10
@@ -1,22 +1,31 @@
|
||||
import { Outlet } from "@remix-run/react";
|
||||
import { type MetaFunction } from "@remix-run/node";
|
||||
import { redirect, type LoaderFunctionArgs, type MetaFunction } from "@remix-run/node";
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: "文档列表 - 中国烟草AI合同及卷宗审核系统" },
|
||||
{ name: "documents", content: "文档列表,新增,修改" }
|
||||
]
|
||||
}
|
||||
return [
|
||||
{ title: "文档列表 - 中国烟草AI合同及卷宗审核系统" },
|
||||
{ name: "documents", content: "文档列表,新增,修改" }
|
||||
];
|
||||
};
|
||||
|
||||
export const handle = {
|
||||
breadcrumb: "文档列表"
|
||||
breadcrumb: "文档列表"
|
||||
};
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === '/documents') {
|
||||
const query = url.searchParams.toString();
|
||||
throw redirect(query ? `/documents/list?${query}` : '/documents/list');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文档列表路由布局
|
||||
*/
|
||||
export default function DocumentsLayout() {
|
||||
return (
|
||||
<Outlet />
|
||||
)
|
||||
return <Outlet />;
|
||||
}
|
||||
|
||||
+127
-19
@@ -14,6 +14,7 @@ import {
|
||||
buildUploadErrorDetails,
|
||||
getTodayDocuments,
|
||||
getDocumentTypes,
|
||||
getDocumentSubtypeGroups,
|
||||
getDocumentsStatus,
|
||||
uploadFileToBinary,
|
||||
uploadDocumentToServer,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
checkDocumentDuplicate,
|
||||
type Document,
|
||||
type DocumentType,
|
||||
type DocumentSubtypeGroup,
|
||||
type UploadErrorDetails,
|
||||
type UploadResult,
|
||||
DocumentStatus
|
||||
@@ -29,7 +31,6 @@ import {
|
||||
import { updateDocumentAuditStatus } from "~/api/evaluation_points/rules-files";
|
||||
import { links as fileTypeTagLinks } from "~/components/ui/FileTypeTag";
|
||||
import { getQueueStatus, type QueueStatus } from "~/api/queue";
|
||||
import { CONTRACT_TYPES, DEFAULT_CONTRACT_TYPE } from "~/constants/contractTypes";
|
||||
|
||||
export function links() {
|
||||
return [
|
||||
@@ -132,9 +133,11 @@ async function handleFileUpload(
|
||||
fileName: string,
|
||||
fileType: string,
|
||||
documentType: FileType,
|
||||
groupId: number | null,
|
||||
priority: Priority,
|
||||
region: string,
|
||||
createdBy?: number,
|
||||
attachments?: File[],
|
||||
jwtToken?: string,
|
||||
): Promise<UploadResult> {
|
||||
const speed = priority === Priority.NORMAL ? "normal" : "urgent";
|
||||
@@ -144,8 +147,10 @@ async function handleFileUpload(
|
||||
fileName,
|
||||
fileType,
|
||||
Number(documentType),
|
||||
groupId,
|
||||
region,
|
||||
createdBy,
|
||||
attachments,
|
||||
true,
|
||||
speed,
|
||||
jwtToken,
|
||||
@@ -331,6 +336,7 @@ export default function FilesUpload() {
|
||||
// 获取 sessionStorage 中的 documentTypeIds 值
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [documentTypeIds, setDocumentTypeIds] = useState<number[] | null>(null);
|
||||
const [selectedModuleId, setSelectedModuleId] = useState<number | null>(null);
|
||||
|
||||
// 使用 useLoaderData 获取初始数据
|
||||
const loaderData = useLoaderData<LoaderData>();
|
||||
@@ -344,7 +350,9 @@ export default function FilesUpload() {
|
||||
const [documentNumber, setDocumentNumber] = useState<string>("");
|
||||
const [remark, setRemark] = useState<string>("");
|
||||
const [currentFiles, setCurrentFiles] = useState<File[]>([]);
|
||||
const [attributeType, setAttributeType] = useState<string>(DEFAULT_CONTRACT_TYPE);
|
||||
const [subtypeGroups, setSubtypeGroups] = useState<DocumentSubtypeGroup[]>([]);
|
||||
const [selectedGroupId, setSelectedGroupId] = useState<string>("");
|
||||
const [groupOptionsLoading, setGroupOptionsLoading] = useState(false);
|
||||
|
||||
// 合同文件上传状态
|
||||
// 这些变量暂时未使用,但保留以备将来扩展
|
||||
@@ -393,6 +401,16 @@ export default function FilesUpload() {
|
||||
loaderData.documentTypes.find(type => type.id.toString() === fileType) ||
|
||||
null;
|
||||
|
||||
const getSubtypeDisplayName = (group: DocumentSubtypeGroup | null | undefined) =>
|
||||
group?.displayName || group?.name || "";
|
||||
|
||||
const selectedSubtypeGroup = subtypeGroups.find(group => String(group.id) === selectedGroupId) || null;
|
||||
const hasMultipleSubtypeGroups = subtypeGroups.length > 1;
|
||||
const singleSubtypeGroup = subtypeGroups.length === 1 ? subtypeGroups[0] : null;
|
||||
const isSingleDefaultSubtype = !!(singleSubtypeGroup && singleSubtypeGroup.isDefault);
|
||||
const selectedRootGroupName = selectedSubtypeGroup?.rootGroupName || singleSubtypeGroup?.rootGroupName || "";
|
||||
const selectedEntryModuleName = selectedSubtypeGroup?.entryModuleName || singleSubtypeGroup?.entryModuleName || "";
|
||||
|
||||
const clearUploadErrorDetails = () => {
|
||||
setUploadErrorDetails(null);
|
||||
};
|
||||
@@ -444,6 +462,8 @@ export default function FilesUpload() {
|
||||
? nextSelectedModuleId
|
||||
: null;
|
||||
|
||||
setSelectedModuleId(normalizedModuleId);
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
@@ -842,6 +862,51 @@ export default function FilesUpload() {
|
||||
setFileTypeError("上传文件之前请选择文件类型");
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const loadSubtypeGroups = async () => {
|
||||
if (!fileType) {
|
||||
setSubtypeGroups([]);
|
||||
setSelectedGroupId("");
|
||||
return;
|
||||
}
|
||||
|
||||
setGroupOptionsLoading(true);
|
||||
try {
|
||||
const response = await getDocumentSubtypeGroups(
|
||||
Number(fileType),
|
||||
loaderData.frontendJWT || undefined,
|
||||
selectedModuleId,
|
||||
);
|
||||
if (cancelled) return;
|
||||
if ("error" in response || !response.data) {
|
||||
setSubtypeGroups([]);
|
||||
setSelectedGroupId("");
|
||||
return;
|
||||
}
|
||||
|
||||
const groups = response.data;
|
||||
setSubtypeGroups(groups);
|
||||
setSelectedGroupId((currentValue) => {
|
||||
if (groups.some((item) => String(item.id) === currentValue)) {
|
||||
return currentValue;
|
||||
}
|
||||
return groups.length === 1 ? String(groups[0].id) : "";
|
||||
});
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setGroupOptionsLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void loadSubtypeGroups();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [fileType, loaderData.frontendJWT, selectedModuleId]);
|
||||
|
||||
// 处理合同主文件选择
|
||||
const handleContractMainFilesSelected = (files: FileList) => {
|
||||
@@ -1260,8 +1325,8 @@ export default function FilesUpload() {
|
||||
const createdBy = loaderData.userInfo?.user_id as number | undefined;
|
||||
const uploadResp = await handleFileUpload(
|
||||
binaryData, mainFile.name, mainFile.type,
|
||||
fileType as FileType, priority,
|
||||
region, createdBy, loaderData.frontendJWT || undefined,
|
||||
fileType as FileType, selectedGroupId ? Number(selectedGroupId) : null, priority,
|
||||
region, createdBy, attachmentFiles, loaderData.frontendJWT || undefined,
|
||||
);
|
||||
|
||||
if (!uploadResp.success) {
|
||||
@@ -1350,6 +1415,10 @@ export default function FilesUpload() {
|
||||
toastService.error('请先选择文件类型');
|
||||
return;
|
||||
}
|
||||
if (subtypeGroups.length > 1 && !selectedGroupId) {
|
||||
toastService.error('请先选择子类型后再上传');
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否为合同类型
|
||||
const selectedType = loaderData.documentTypes.find(t => t.id.toString() === fileType);
|
||||
@@ -1596,8 +1665,8 @@ export default function FilesUpload() {
|
||||
const createdBy = loaderData.userInfo?.user_id as number | undefined;
|
||||
const uploadPromise = handleFileUpload(
|
||||
binaryData, file.name, file.type,
|
||||
fileType as FileType, priority,
|
||||
region, createdBy, loaderData.frontendJWT || undefined,
|
||||
fileType as FileType, selectedGroupId ? Number(selectedGroupId) : null, priority,
|
||||
region, createdBy, undefined, loaderData.frontendJWT || undefined,
|
||||
);
|
||||
|
||||
const timeoutPromise = new Promise<UploadResult>((_, reject) => {
|
||||
@@ -2362,27 +2431,66 @@ export default function FilesUpload() {
|
||||
</select>
|
||||
<div className="form-tip">优先级影响文档在队列中的处理顺序</div>
|
||||
</div>
|
||||
{/* 子类型(专属类型)- 始终显示 */}
|
||||
{/* 子类型(二级分组) */}
|
||||
<div className="form-group">
|
||||
<label htmlFor="attribute-type-select" className="form-label">
|
||||
子类型 <span className="required">*</span>
|
||||
</label>
|
||||
<select
|
||||
id="attribute-type-select"
|
||||
name="attributeType"
|
||||
name="groupId"
|
||||
className="form-select"
|
||||
value={attributeType}
|
||||
onChange={(e) => setAttributeType(e.target.value)}
|
||||
disabled={uploadStage !== "idle"}
|
||||
required
|
||||
value={selectedGroupId}
|
||||
onChange={(e) => setSelectedGroupId(e.target.value)}
|
||||
disabled={uploadStage !== "idle" || !fileType || groupOptionsLoading || subtypeGroups.length <= 1}
|
||||
required={subtypeGroups.length > 1}
|
||||
>
|
||||
{CONTRACT_TYPES.map(type => (
|
||||
<option key={type.value} value={type.value}>
|
||||
{type.label}
|
||||
{!fileType ? (
|
||||
<option value="">请先选择文件类型</option>
|
||||
) : groupOptionsLoading ? (
|
||||
<option value="">子类型加载中...</option>
|
||||
) : subtypeGroups.length === 0 ? (
|
||||
<option value="">当前文档类型暂无二级分组</option>
|
||||
) : subtypeGroups.length === 1 ? (
|
||||
<option value={String(subtypeGroups[0].id)}>
|
||||
{getSubtypeDisplayName(subtypeGroups[0])}
|
||||
</option>
|
||||
))}
|
||||
) : (
|
||||
<>
|
||||
<option value="">请选择子类型</option>
|
||||
{subtypeGroups.map((group) => (
|
||||
<option key={group.id} value={String(group.id)}>
|
||||
{getSubtypeDisplayName(group)}
|
||||
</option>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</select>
|
||||
<div className="form-tip">选择文档专属类型以应用对应的审核规则(合同大类请选择技术/租赁/买卖等)</div>
|
||||
<div className="form-tip">
|
||||
{!fileType
|
||||
? "请先选择文件类型,再确定本次上传实际命中的子类型。"
|
||||
: groupOptionsLoading
|
||||
? "正在加载当前文档类型下可用的子类型配置。"
|
||||
: subtypeGroups.length === 0
|
||||
? "当前文档类型在当前入口下还没有可用子类型,请先到评查点分组管理补齐“一级分组 / 二级分组 / 规则集”绑定。"
|
||||
: hasMultipleSubtypeGroups
|
||||
? "同一文档类型在当前入口下已拆分多个子类型,请选择本次上传实际命中的子类型。"
|
||||
: isSingleDefaultSubtype
|
||||
? "当前文档类型在当前入口下尚未拆分业务子类型,系统将按默认子类型处理;后续可在评查点分组管理中继续细分。"
|
||||
: "当前文档类型在当前入口下仅配置了一个子类型,系统会自动带出该子类型。"}
|
||||
</div>
|
||||
{selectedRootGroupName ? (
|
||||
<div className="form-tip">
|
||||
所属一级分组:{selectedRootGroupName}
|
||||
{selectedEntryModuleName ? ` · 入口模块:${selectedEntryModuleName}` : ""}
|
||||
</div>
|
||||
) : null}
|
||||
{selectedSubtypeGroup ? (
|
||||
<div className="form-tip">
|
||||
当前命中:{getSubtypeDisplayName(selectedSubtypeGroup)}
|
||||
{selectedSubtypeGroup.displayHint ? ` · ${selectedSubtypeGroup.displayHint}` : ""}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label htmlFor="docNumber" className="form-label">文档编号</label>
|
||||
@@ -2783,7 +2891,7 @@ export default function FilesUpload() {
|
||||
<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>
|
||||
<p className="text-sm text-green-700">文件已成功上传并评查完成,请查看详情。</p>
|
||||
</div>
|
||||
|
||||
{/* <div className="flex justify-end">
|
||||
@@ -2792,7 +2900,7 @@ export default function FilesUpload() {
|
||||
icon="ri-file-search-line"
|
||||
|
||||
>
|
||||
查看详情并审核
|
||||
查看详情
|
||||
</Button>
|
||||
</div> */}
|
||||
</div>
|
||||
|
||||
+1
-1
@@ -391,7 +391,7 @@ export default function Home() {
|
||||
<ShortcutItem icon="ri-upload-cloud-line" label="上传文件" to="/files/upload" />
|
||||
<ShortcutItem icon="ri-file-list-3-line" label="文档列表" to="/documents/list" />
|
||||
<ShortcutItem icon="ri-list-check-3" label="评查点列表" to="/rules/list" />
|
||||
<ShortcutItem icon="ri-folder-open-line" label="评查点分组" to="/rule-groups" />
|
||||
<ShortcutItem icon="ri-folder-open-line" label="规则组导航" to="/rule-groups" />
|
||||
</div>
|
||||
</Card> */}
|
||||
|
||||
|
||||
@@ -844,7 +844,7 @@ export default function ReviewDetails() {
|
||||
// 构建自定义面包屑项
|
||||
const getBreadcrumbItems = () => {
|
||||
const items = [
|
||||
{ title: "评查详情", to: `/reviews?id=${document?.id}` }
|
||||
{ title: "评查详情", to: `/reviewsTest?id=${document?.id}` }
|
||||
];
|
||||
|
||||
// 添加前置路由
|
||||
|
||||
+1124
-954
File diff suppressed because it is too large
Load Diff
+45
-742
@@ -1,768 +1,71 @@
|
||||
|
||||
import { redirect, type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction } from "@remix-run/node";
|
||||
import { useLoaderData, useActionData, useNavigation, Form } from "@remix-run/react";
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
import { Button } from "~/components/ui/Button";
|
||||
import { redirect, type LoaderFunctionArgs, type MetaFunction } from "@remix-run/node";
|
||||
import { Link, useLoaderData } from "@remix-run/react";
|
||||
import { Card } from "~/components/ui/Card";
|
||||
import { toastService } from "~/components/ui/Toast";
|
||||
import { usePermission } from "~/hooks/usePermission";
|
||||
import { Button } from "~/components/ui/Button";
|
||||
import ruleGroupsNewStyles from "~/styles/pages/rule-groups_new.css?url";
|
||||
import {
|
||||
getEvaluationPointGroups,
|
||||
getEvaluationPointGroup,
|
||||
createEvaluationPointGroup,
|
||||
updateEvaluationPointGroup,
|
||||
type RuleGroup as ApiRuleGroup,
|
||||
type RuleGroupCreateUpdateDto
|
||||
} from "~/api/evaluation_points/rule-groups";
|
||||
|
||||
// 类型定义
|
||||
interface RuleGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
description?: string;
|
||||
status: 'active' | 'inactive';
|
||||
parentId?: string | null;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
interface ParentGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
// 定义加载器返回数据类型
|
||||
export interface LoaderData {
|
||||
group?: RuleGroup;
|
||||
parentGroups: ParentGroup[];
|
||||
isEdit: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// 定义action返回数据类型
|
||||
export interface ActionData {
|
||||
success?: boolean;
|
||||
errors?: {
|
||||
name?: string;
|
||||
code?: string;
|
||||
parentId?: string;
|
||||
general?: string;
|
||||
};
|
||||
values?: Record<string, string>;
|
||||
}
|
||||
|
||||
// 样式链接
|
||||
export function links() {
|
||||
return [{ rel: "stylesheet", href: ruleGroupsNewStyles }];
|
||||
}
|
||||
|
||||
// 动态面包屑
|
||||
export const handle = {
|
||||
breadcrumb: (data: LoaderData) => {
|
||||
return data.isEdit ? "编辑分组" : "新增分组";
|
||||
}
|
||||
breadcrumb: "规则导航说明",
|
||||
};
|
||||
|
||||
// 页面元数据
|
||||
export const meta: MetaFunction = ({ location }) => {
|
||||
const isEdit = new URLSearchParams(location.search).has("id");
|
||||
const title = isEdit ? "编辑评查点分组" : "新建评查点分组";
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: `${title} - 中国烟草AI合同及卷宗审核系统` },
|
||||
{ name: "description", content: "创建新的评查点分组,包括分组名称、编码、描述和状态" },
|
||||
{ title: "规则导航说明 - 中国烟草AI合同及卷宗审核系统" },
|
||||
{ name: "description", content: "旧评查点分组编辑入口已下线,请改用新规则导航页。" },
|
||||
];
|
||||
};
|
||||
|
||||
// 将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 || apiGroup.pid === '0') ? null : apiGroup.pid, // 🆕 NULL或'0'都表示顶级分组
|
||||
sortOrder: 0 // API中不存在sortOrder字段,使用默认值
|
||||
};
|
||||
interface LoaderData {
|
||||
redirectTarget: string;
|
||||
}
|
||||
|
||||
// 数据加载器
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
// console.log("rule-groups.new loader被调用,URL:", request.url);
|
||||
try {
|
||||
// 获取用户会话信息
|
||||
const { getUserSession } = await import("~/api/login/auth.server");
|
||||
const { frontendJWT } = await getUserSession(request);
|
||||
|
||||
const url = new URL(request.url);
|
||||
const id = url.searchParams.get("id");
|
||||
// console.log("获取到的ID参数:", id);
|
||||
|
||||
// 获取一级分组列表 (用于选择父级分组)
|
||||
// 🆕 使用 FastAPI v3 的 getEvaluationPointGroups API,仅获取一级分组且已启用的分组
|
||||
const parentGroupsResponse = await getEvaluationPointGroups({
|
||||
pid: null, // 仅获取一级分组(pid为null表示顶级分组)
|
||||
is_enabled: true, // 仅获取已启用的分组
|
||||
pageSize: 100, // 获取足够多的分组
|
||||
token: frontendJWT
|
||||
}, frontendJWT);
|
||||
if (parentGroupsResponse.error) {
|
||||
console.error("获取父分组列表失败:", parentGroupsResponse.error);
|
||||
throw new Error(parentGroupsResponse.error);
|
||||
}
|
||||
const url = new URL(request.url);
|
||||
|
||||
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 getEvaluationPointGroup(id, true, frontendJWT);
|
||||
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
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("loader函数出错:", error);
|
||||
// 返回一个基本的响应,避免500错误
|
||||
return Response.json({
|
||||
group: undefined,
|
||||
parentGroups: [],
|
||||
isEdit: false,
|
||||
error: error instanceof Error ? error.message : "加载数据时出错"
|
||||
});
|
||||
if (url.searchParams.get("id") || url.searchParams.get("mode")) {
|
||||
throw redirect("/rule-groups");
|
||||
}
|
||||
|
||||
return Response.json({ redirectTarget: "/rule-groups" } satisfies LoaderData);
|
||||
}
|
||||
|
||||
// 表单处理
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
const formData = await request.formData();
|
||||
export default function RuleGroupsLegacyRedirect() {
|
||||
const { redirectTarget } = useLoaderData<LoaderData>();
|
||||
|
||||
// 获取用户会话信息
|
||||
const { getUserSession } = await import("~/api/login/auth.server");
|
||||
const { frontendJWT } = await getUserSession(request);
|
||||
|
||||
// 提取表单数据
|
||||
const id = formData.get("id") as string | null;
|
||||
const name = formData.get("name") as string;
|
||||
const code = formData.get("code") as string;
|
||||
const description = formData.get("description") as string;
|
||||
const status = formData.get("status") as string || "active";
|
||||
const groupType = formData.get("groupType") as string;
|
||||
const parentId = groupType === "secondary" ? formData.get("parentId") as string : null;
|
||||
|
||||
// 表单验证
|
||||
// action是处于服务端的表单提交方法,这里再次验证表单数据也是出于安全考虑,防止客户端验证被绕过从而提交非法数据
|
||||
const errors: ActionData["errors"] = {};
|
||||
|
||||
if (!name || name.trim() === "") {
|
||||
errors.name = "分组名称不能为空";
|
||||
}
|
||||
|
||||
if (!code || code.trim() === "") {
|
||||
errors.code = "分组编码不能为空";
|
||||
} else if (!/^[a-zA-Z0-9-_]+$/.test(code)) {
|
||||
errors.code = "分组编码只能包含字母、数字、连字符和下划线";
|
||||
}
|
||||
|
||||
if (groupType === "secondary" && (!parentId || parentId.trim() === "")) {
|
||||
errors.parentId = "请选择上级分组";
|
||||
}
|
||||
|
||||
if (Object.keys(errors).length > 0) {
|
||||
return Response.json({
|
||||
errors,
|
||||
values: Object.fromEntries(formData) as Record<string, string>
|
||||
});
|
||||
}
|
||||
|
||||
// 构建保存数据
|
||||
const saveData: RuleGroupCreateUpdateDto = {
|
||||
name: name.trim(),
|
||||
code: code.trim(),
|
||||
description: description?.trim() || "",
|
||||
is_enabled: status === "active",
|
||||
pid: parentId || null // 🆕 NULL 表示顶级分组
|
||||
};
|
||||
|
||||
try {
|
||||
// 根据是否有ID决定是创建还是更新
|
||||
let response;
|
||||
if (id) {
|
||||
response = await updateEvaluationPointGroup(id, saveData, frontendJWT);
|
||||
} else {
|
||||
response = await createEvaluationPointGroup(saveData, frontendJWT);
|
||||
}
|
||||
|
||||
// 处理API响应
|
||||
if (response.error) {
|
||||
console.error("保存分组失败:", response.error);
|
||||
return Response.json({
|
||||
success: false,
|
||||
errors: {
|
||||
general: response.error
|
||||
},
|
||||
values: Object.fromEntries(formData) as Record<string, string>
|
||||
});
|
||||
}
|
||||
|
||||
// 保存成功,重定向到列表页
|
||||
toastService.success("保存成功");
|
||||
return redirect("/rule-groups");
|
||||
} catch (error) {
|
||||
console.error("保存分组失败:", error);
|
||||
return Response.json({
|
||||
success: false,
|
||||
errors: {
|
||||
general: error instanceof Error ? error.message : "保存分组失败,请稍后重试"
|
||||
},
|
||||
values: Object.fromEntries(formData) as Record<string, string>
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 页面组件
|
||||
export default function RuleGroupNew() {
|
||||
// 所有Hooks必须在组件顶部无条件调用
|
||||
const data = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<typeof action>();
|
||||
const navigation = useNavigation();
|
||||
const isSubmitting = navigation.state === "submitting";
|
||||
|
||||
// ✅ Use permission Hook
|
||||
const { canCreate, canUpdate } = usePermission();
|
||||
const canCreateGroup = canCreate('evaluation_group');
|
||||
const canUpdateGroup = canUpdate('evaluation_group');
|
||||
|
||||
// 解构数据
|
||||
const { group, parentGroups, isEdit, error } = data;
|
||||
|
||||
// ✅ 根据当前操作类型判断权限
|
||||
const hasEditPermission = isEdit ? canUpdateGroup : canCreateGroup;
|
||||
const isReadOnly = !hasEditPermission;
|
||||
|
||||
// 表单状态管理 - 使用受控组件
|
||||
const [formValues, setFormValues] = useState<{
|
||||
groupType: "primary" | "secondary";
|
||||
name: string;
|
||||
code: string;
|
||||
parentId: string;
|
||||
description: string;
|
||||
status: string;
|
||||
}>({
|
||||
groupType: group?.parentId ? "secondary" : "primary",
|
||||
name: group?.name || "",
|
||||
code: group?.code || "",
|
||||
parentId: group?.parentId || "",
|
||||
description: group?.description || "",
|
||||
status: group?.status || "active",
|
||||
});
|
||||
|
||||
// 表单验证错误状态
|
||||
const [formErrors, setFormErrors] = useState<{
|
||||
name?: string;
|
||||
code?: string;
|
||||
parentId?: string;
|
||||
general?: string;
|
||||
}>({});
|
||||
|
||||
// 🆕 编码唯一性验证状态
|
||||
const [codeValidating, setCodeValidating] = useState(false);
|
||||
const [codeValidationTimer, setCodeValidationTimer] = useState<NodeJS.Timeout | null>(null);
|
||||
|
||||
// 表单引用
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
// 字段是否被触摸过(用于确定何时显示错误)
|
||||
const [touchedFields, setTouchedFields] = useState<{
|
||||
name: boolean;
|
||||
code: boolean;
|
||||
parentId: boolean;
|
||||
}>({
|
||||
name: false,
|
||||
code: false,
|
||||
parentId: false
|
||||
});
|
||||
|
||||
// ✅ 页面加载时检查权限并提示(仅在只读模式下提示)
|
||||
// useEffect(() => {
|
||||
// console.log("权限",canCreateGroup,canUpdateGroup)
|
||||
// if (isReadOnly) {
|
||||
// if (isEdit) {
|
||||
// toastService.info('当前为查看模式,您没有编辑权限');
|
||||
// } else {
|
||||
// toastService.warning('您没有创建分组的权限');
|
||||
// }
|
||||
// }
|
||||
// }, [isReadOnly, isEdit]);
|
||||
|
||||
// 从 actionData 初始化表单错误
|
||||
useEffect(() => {
|
||||
if (actionData?.errors) {
|
||||
setFormErrors(actionData.errors);
|
||||
// ✅ 如果有通用错误,使用 toast 显示
|
||||
if (actionData.errors.general) {
|
||||
toastService.error(actionData.errors.general);
|
||||
}
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
// 根据加载的组数据初始化表单
|
||||
useEffect(() => {
|
||||
if (group) {
|
||||
setFormValues({
|
||||
groupType: group.parentId ? "secondary" : "primary",
|
||||
name: group.name,
|
||||
code: group.code,
|
||||
parentId: group.parentId || "",
|
||||
description: group.description || "",
|
||||
status: group.status
|
||||
});
|
||||
}
|
||||
}, [group]);
|
||||
|
||||
// 🆕 异步验证编码唯一性
|
||||
const validateCodeUnique = async (code: string): Promise<string> => {
|
||||
if (!code || code.trim() === "") {
|
||||
return "";
|
||||
}
|
||||
|
||||
try {
|
||||
setCodeValidating(true);
|
||||
const response = await getEvaluationPointGroups({
|
||||
code: code.trim(),
|
||||
pageSize: 10,
|
||||
token: data.frontendJWT
|
||||
}, data.frontendJWT);
|
||||
|
||||
if (response.error) {
|
||||
console.error("验证编码唯一性失败:", response.error);
|
||||
return ""; // 验证失败时不显示错误,避免干扰用户
|
||||
}
|
||||
|
||||
if (response.data && response.data.length > 0) {
|
||||
// 在编辑模式下,排除当前分组自身
|
||||
const isDuplicate = response.data.some(g =>
|
||||
g.id !== group?.id && g.code === code.trim()
|
||||
);
|
||||
if (isDuplicate) {
|
||||
return "该编码已被使用,请使用其他编码";
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
} catch (error) {
|
||||
console.error("验证编码唯一性出错:", error);
|
||||
return "";
|
||||
} finally {
|
||||
setCodeValidating(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 验证表单字段
|
||||
const validateField = (field: string, value: string) => {
|
||||
switch (field) {
|
||||
case 'name':
|
||||
return value.trim() === "" ? "分组名称不能为空" : "";
|
||||
case 'code':
|
||||
if (value.trim() === "") {
|
||||
return "分组编码不能为空";
|
||||
} else if (!/^[a-zA-Z0-9-_]+$/.test(value)) {
|
||||
return "分组编码只能包含字母、数字、连字符和下划线";
|
||||
}
|
||||
return "";
|
||||
case 'parentId':
|
||||
return formValues.groupType === "secondary" && value.trim() === ""
|
||||
? "请选择上级分组"
|
||||
: "";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
// 处理字段改变
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
|
||||
const { name, value } = e.target;
|
||||
|
||||
setFormValues(prev => ({
|
||||
...prev,
|
||||
[name]: value
|
||||
}));
|
||||
|
||||
// 标记字段为已触摸
|
||||
if (['name', 'code', 'parentId'].includes(name)) {
|
||||
setTouchedFields(prev => ({
|
||||
...prev,
|
||||
[name]: true
|
||||
}));
|
||||
}
|
||||
|
||||
// 实时验证
|
||||
const error = validateField(name, value);
|
||||
setFormErrors(prev => ({
|
||||
...prev,
|
||||
[name]: error
|
||||
}));
|
||||
|
||||
// 🆕 编码字段特殊处理:异步验证唯一性(防抖处理)
|
||||
if (name === 'code' && !error) {
|
||||
// 清除之前的定时器
|
||||
if (codeValidationTimer) {
|
||||
clearTimeout(codeValidationTimer);
|
||||
}
|
||||
|
||||
// 设置新的定时器,500ms后执行验证
|
||||
const timer = setTimeout(async () => {
|
||||
const uniqueError = await validateCodeUnique(value);
|
||||
if (uniqueError) {
|
||||
setFormErrors(prev => ({
|
||||
...prev,
|
||||
code: uniqueError
|
||||
}));
|
||||
}
|
||||
}, 500);
|
||||
|
||||
setCodeValidationTimer(timer);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理分组类型更改
|
||||
const handleGroupTypeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const value = e.target.value as "primary" | "secondary";
|
||||
|
||||
setFormValues(prev => ({
|
||||
...prev,
|
||||
groupType: value
|
||||
}));
|
||||
|
||||
// 如果切换为一级分组,清除父分组错误
|
||||
if (value === "primary") {
|
||||
setFormErrors(prev => ({
|
||||
...prev,
|
||||
parentId: ""
|
||||
}));
|
||||
} else if (value === "secondary" && touchedFields.parentId) {
|
||||
// 如果切换为二级分组,且父分组字段已被触摸,重新验证
|
||||
const error = validateField('parentId', formValues.parentId);
|
||||
setFormErrors(prev => ({
|
||||
...prev,
|
||||
parentId: error
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
// 处理表单提交前验证
|
||||
const handleBeforeSubmit = (e: React.FormEvent) => {
|
||||
// ✅ Runtime permission check
|
||||
if (isEdit && !canUpdateGroup) {
|
||||
e.preventDefault();
|
||||
toastService.warning('您没有修改权限,无法保存更改');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isEdit && !canCreateGroup) {
|
||||
e.preventDefault();
|
||||
toastService.warning('您没有创建权限,无法新增分组');
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果是只读模式,阻止提交
|
||||
if (isReadOnly) {
|
||||
e.preventDefault();
|
||||
toastService.info('当前为只读模式,无法提交');
|
||||
return;
|
||||
}
|
||||
|
||||
// 标记所有字段为已触摸
|
||||
setTouchedFields({
|
||||
name: true,
|
||||
code: true,
|
||||
parentId: true
|
||||
});
|
||||
|
||||
// 验证所有字段
|
||||
const errors = {
|
||||
name: validateField('name', formValues.name),
|
||||
code: validateField('code', formValues.code),
|
||||
parentId: validateField('parentId', formValues.parentId)
|
||||
};
|
||||
|
||||
setFormErrors(errors);
|
||||
|
||||
// 如果有错误,阻止提交并提示
|
||||
const hasErrors = errors.name || errors.code || (formValues.groupType === "secondary" && errors.parentId);
|
||||
if (hasErrors) {
|
||||
e.preventDefault();
|
||||
// ✅ 收集所有错误信息并提示
|
||||
const errorMessages = [];
|
||||
if (errors.name) errorMessages.push(errors.name);
|
||||
if (errors.code) errorMessages.push(errors.code);
|
||||
if (errors.parentId) errorMessages.push(errors.parentId);
|
||||
|
||||
toastService.error(`表单验证失败:${errorMessages[0]}`);
|
||||
}
|
||||
};
|
||||
|
||||
// 如果加载数据时出错,显示错误信息
|
||||
if (error) {
|
||||
return (
|
||||
<div className="error-container">
|
||||
<h1>加载出错</h1>
|
||||
<p>{error}</p>
|
||||
<Button type="default" to="/rule-groups">
|
||||
<i className="ri-arrow-left-line"></i> 返回列表
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rule-group-new-page">
|
||||
{/* 页面头部 */}
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1 className="page-title">{isEdit ? (isReadOnly ? "查看评查点分组" : "编辑评查点分组") : "新增评查点分组"}</h1>
|
||||
<p className="page-subtitle">创建新的评查点分组,用于组织管理评查点</p>
|
||||
</div>
|
||||
<div className="header-actions">
|
||||
<Button
|
||||
type="default"
|
||||
to="/rule-groups"
|
||||
className="mr-3"
|
||||
>
|
||||
<i className="ri-arrow-left-line"></i> 返回列表
|
||||
</Button>
|
||||
{/* ✅ 仅在有对应权限时显示保存按钮 */}
|
||||
{hasEditPermission && (
|
||||
<Button
|
||||
type="primary"
|
||||
form="group-form"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<i className="ri-save-line"></i> {isSubmitting ? '保存中...' : '保存分组'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-container">
|
||||
{/* 提示信息 */}
|
||||
<div className="info-message">
|
||||
<i className="ri-information-line"></i>
|
||||
<p>评查点分组用于对评查点进行分类管理,合理的分组结构有助于更高效地组织和查找评查点。</p>
|
||||
</div>
|
||||
|
||||
{/* 错误提示 */}
|
||||
{formErrors.general && (
|
||||
<div className="general-error">
|
||||
<i className="ri-error-warning-line mr-2"></i>
|
||||
{formErrors.general}
|
||||
<div className="rule-group-form-page">
|
||||
<Card className="card p-6 max-w-3xl mx-auto mt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-amber-50 text-amber-700 text-2xl mx-auto">
|
||||
<i className="ri-route-line"></i>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 表单 */}
|
||||
<Form method="post" id="group-form" ref={formRef} onSubmit={handleBeforeSubmit}>
|
||||
{/* 如果是编辑模式,添加ID */}
|
||||
{group?.id && <input type="hidden" name="id" value={group.id} />}
|
||||
|
||||
{/* 基本信息区域 */}
|
||||
<Card className="form-section">
|
||||
<div className="form-section-header">
|
||||
<i className="ri-file-info-line"></i>
|
||||
<h3>基本信息</h3>
|
||||
</div>
|
||||
<div className="form-section-body">
|
||||
{/* 分组类型选择 */}
|
||||
<div className="form-group">
|
||||
<legend className="form-label" id="groupTypeLabel">
|
||||
分组类型 <span className="required-mark">*</span>
|
||||
</legend>
|
||||
<div className="radio-group" role="radiogroup" aria-labelledby="groupTypeLabel">
|
||||
<label className="radio-item" htmlFor="groupType-primary">
|
||||
<input
|
||||
type="radio"
|
||||
id="groupType-primary"
|
||||
name="groupType"
|
||||
className="radio-input"
|
||||
value="primary"
|
||||
checked={formValues.groupType === "primary"}
|
||||
onChange={handleGroupTypeChange}
|
||||
disabled={isReadOnly}
|
||||
/>
|
||||
<span>一级分组</span>
|
||||
</label>
|
||||
<label className="radio-item" htmlFor="groupType-secondary">
|
||||
<input
|
||||
type="radio"
|
||||
id="groupType-secondary"
|
||||
name="groupType"
|
||||
className="radio-input"
|
||||
value="secondary"
|
||||
checked={formValues.groupType === "secondary"}
|
||||
onChange={handleGroupTypeChange}
|
||||
disabled={isReadOnly}
|
||||
/>
|
||||
<span>二级分组</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="form-tip">一级分组作为顶层分类,二级分组需要选择所属的一级分组</div>
|
||||
</div>
|
||||
|
||||
{/* 上级分组选择 */}
|
||||
{formValues.groupType === "secondary" && (
|
||||
<div className="form-group">
|
||||
<label htmlFor="parentId" className="form-label">
|
||||
上级分组 <span className="required-mark">*</span>
|
||||
</label>
|
||||
<select
|
||||
id="parentId"
|
||||
name="parentId"
|
||||
className={`form-select ${touchedFields.parentId && formErrors.parentId ? 'error' : ''}`}
|
||||
value={formValues.parentId}
|
||||
onChange={handleChange}
|
||||
disabled={isReadOnly}
|
||||
>
|
||||
<option value="">请选择上级分组</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>
|
||||
{touchedFields.parentId && formErrors.parentId && (
|
||||
<div className="form-error">{formErrors.parentId}</div>
|
||||
)}
|
||||
<div className="form-tip">选择此分组所属的上级分组</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 分组编码和名称 */}
|
||||
<div className="form-row">
|
||||
<div className="form-col">
|
||||
<div className="form-group">
|
||||
<label htmlFor="code" className="form-label">
|
||||
分组编码 <span className="required-mark">*</span>
|
||||
{codeValidating && <span className="ml-2 text-sm text-gray-500">验证中...</span>}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="code"
|
||||
name="code"
|
||||
className={`form-input ${touchedFields.code && formErrors.code ? 'error' : ''}`}
|
||||
value={formValues.code}
|
||||
onChange={handleChange}
|
||||
placeholder="请输入分组编码,如contract-base"
|
||||
readOnly={isReadOnly}
|
||||
/>
|
||||
{touchedFields.code && formErrors.code && (
|
||||
<div className="form-error">{formErrors.code}</div>
|
||||
)}
|
||||
<div className="form-tip">编码只能包含字母、数字、连字符和下划线,且必须唯一</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-col">
|
||||
<div className="form-group">
|
||||
<label htmlFor="name" className="form-label">
|
||||
分组名称 <span className="required-mark">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="name"
|
||||
name="name"
|
||||
className={`form-input ${touchedFields.name && formErrors.name ? 'error' : ''}`}
|
||||
value={formValues.name}
|
||||
onChange={handleChange}
|
||||
placeholder="请输入分组名称,如合同基本要素检查"
|
||||
readOnly={isReadOnly}
|
||||
/>
|
||||
{touchedFields.name && formErrors.name && (
|
||||
<div className="form-error">{formErrors.name}</div>
|
||||
)}
|
||||
<div className="form-tip">请使用简洁明了的名称,不超过30个字符</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* 详细配置区域 */}
|
||||
<Card className="form-section">
|
||||
<div className="form-section-header">
|
||||
<i className="ri-settings-4-line"></i>
|
||||
<h3>详细配置</h3>
|
||||
</div>
|
||||
<div className="form-section-body">
|
||||
{/* 分组描述 */}
|
||||
<div className="form-group">
|
||||
<label htmlFor="description" className="form-label">分组描述</label>
|
||||
<textarea
|
||||
id="description"
|
||||
name="description"
|
||||
className="form-textarea"
|
||||
value={formValues.description}
|
||||
onChange={handleChange}
|
||||
placeholder="请输入分组描述,包括适用场景、分组目的等"
|
||||
readOnly={isReadOnly}
|
||||
></textarea>
|
||||
<div className="form-tip">详细描述有助于其他用户了解该分组的用途</div>
|
||||
</div>
|
||||
|
||||
{/* 状态 */}
|
||||
<div className="form-group" style={{ maxWidth: "400px" }}>
|
||||
<label htmlFor="status" className="form-label">状态</label>
|
||||
<select
|
||||
id="status"
|
||||
name="status"
|
||||
className="form-select"
|
||||
value={formValues.status}
|
||||
onChange={handleChange}
|
||||
disabled={isReadOnly}
|
||||
>
|
||||
<option value="active">启用</option>
|
||||
<option value="inactive">禁用</option>
|
||||
</select>
|
||||
<div className="form-tip">禁用状态的分组及其下的评查点将不会参与评查</div>
|
||||
</div>
|
||||
|
||||
{/* 排序 */}
|
||||
<div className="form-group hidden" style={{ maxWidth: "400px" }}>
|
||||
<label htmlFor="sortOrder" className="form-label">排序</label>
|
||||
<input
|
||||
type="number"
|
||||
id="sortOrder"
|
||||
name="sortOrder"
|
||||
className="form-input"
|
||||
defaultValue={group?.sortOrder?.toString() || "0"}
|
||||
placeholder="请输入排序值,数字越小排序越靠前"
|
||||
min="0"
|
||||
/>
|
||||
<div className="form-tip">用于设置分组在列表中的显示顺序,默认为0</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</Form>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="page-title">旧分组编辑入口已下线</h1>
|
||||
<p className="page-subtitle">
|
||||
`/rule-groups/new` 原来对应的是老评查点分组维护语义,当前系统已改为新规则导航视图,
|
||||
不再在这里维护老分组树。
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-[rgba(11,109,77,0.05)] border border-[rgba(11,109,77,0.12)] rounded-2xl p-4 text-left text-sm leading-7 text-slate-600">
|
||||
<p>现在请改用以下入口:</p>
|
||||
<p>1. `规则导航`:查看 入口模块 → 文档类型 → 规则集 / 版本</p>
|
||||
<p>2. `文档类型管理`:调整文档类型与规则集绑定关系</p>
|
||||
<p>3. `规则管理`:维护规则集版本与 YAML 内容</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-center gap-3 pt-2">
|
||||
<Link to={redirectTarget}>
|
||||
<Button type="primary">前往规则导航</Button>
|
||||
</Link>
|
||||
<Link to="/document-types">
|
||||
<Button type="default">前往文档类型管理</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Outlet } from "@remix-run/react";
|
||||
|
||||
/**
|
||||
* 评查点分组管理 - 父级路由
|
||||
* 规则导航 - 父级路由
|
||||
* 仅作为嵌套路由的容器,不包含具体内容
|
||||
*/
|
||||
export const handle = {
|
||||
breadcrumb: "评查点分组"
|
||||
breadcrumb: "规则导航"
|
||||
}
|
||||
export default function RuleGroups() {
|
||||
return <Outlet />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,6 +349,8 @@ export default function RulesIndex() {
|
||||
const [filteredTotalCount, setFilteredTotalCount] = useState<number>(initialTotalCount);
|
||||
const [ruleTypes, setRuleTypes] = useState<ApiRuleType[]>(initialRuleTypes);
|
||||
const [attributeTypes, setAttributeTypes] = useState<Array<{ code: string; label: string }>>([]);
|
||||
const [selectedModuleName, setSelectedModuleName] = useState('');
|
||||
const [moduleScopeReady, setModuleScopeReady] = useState(false);
|
||||
|
||||
// 添加一个状态来跟踪是否执行了删除操作
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
@@ -398,7 +400,7 @@ export default function RulesIndex() {
|
||||
// 🔑 从 sessionStorage 获取 documentTypeIds
|
||||
const typeIdsStr = typeof window !== 'undefined' ? sessionStorage.getItem('documentTypeIds') : null;
|
||||
const documentTypeIds = typeIdsStr ? JSON.parse(typeIdsStr) : null;
|
||||
const selectedModuleName = typeof window !== 'undefined'
|
||||
const currentModuleName = typeof window !== 'undefined'
|
||||
? sessionStorage.getItem('selectedModuleName') || ''
|
||||
: '';
|
||||
|
||||
@@ -456,7 +458,7 @@ export default function RulesIndex() {
|
||||
let effectiveAttributeType = searchParams.get('documentAttributeType') || undefined;
|
||||
const presetScopedAttributeTypes = resolveScopedSubtypeOptions({
|
||||
documentTypeIds,
|
||||
selectedModuleName,
|
||||
selectedModuleName: currentModuleName,
|
||||
ruleTypeName: ruleTypeNameParam,
|
||||
apiOptions: apiAttributeTypes,
|
||||
ruleOptions: []
|
||||
@@ -497,7 +499,7 @@ export default function RulesIndex() {
|
||||
).map(value => ({ code: value, label: value }));
|
||||
const scopedAttributeTypes = resolveScopedSubtypeOptions({
|
||||
documentTypeIds,
|
||||
selectedModuleName,
|
||||
selectedModuleName: currentModuleName,
|
||||
ruleTypeName: ruleTypeNameParam,
|
||||
apiOptions: apiAttributeTypes,
|
||||
ruleOptions: ruleAttributeTypes
|
||||
@@ -656,6 +658,8 @@ export default function RulesIndex() {
|
||||
const typeIdsStr = sessionStorage.getItem('documentTypeIds');
|
||||
const documentTypeIds = typeIdsStr ? JSON.parse(typeIdsStr) : null;
|
||||
console.log("📋 组件挂载,从 sessionStorage 获取 documentTypeIds:", documentTypeIds);
|
||||
setSelectedModuleName(sessionStorage.getItem('selectedModuleName') || '');
|
||||
setModuleScopeReady(true);
|
||||
|
||||
// 如果有 documentTypeIds,加载数据
|
||||
if (documentTypeIds && documentTypeIds.length > 0) {
|
||||
@@ -667,6 +671,7 @@ export default function RulesIndex() {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取 sessionStorage 中的 documentTypeIds 失败:', error);
|
||||
setModuleScopeReady(true);
|
||||
}
|
||||
}, [initialLoad, fetchData]);
|
||||
|
||||
@@ -1118,7 +1123,14 @@ export default function RulesIndex() {
|
||||
{/* 页面头部 */}
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<div className="flex items-center">
|
||||
<h2 className="text-xl font-medium">评查点管理</h2>
|
||||
<div>
|
||||
<h2 className="text-xl font-medium">评查点管理</h2>
|
||||
<p className="mt-1 text-sm text-gray-500">
|
||||
{selectedModuleName
|
||||
? `当前仅展示“${selectedModuleName}”入口关联文档类型的规则点。`
|
||||
: '请先从首页进入具体入口模块,再查看该入口对应的规则点。'}
|
||||
</p>
|
||||
</div>
|
||||
{loading ? (
|
||||
<div className="flex items-center ml-4 bg-white px-3 py-1 rounded-md">
|
||||
<NumberSkeleton className="ml-1" />
|
||||
@@ -1171,6 +1183,20 @@ export default function RulesIndex() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{moduleScopeReady && !selectedModuleName && (
|
||||
<Card className="ant-card mb-4 border-amber-200 bg-amber-50">
|
||||
<div className="flex items-start gap-3 text-amber-900">
|
||||
<i className="ri-information-line text-lg mt-0.5"></i>
|
||||
<div>
|
||||
<div className="font-medium">当前未绑定业务入口上下文</div>
|
||||
<div className="text-sm mt-1">
|
||||
评查点列表按入口模块显示对应文档类型规则。请先从首页进入具体入口,再查看这里。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 筛选区域 */}
|
||||
<FilterPanel className="px-3 py-3" noActionDivider={true}
|
||||
|
||||
+52
-40
@@ -58,7 +58,7 @@ import {
|
||||
type EvaluationPointData
|
||||
} from '~/api/evaluation_points/rules';
|
||||
import { getRulesList } from '~/api/evaluation_points/rules';
|
||||
import { postgrestGet } from '~/api/postgrest-client';
|
||||
import { getEvaluationPointGroupsByDocumentTypes, type RuleGroup as ApiRuleGroupTree } from '~/api/evaluation_points/rule-groups';
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
@@ -280,28 +280,6 @@ export default function RuleNew() {
|
||||
setInstanceKey(`new_${Date.now()}`);
|
||||
}, []);
|
||||
|
||||
|
||||
/**
|
||||
* 从API响应中提取数据
|
||||
* @param responseData - API响应数据
|
||||
* @returns 提取的数据或null
|
||||
*/
|
||||
function extractApiData<T>(responseData: unknown): T | null {
|
||||
if (!responseData) return null;
|
||||
|
||||
// 格式1: { code: number, msg: string, data: T }
|
||||
if (typeof responseData === 'object' && responseData !== null &&
|
||||
'code' in responseData &&
|
||||
'data' in responseData &&
|
||||
(responseData as { data: unknown }).data) {
|
||||
return (responseData as { data: T }).data;
|
||||
}
|
||||
|
||||
// 格式2: 直接是数据对象
|
||||
return responseData as T;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取评查点数据
|
||||
* 编辑模式下从API获取指定ID的评查点数据
|
||||
@@ -386,32 +364,66 @@ export default function RuleNew() {
|
||||
*/
|
||||
const fetchEvaluationPointGroups = useCallback(async () => {
|
||||
try {
|
||||
// console.log("🔍 [fetchEvaluationPointGroups] 开始获取评查点组数据");
|
||||
const response = await postgrestGet('/api/postgrest/proxy/evaluation_point_groups', { token: frontendJWT });
|
||||
const storedIds = typeof window !== 'undefined' ? sessionStorage.getItem('documentTypeIds') : null;
|
||||
if (!storedIds) {
|
||||
setEvaluationPointGroups([]);
|
||||
return;
|
||||
}
|
||||
|
||||
// console.log("🔍 [fetchEvaluationPointGroups] API响应:", response);
|
||||
const parsedIds = JSON.parse(storedIds);
|
||||
if (!Array.isArray(parsedIds) || parsedIds.length === 0) {
|
||||
setEvaluationPointGroups([]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.data) {
|
||||
// 使用 extractApiData 提取数据(处理可能的包装格式)
|
||||
const extractedData = extractApiData<EvaluationPointGroup[]>(response.data);
|
||||
// console.log("🔍 [fetchEvaluationPointGroups] 提取后的数据:", extractedData);
|
||||
const documentTypeIds = parsedIds
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isFinite(item) && item > 0);
|
||||
|
||||
if (extractedData && Array.isArray(extractedData) && extractedData.length > 0) {
|
||||
setEvaluationPointGroups(extractedData);
|
||||
// console.log(`✅ [fetchEvaluationPointGroups] 成功加载 ${extractedData.length} 个评查点组`);
|
||||
} else {
|
||||
console.warn("⚠️ [fetchEvaluationPointGroups] 提取的数据为空或格式不正确");
|
||||
setEvaluationPointGroups([]);
|
||||
}
|
||||
} else if (response.error) {
|
||||
const response = await getEvaluationPointGroupsByDocumentTypes(documentTypeIds, frontendJWT);
|
||||
if (response.error) {
|
||||
console.error('❌ [fetchEvaluationPointGroups] API返回错误:', response.error);
|
||||
setEvaluationPointGroups([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const flattenGroups = (groups: ApiRuleGroupTree[]): EvaluationPointGroup[] => {
|
||||
const items: EvaluationPointGroup[] = [];
|
||||
groups.forEach(group => {
|
||||
items.push({
|
||||
id: Number(group.id),
|
||||
pid: group.pid === '0' ? 0 : Number(group.pid),
|
||||
code: group.code || '',
|
||||
name: group.name,
|
||||
description: group.description,
|
||||
is_enabled: group.is_enabled,
|
||||
created_at: group.createdAt || '',
|
||||
updated_at: group.createdAt || ''
|
||||
});
|
||||
|
||||
if (group.children && group.children.length > 0) {
|
||||
group.children.forEach(child => {
|
||||
items.push({
|
||||
id: Number(child.id),
|
||||
pid: child.pid === '0' ? 0 : Number(child.pid),
|
||||
code: child.code || '',
|
||||
name: child.name,
|
||||
description: child.description,
|
||||
is_enabled: child.is_enabled,
|
||||
created_at: child.createdAt || '',
|
||||
updated_at: child.createdAt || ''
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
return items;
|
||||
};
|
||||
|
||||
setEvaluationPointGroups(flattenGroups(response.data || []));
|
||||
} catch (error) {
|
||||
console.error('❌ [fetchEvaluationPointGroups] 获取评查点组数据失败:', error);
|
||||
setEvaluationPointGroups([]);
|
||||
// 显示错误提示但不影响应用继续使用
|
||||
toastService.error(`获取评查点组数据失败: ${error instanceof Error ? error.message : '未知错误'}\n将使用默认数据`);
|
||||
toastService.error(`获取评查点组数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
|
||||
}
|
||||
}, [frontendJWT]);
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { redirect, type LoaderFunctionArgs, type MetaFunction } from "@remix-run/node";
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: "规则管理 - 中国烟草AI合同及卷宗审核系统" },
|
||||
{
|
||||
name: "rules-sets",
|
||||
content: "兼容旧版规则管理入口,自动跳转到新版规则维护页"
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
export const handle = {
|
||||
hideBreadcrumb: true,
|
||||
};
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const url = new URL(request.url);
|
||||
const query = url.searchParams.toString();
|
||||
throw redirect(query ? `/rulesTest/list?${query}` : "/rulesTest/list");
|
||||
}
|
||||
|
||||
export default function RulesSetsRedirect() {
|
||||
return null;
|
||||
}
|
||||
+16
-6
@@ -1,13 +1,12 @@
|
||||
import { Outlet } from "@remix-run/react";
|
||||
import { type MetaFunction } from "@remix-run/node";
|
||||
|
||||
import { redirect, type LoaderFunctionArgs, type MetaFunction } from "@remix-run/node";
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return [
|
||||
{ title: "评查规则管理 - 中国烟草AI合同及卷宗审核系统" },
|
||||
{
|
||||
name: "rules",
|
||||
content: "评查规则管理模块,包括评查点列表、创建和编辑功能"
|
||||
{
|
||||
name: "rules",
|
||||
content: "评查规则管理模块,包括评查点列表、创建和编辑功能"
|
||||
}
|
||||
];
|
||||
};
|
||||
@@ -17,9 +16,20 @@ export const handle = {
|
||||
to: "/rulesTest/list" // 新版规则维护入口;旧版可从新版页面内返回
|
||||
};
|
||||
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (url.pathname === '/rules') {
|
||||
const query = url.searchParams.toString();
|
||||
throw redirect(query ? `/rulesTest/list?${query}` : '/rulesTest/list');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规则管理路由布局
|
||||
*/
|
||||
export default function RulesLayout() {
|
||||
export default function RulesLayout() {
|
||||
return <Outlet />;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { type LoaderFunctionArgs, type MetaFunction } from '@remix-run/node';
|
||||
import { Link, useLoaderData } from '@remix-run/react';
|
||||
import { json, type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction } from '@remix-run/node';
|
||||
import { Link, useFetcher, useLoaderData, useRevalidator } from '@remix-run/react';
|
||||
import type React from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Button } from '~/components/ui/Button';
|
||||
import { Card } from '~/components/ui/Card';
|
||||
import { Table } from '~/components/ui/Table';
|
||||
import { Tag, type TagColor } from '~/components/ui/Tag';
|
||||
import { loadRuleYamlPack, loadRuleYamlPacks, type RuleSummary, type RuleYamlPack } from '~/utils/rules-yaml-mock.server';
|
||||
import { buildRuleYamlPreview, collectDependencyOptions, getDefaultExpandedDependencyGroups, type DependencyOption, type EditableRuleConfig, type ValidationIssue } from '~/utils/rules-config-editor';
|
||||
import { getUserSession } from '~/api/login/auth.server';
|
||||
import { API_BASE_URL } from '~/config/api-config';
|
||||
import { loadRuleConfigPack, loadRuleConfigPacks, loadRuleConfigVersions, type RuleVersionItem } from '~/utils/rules-config-packs.server';
|
||||
import { buildRuleYamlPreview, buildYamlPreview, collectDependencyOptions, getDefaultExpandedDependencyGroups, validateEditableRuleConfig, type DependencyOption, type EditableRuleConfig, type ValidationIssue } from '~/utils/rules-config-editor';
|
||||
import type { RuleSummary, RuleYamlPack } from '~/utils/rules-yaml-mock.server';
|
||||
import styles from '~/styles/pages/rules_test.css?url';
|
||||
|
||||
export const links = () => [
|
||||
@@ -21,6 +24,15 @@ export const meta: MetaFunction = () => [
|
||||
type LoaderData = {
|
||||
pack: RuleYamlPack;
|
||||
requestedRuleId: string;
|
||||
versions: RuleVersionItem[];
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success: boolean;
|
||||
message: string;
|
||||
intent: 'save' | 'publish' | 'rollback';
|
||||
versionId?: number;
|
||||
versionNo?: string;
|
||||
};
|
||||
|
||||
type EditorState = { kind: 'rule'; mode: 'create' | 'edit'; id?: string } | null;
|
||||
@@ -304,18 +316,96 @@ export async function loader({ request }: LoaderFunctionArgs) {
|
||||
const url = new URL(request.url);
|
||||
const packId = url.searchParams.get('packId') || url.searchParams.get('id') || '';
|
||||
const requestedRuleId = url.searchParams.get('ruleId') || '';
|
||||
const packs = await loadRuleYamlPacks();
|
||||
const pack = (packId ? await loadRuleYamlPack(packId) : undefined) || packs[0];
|
||||
const packs = await loadRuleConfigPacks(request);
|
||||
const pack = (packId ? await loadRuleConfigPack(request, packId) : undefined) || packs[0];
|
||||
|
||||
if (!pack) {
|
||||
throw new Response('未找到 YAML 配置', { status: 404 });
|
||||
}
|
||||
|
||||
return Response.json({ pack, requestedRuleId } satisfies LoaderData);
|
||||
const versions = await loadRuleConfigVersions(request, pack.metadata.typeId || '');
|
||||
|
||||
return Response.json({ pack, requestedRuleId, versions } satisfies LoaderData);
|
||||
}
|
||||
|
||||
export async function action({ request }: ActionFunctionArgs) {
|
||||
const { frontendJWT, userInfo } = await getUserSession(request);
|
||||
if (!frontendJWT) {
|
||||
return json<ActionData>({ success: false, intent: 'save', message: '登录已失效,请重新登录后再保存。' }, { status: 401 });
|
||||
}
|
||||
|
||||
const formData = await request.formData();
|
||||
const intent = String(formData.get('intent') || 'save').trim() as ActionData['intent'];
|
||||
const ruleType = String(formData.get('ruleType') || '').trim();
|
||||
const yamlText = String(formData.get('yamlText') || '');
|
||||
const changeNote = String(formData.get('changeNote') || '').trim() || 'rulesTest.detail 保存评查点草稿';
|
||||
const versionId = Number(formData.get('versionId') || 0);
|
||||
|
||||
if (!ruleType) {
|
||||
return json<ActionData>({ success: false, intent, message: '当前规则类型缺失,无法保存。' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (intent === 'save' && !yamlText.trim()) {
|
||||
return json<ActionData>({ success: false, intent, message: '当前 YAML 内容为空,无法保存。' }, { status: 400 });
|
||||
}
|
||||
|
||||
if ((intent === 'publish' || intent === 'rollback') && (!Number.isFinite(versionId) || versionId <= 0)) {
|
||||
return json<ActionData>({ success: false, intent, message: '目标版本缺失,无法继续操作。' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const apiPath = intent === 'save'
|
||||
? `/api/rule-sets/${encodeURIComponent(ruleType)}/versions`
|
||||
: `/api/rule-sets/${encodeURIComponent(ruleType)}/${intent}`;
|
||||
const requestBody = intent === 'save'
|
||||
? {
|
||||
yamlText,
|
||||
changeNote,
|
||||
editorUserId: userInfo?.user_id ? Number(userInfo.user_id) : undefined,
|
||||
}
|
||||
: {
|
||||
versionId,
|
||||
operatorUserId: userInfo?.user_id ? Number(userInfo.user_id) : undefined,
|
||||
};
|
||||
|
||||
const response = await fetch(`${API_BASE_URL}${apiPath}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${frontendJWT}`,
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
const payload = await response.json();
|
||||
const data = payload?.data ?? null;
|
||||
const message = String(payload?.message || payload?.msg || (response.ok ? '规则草稿保存成功' : '规则草稿保存失败'));
|
||||
|
||||
if (!response.ok || !data) {
|
||||
return json<ActionData>({ success: false, intent, message }, { status: response.status || 500 });
|
||||
}
|
||||
|
||||
return json<ActionData>({
|
||||
success: true,
|
||||
intent,
|
||||
message,
|
||||
versionId: Number(data.id),
|
||||
versionNo: String(data.versionNo || ''),
|
||||
});
|
||||
} catch (error) {
|
||||
return json<ActionData>({
|
||||
success: false,
|
||||
intent,
|
||||
message: error instanceof Error ? error.message : '规则草稿保存失败',
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export default function RulesTestDetail() {
|
||||
const { pack, requestedRuleId } = useLoaderData<typeof loader>() as LoaderData;
|
||||
const { pack, requestedRuleId, versions } = useLoaderData<typeof loader>() as LoaderData;
|
||||
const saveFetcher = useFetcher<ActionData>();
|
||||
const revalidator = useRevalidator();
|
||||
const initialRuleKey = requestedRuleId || ruleKey(pack.rules[0] || { id: '', ruleId: '' });
|
||||
const [rules, setRules] = useState<RuleSummary[]>(pack.rules);
|
||||
const [selectedRuleKey, setSelectedRuleKey] = useState(initialRuleKey);
|
||||
@@ -328,6 +418,8 @@ export default function RulesTestDetail() {
|
||||
const [showValidation, setShowValidation] = useState(false);
|
||||
const [showYamlPreview, setShowYamlPreview] = useState(false);
|
||||
const [draftSaved, setDraftSaved] = useState(false);
|
||||
const [saveMessage, setSaveMessage] = useState('');
|
||||
const [saveError, setSaveError] = useState('');
|
||||
const promptEditorRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -341,6 +433,8 @@ export default function RulesTestDetail() {
|
||||
setShowValidation(false);
|
||||
setShowYamlPreview(false);
|
||||
setDraftSaved(false);
|
||||
setSaveMessage('');
|
||||
setSaveError('');
|
||||
}, [pack.id, requestedRuleId]);
|
||||
|
||||
const currentRule = useMemo(() => {
|
||||
@@ -409,9 +503,53 @@ export default function RulesTestDetail() {
|
||||
}, [dialogDependencyOptions, dependencySelection]);
|
||||
const dependencyDialogEmptyText = dependencySearch.trim() ? '没有匹配的字段。' : '当前文档类型暂无可追加字段。';
|
||||
const hasErrors = validationIssues.some(issue => issue.severity === 'error');
|
||||
const configValidationIssues = useMemo(() => validateEditableRuleConfig(editableConfig), [editableConfig]);
|
||||
const hasConfigErrors = configValidationIssues.some(issue => issue.severity === 'error');
|
||||
const fullYamlText = useMemo(() => buildYamlPreview(editableConfig), [editableConfig]);
|
||||
const isSmartRuleDraft = ruleDraft.type === 'ai_rule' || ruleDraft.checkTypes.includes('ai');
|
||||
const isRuleGroupDraft = ruleDraft.type === 'rule_group';
|
||||
const rulesById = useMemo(() => new Map(rules.map(rule => [rule.ruleId || rule.id, rule])), [rules]);
|
||||
const saveButtonBusy = saveFetcher.state !== 'idle';
|
||||
const latestDraftVersion = useMemo(
|
||||
() => versions.find((item) => !['published', 'rollback'].includes(item.status)),
|
||||
[versions],
|
||||
);
|
||||
const rollbackTargetVersion = useMemo(
|
||||
() => versions.find((item) => ['published', 'rollback'].includes(item.status) && item.id !== pack.currentVersionId),
|
||||
[versions, pack.currentVersionId],
|
||||
);
|
||||
const currentResolvedVersion = useMemo(
|
||||
() => versions.find((item) => item.id === pack.currentVersionId || item.id === pack.fallbackVersionId) || null,
|
||||
[pack.currentVersionId, pack.fallbackVersionId, versions],
|
||||
);
|
||||
const versionStatusLabel = (status: string | undefined) => {
|
||||
const normalized = String(status || '').trim().toLowerCase();
|
||||
if (normalized === 'published') return '已发布';
|
||||
if (normalized === 'rollback') return '回滚版本';
|
||||
if (normalized === 'draft') return '草稿';
|
||||
if (normalized === 'deprecated') return '已废弃';
|
||||
return status || '-';
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!saveFetcher.data) return;
|
||||
if (saveFetcher.data.success) {
|
||||
setDraftSaved(saveFetcher.data.intent === 'save');
|
||||
setSaveError('');
|
||||
if (saveFetcher.data.intent === 'save') {
|
||||
setSaveMessage(saveFetcher.data.versionNo
|
||||
? `规则草稿已保存为版本 ${saveFetcher.data.versionNo}`
|
||||
: saveFetcher.data.message || '规则草稿已保存');
|
||||
} else {
|
||||
setSaveMessage(saveFetcher.data.message || (saveFetcher.data.intent === 'publish' ? '规则版本已发布' : '规则版本已回滚'));
|
||||
}
|
||||
revalidator.revalidate();
|
||||
return;
|
||||
}
|
||||
setDraftSaved(false);
|
||||
setSaveMessage('');
|
||||
setSaveError(saveFetcher.data.message || '规则草稿保存失败');
|
||||
}, [revalidator, saveFetcher.data]);
|
||||
|
||||
const openRuleEditor = (rule?: RuleSummary) => {
|
||||
setRuleDraft(rule ? { ...rule } : emptyRuleDraft(ruleGroups[0]));
|
||||
@@ -493,10 +631,56 @@ export default function RulesTestDetail() {
|
||||
? current.map(rule => rule.id === editor.id ? normalizedRule : rule)
|
||||
: [...current, normalizedRule]);
|
||||
setSelectedRuleKey(ruleKey(normalizedRule));
|
||||
setDraftSaved(true);
|
||||
setDraftSaved(false);
|
||||
setSaveMessage('');
|
||||
setSaveError('');
|
||||
setEditor(null);
|
||||
};
|
||||
|
||||
const saveDraftToServer = () => {
|
||||
if (hasConfigErrors) {
|
||||
setShowValidation(true);
|
||||
setSaveError('当前规则配置仍有必改问题,请先处理后再保存。');
|
||||
setSaveMessage('');
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('ruleType', pack.metadata.typeId || '');
|
||||
formData.append('yamlText', fullYamlText);
|
||||
formData.append('changeNote', `保存 ${pack.documentType}/${pack.mainType}/${pack.subtype} 规则配置`);
|
||||
formData.append('intent', 'save');
|
||||
saveFetcher.submit(formData, { method: 'post' });
|
||||
};
|
||||
|
||||
const publishDraftVersion = () => {
|
||||
if (!latestDraftVersion) {
|
||||
setSaveError('当前没有可发布的新版本,请先保存规则配置。');
|
||||
setSaveMessage('');
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('intent', 'publish');
|
||||
formData.append('ruleType', pack.metadata.typeId || '');
|
||||
formData.append('versionId', String(latestDraftVersion.id));
|
||||
saveFetcher.submit(formData, { method: 'post' });
|
||||
};
|
||||
|
||||
const rollbackRuleVersion = () => {
|
||||
if (!rollbackTargetVersion) {
|
||||
setSaveError('当前没有可回滚的历史可用版本。');
|
||||
setSaveMessage('');
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('intent', 'rollback');
|
||||
formData.append('ruleType', pack.metadata.typeId || '');
|
||||
formData.append('versionId', String(rollbackTargetVersion.id));
|
||||
saveFetcher.submit(formData, { method: 'post' });
|
||||
};
|
||||
|
||||
const resetDraft = () => {
|
||||
setRules(pack.rules);
|
||||
setSelectedRuleKey(requestedRuleId || ruleKey(pack.rules[0] || { id: '', ruleId: '' }));
|
||||
@@ -506,6 +690,8 @@ export default function RulesTestDetail() {
|
||||
setShowValidation(false);
|
||||
setShowYamlPreview(false);
|
||||
setDraftSaved(false);
|
||||
setSaveMessage('');
|
||||
setSaveError('');
|
||||
};
|
||||
|
||||
const dependencyColumns = [
|
||||
@@ -545,6 +731,9 @@ export default function RulesTestDetail() {
|
||||
<div className="config-toolbar-desc">
|
||||
{pack.documentType} / {pack.mainType} / {pack.subtype} / {currentRule?.ruleId || '-'}
|
||||
</div>
|
||||
<div className="config-toolbar-desc">
|
||||
当前版本:{currentResolvedVersion?.versionNo || '-'} / 当前状态:{versionStatusLabel(currentResolvedVersion?.status)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="config-toolbar-actions">
|
||||
<Link to={backLink} className="ant-btn ant-btn-default">
|
||||
@@ -559,6 +748,16 @@ export default function RulesTestDetail() {
|
||||
<button type="button" className="ant-btn ant-btn-default" onClick={resetDraft}>
|
||||
<i className="ri-refresh-line mr-1.5"></i>重置修改
|
||||
</button>
|
||||
<button type="button" className="ant-btn ant-btn-primary" disabled={saveButtonBusy} onClick={saveDraftToServer}>
|
||||
<i className={`${saveButtonBusy ? 'ri-loader-4-line' : 'ri-save-line'} mr-1.5`}></i>
|
||||
{saveButtonBusy ? '保存中...' : '保存规则配置'}
|
||||
</button>
|
||||
<button type="button" className="ant-btn ant-btn-default" disabled={saveButtonBusy || !latestDraftVersion} onClick={publishDraftVersion}>
|
||||
<i className="ri-upload-cloud-line mr-1.5"></i>发布版本
|
||||
</button>
|
||||
<button type="button" className="ant-btn ant-btn-default" disabled={saveButtonBusy || !rollbackTargetVersion} onClick={rollbackRuleVersion}>
|
||||
<i className="ri-history-line mr-1.5"></i>回滚版本
|
||||
</button>
|
||||
<button type="button" className="ant-btn ant-btn-primary" disabled={!currentRule} onClick={() => currentRule && openRuleEditor(currentRule)}>
|
||||
<i className="ri-edit-line mr-1.5"></i>编辑评查点
|
||||
</button>
|
||||
@@ -570,6 +769,18 @@ export default function RulesTestDetail() {
|
||||
草稿已保存。
|
||||
</div>
|
||||
)}
|
||||
{saveMessage && (
|
||||
<div className="draft-tip">
|
||||
<i className="ri-checkbox-circle-line"></i>
|
||||
{saveMessage}
|
||||
</div>
|
||||
)}
|
||||
{saveError && (
|
||||
<div className="draft-tip danger">
|
||||
<i className="ri-error-warning-line"></i>
|
||||
{saveError}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{showValidation && (
|
||||
|
||||
@@ -7,7 +7,8 @@ import { FilterPanel, FilterSelect, SearchFilter } from '~/components/ui/FilterP
|
||||
import { Pagination } from '~/components/ui/Pagination';
|
||||
import { Table } from '~/components/ui/Table';
|
||||
import { Tag, type TagColor } from '~/components/ui/Tag';
|
||||
import { loadRuleYamlPacks, type RuleSummary, type RuleYamlPack } from '~/utils/rules-yaml-mock.server';
|
||||
import { loadRuleConfigPacks } from '~/utils/rules-config-packs.server';
|
||||
import type { RuleSummary, RuleYamlPack } from '~/utils/rules-yaml-mock.server';
|
||||
import styles from '~/styles/pages/rules_test.css?url';
|
||||
|
||||
export const links = () => [
|
||||
@@ -84,7 +85,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
|
||||
pageSize: [10, 20, 30, 50].includes(requestedPageSize) ? requestedPageSize : 10
|
||||
};
|
||||
|
||||
const packs = await loadRuleYamlPacks();
|
||||
const packs = await loadRuleConfigPacks(request);
|
||||
const documentTypes = unique(packs.map(pack => pack.documentType));
|
||||
const inferredDocumentType = packs.find(pack => pack.mainType === requestedFilters.mainType)?.documentType || '';
|
||||
const currentDocumentType = documentTypes.includes(requestedFilters.documentType)
|
||||
|
||||
Reference in New Issue
Block a user