cc 2 miesięcy temu
rodzic
commit
731a22bbd2

+ 35 - 0
.workbuddy/memory/2026-09-16.md

@@ -0,0 +1,35 @@
+# 2026-09-16(下午)
+
+## 上传/清洗流程:sessionStorage 缓存清理时机(用户要求)
+
+用户要求:「我发起调用清洗,或者从上传文件页面返回时,清空 sessionStore 内容/已上传文件缓存」。
+经确认(AskUserQuestion):时机 = **发起清洗任务时 + 上传页点返回时**;范围 = **连同清洗流程缓存一起清**。
+
+### 改动(2 个文件)
+| 文件 | 改动 |
+| --- | --- |
+| `case/views/data/upload.vue` | 新增 `clearCleanFlowSessionCache()`:清 `case_clean_file_infos`(沿用 `isOwnBatchStorage()` 批次守卫)+ `case_clean_import_file_infos` + `case_clean_reclean_context` + `resetImportProgressSession()`(清 `case_clean_import_progress`、关 SSE、重置运行时状态)。调用点 3 处:`handleBack()` 无活动分支、`cleanupAndLeave()`、`onBeforeRouteLeave` 兜底(目标不是清洗页/清洗进度页时才清) |
+| `case/views/data/cleanProgress.vue` | `startClean()`:`doClean()` **成功后**清 `case_clean_file_infos` + `case_clean_import_file_infos` + `case_clean_reclean_context`(原第 736 行那行保留) |
+
+### ★ 关键约束(以后改这块必看)
+- **进清洗流程前绝对不能清 `case_clean_file_infos`**:`cleaning.vue`(`loadStoredFileList`)与 `cleanProgress.vue`(`loadCleanFiles` 的兜底键)都要读它,清了就无法清洗。所以「发起清洗时清」只能落在 `startClean()` 里、`loadCleanFiles()`/`loadReCleanContext()` **之后**。
+- `startClean()` 里 **不能** 调 `resetImportProgressSession()`:`initializeProgress()` 的顺序是 `resetRuntimeState → connectSse → testSse → startClean`,它会把刚建立的 SSE 关掉;且会清掉刚设置的 `cleanTaskStarted/currentCleanFiles`。要清进度键就用 `clearImportProgress(caseId)`。
+- 清除放在 `doClean()` 成功之后而非之前:失败时缓存仍在,可重新发起;否则发起失败即死路(必须重传文件)。
+- `case_clean_import_progress` **不清**:它是当前任务的进度快照(`currentCleanFiles` 自包含),清了刷新页面就无法恢复进度。
+- 5 个文件各自硬编码了同一批 key(upload/cleaning/cleanProgress/importList + importProgressSession),没有共享常量模块 —— 后续如要改 key 需全量搜 `case_clean_`。
+
+### 顺手修(预防性,非本次需求)
+- `upload.vue`:`import { type Key } from 'vue'` 报 TS2305(该版本 vue 不导出 `Key`)→ 去掉导入,`expandedRowKeys`/`onExpandedRowsChange` 改用 `(string | number)[]`(与 antd Table 的 `Key` 一致,代码里只塞字符串)。
+
+### 校验
+- `eslint src/case/views/data/{upload,cleanProgress}.vue --max-warnings 0` → **0 错误**
+  (`cleanProgress.vue` 原有 1 处 prettier 报错(第 134 行 import 折行)用 `--fix` 修掉,只动了那一行)
+- `vue-tsc --noEmit --skipLibCheck` → `case/views/data/{upload,cleanProgress,cleaning}.vue` **0 错误**(全仓 103 个既有错误在 `src/core` 等,与本次无关)
+
+### 环境备忘(本机 Bash shim 残缺,绕过方式)
+- 本机 shim 里 `ls/head/tail/sed/dirname/grep/uname/rm` **全部不可用**(`dirname: command not found`),
+  → `./node_modules/.bin/eslint` 这类 shell 包装脚本必然失败(它内部用 sed/dirname)。
+- **可用方式**:绝对路径调托管 node 直接执行 JS 入口:
+  `/c/Users/cc/.workbuddy/binaries/node/versions/22.22.2-3/node.exe ./node_modules/eslint/bin/eslint.js ...`
+  同理 `./node_modules/vue-tsc/bin/vue-tsc.js`。`git` 可用;`rm` 用 node 的 `fs.unlinkSync` 兜底。
+- 类型检查输出重定向到仓库内文件 + Grep 工具过滤,比试图用管道 grep 更可靠(用完记得删)。

+ 25 - 0
ai-frontend/src/case/api/govern/governApi.ts

@@ -197,6 +197,31 @@ export const preFileUpload = (
 export const cancelClean = (params: { batchId?: ApiId | number }) =>
   defHttp.get<void>({ url: adminPath + '/dm/cancelClean', params });
 
+// ==================== 原始数据预览 ====================
+
+export interface RawPreviewParams {
+  /** 工作表 ID(sheet 节点的 FileInfo.id,对应动态表 raw_{sheetId}) */
+  sheetId?: ApiId | number | string;
+  /** 表头行索引(0 开始,对应 FileInfo.lineNo - 1);有效时取该行作为表头 */
+  headerRowIndex?: number | null;
+  /** 兜底表头(模板匹配结果 FileInfo.header),headerRowIndex 无效时使用 */
+  headers?: string[];
+  /** 预览行数,默认 2000 */
+  limit?: number;
+}
+
+export interface RawPreviewDataset {
+  headers?: string[] | null;
+  rows?: Record<string, string>[] | null;
+}
+
+/**
+ * 查询 sheet 原始数据预览(DuckDB 动态表 raw_{sheetId})
+ * 替代原 Electron 端 readPreviewFile:返回 headers + rows(从文件第一行开始的所有行)
+ */
+export const rawPreview = (data: RawPreviewParams) =>
+  defHttp.postJson<RawPreviewDataset>({ url: adminPath + '/dm/rawPreview', data });
+
 /**
  * 清理废弃批次
  * 删除本批次已上传文件、解析缓存与记录(未进入清洗而离开上传页时调用)

+ 6 - 7
ai-frontend/src/case/views/data/cleanProgress.vue

@@ -131,13 +131,7 @@
   import { useMessage } from '@/core/hooks/web/useMessage';
   import { useEmitter, useUserStore } from '@/core/store/modules/case';
   import { markAnalysisDataChanged } from '@/core/logics/analysisRefreshPrompt';
-  import {
-    calcTask,
-    doClean,
-    getGovernConfList,
-    getGovernTaskSseUrl,
-    testSse,
-  } from '@/case/api/govern/governApi';
+  import { calcTask, doClean, getGovernConfList, getGovernTaskSseUrl, testSse } from '@/case/api/govern/governApi';
   import CleanLogModal from './components/CleanLogModal.vue';
   import {
     clearImportProgress,
@@ -733,6 +727,11 @@
             }
           : { fileInfos },
       );
+      // 清洗任务已发起:文件列表已读入 currentCleanFiles、进度快照由 persistImportProgress 维护,
+      // 因此立即清空「已上传文件缓存」与清洗流程中间缓存,避免后续进入流程时复用上一批文件。
+      // 放在 doClean 成功之后再清,保证发起失败时缓存仍在、可重新发起。
+      sessionStorage.removeItem(FILE_INFO_STORAGE_KEY);
+      sessionStorage.removeItem(IMPORT_FILE_INFO_STORAGE_KEY);
       sessionStorage.removeItem(RECLEAN_CONTEXT_STORAGE_KEY);
       // applyCleanResult(result);
       // if (isCleanFinishedResult(result)) {

+ 10 - 114
ai-frontend/src/case/views/data/cleaning.vue

@@ -1513,6 +1513,7 @@
   import { useMessage } from '@/core/hooks/web/useMessage';
   import type { FileInfo } from '@/types/api';
   import { tplCategoryList, tplCheckTableName, tplDetail, tplPage } from '@/plat/api/tpl/tplApi';
+  import { rawPreview } from '@/case/api/govern/governApi';
   import type { TableInfo } from '@/plat/api/tpl/types/dto';
   import {
     FunAbs,
@@ -2352,88 +2353,6 @@
   );
 
   const defaultRightTableHeaders = ['列A', '列B', '列C', '列D', '列E', '列F', '列G', '列H'];
-  const createDefaultSourceRows = () => [
-    {
-      列A: '本方号码',
-      列B: '使用人姓名',
-      列C: '号码类别',
-      列D: 'IMSI号',
-      列E: 'IMEI号',
-      列F: '归属运营商标识',
-      列G: '号码归属省',
-      列H: '号码归属市',
-    },
-    {
-      列A: '13800138000',
-      列B: '张伟',
-      列C: '移动',
-      列D: '460001234567890',
-      列E: '869990012345678',
-      列F: '中国移动',
-      列G: '广东省',
-      列H: '深圳市',
-    },
-    {
-      列A: '13900139001',
-      列B: '李娜',
-      列C: '联通',
-      列D: '460011112223334',
-      列E: '869990045612345',
-      列F: '中国联通',
-      列G: '北京市',
-      列H: '北京市',
-    },
-    {
-      列A: '13700137002',
-      列B: '王强',
-      列C: '电信',
-      列D: '460031234500987',
-      列E: '869990078900123',
-      列F: '中国电信',
-      列G: '浙江省',
-      列H: '杭州市',
-    },
-    {
-      列A: '13600136003',
-      列B: '赵敏',
-      列C: '移动',
-      列D: '460001998877665',
-      列E: '869990011122233',
-      列F: '中国移动',
-      列G: '江苏省',
-      列H: '南京市',
-    },
-    {
-      列A: '13500135004',
-      列B: '陈涛',
-      列C: '联通',
-      列D: '460019876543210',
-      列E: '869990066677788',
-      列F: '中国联通',
-      列G: '四川省',
-      列H: '成都市',
-    },
-    {
-      列A: '13400134005',
-      列B: '刘洋',
-      列C: '电信',
-      列D: '460031110000222',
-      列E: '869990099988877',
-      列F: '中国电信',
-      列G: '湖北省',
-      列H: '武汉市',
-    },
-    {
-      列A: '13300133006',
-      列B: '周倩',
-      列C: '移动',
-      列D: '460001010203040',
-      列E: '869990055544433',
-      列F: '中国移动',
-      列G: '福建省',
-      列H: '厦门市',
-    },
-  ];
 
   const rightTableHeaders = ref([...defaultRightTableHeaders]);
   const addedColumns = ref<string[]>([]);
@@ -3143,8 +3062,6 @@
     }
   };
 
-  const getElectronIpcRenderer = () => (window as any)?.electron?.ipcRenderer;
-
   const createPreviewRowsByHeaders = (headers: string[]) => {
     return headers.length ? [] : [];
   };
@@ -3192,17 +3109,16 @@
     headerRowInput.value = snapshot.headerRowIndex === null ? '' : String(snapshot.headerRowIndex + 1);
   };
   const loadPreviewDatasetFromFile = async (item?: TreeFileInfo | null): Promise<PreviewFileDataset | null> => {
-    const normalizedPath = normalizeRuleText(item?.filePath);
-    if (!normalizedPath) return null;
-
-    const ipcRenderer = getElectronIpcRenderer();
-    if (!ipcRenderer?.invoke) return null;
+    // 从 DuckDB 动态表 raw_{sheetId} 查询预览数据(sheet 节点 id 即 sheetId),
+    // 替代原 Electron 端本地文件读取
+    if (!isTreeSheetNode(item) || item?.id === null || item?.id === undefined) return null;
 
     try {
-      const payload = (await ipcRenderer.invoke('controller/os/readPreviewFile', {
-        filePath: normalizedPath,
+      const payload = (await rawPreview({
+        sheetId: item.id,
         headers: normalizeTemplateHeaders(item?.header),
         headerRowIndex: normalizeStoredLineNoToRowIndex(item?.lineNo),
+        limit: 2000,
       })) as PreviewFileDataset | null;
 
       if (!payload?.headers?.length) return null;
@@ -3212,7 +3128,7 @@
         rows: Array.isArray(payload.rows) ? payload.rows : [],
       };
     } catch (error) {
-      console.error('读取预览文件失败', normalizedPath, error);
+      console.error('读取预览数据失败', item?.id, error);
       return null;
     }
   };
@@ -8215,29 +8131,9 @@
     const rawFocusKey = pageQuery.value?.focusKey;
     return Array.isArray(rawFocusKey) ? normalizeRuleText(rawFocusKey[0]) : normalizeRuleText(rawFocusKey);
   };
-  const getQueryText = (value?: string | string[] | null) =>
-    Array.isArray(value) ? normalizeRuleText(value[0]) : normalizeRuleText(value);
   const handleBack = () => {
-    const from = getQueryText(pageQuery.value?.from);
-
-    if (from === 'match') {
-      const matchStatus = getQueryText(pageQuery.value?.matchStatus);
-      const focusKey = getFocusedNodeKeyFromQuery();
-      const matchQuery: Record<string, string> = {};
-      if (['all', 'success', 'fail'].includes(matchStatus)) {
-        matchQuery.status = matchStatus;
-      }
-      if (focusKey) {
-        matchQuery.focusKey = focusKey;
-      }
-      go({
-        path: PageEnum.BASE_MATCH,
-        query: Object.keys(matchQuery).length ? matchQuery : undefined,
-      });
-      return;
-    }
-
-    go(PageEnum.BASE_HOME);
+    // 返回上一级:文件上传页
+    go(PageEnum.BASE_UPLOAD);
   };
   const scrollSelectedTreeNodeIntoView = () => {
     void nextTick(() => {

+ 0 - 605
ai-frontend/src/case/views/data/match.vue

@@ -1,605 +0,0 @@
-<template>
-  <div :class="prefixCls" class="case-match-page">
-    <div class="page-header">
-      <div class="page-title-wrap">
-        <Button type="link" class="back-btn" @click="handleBack">
-          <template #icon><LeftOutlined /></template>
-          返回
-        </Button>
-        <div>
-          <div class="page-title">数据匹配结果</div>
-          <div class="page-subtitle">按匹配状态查看文件识别结果,确认无误后继续执行清洗导入。</div>
-        </div>
-      </div>
-      <Button type="primary" class="page-action" @click="handleCleanImport">清洗并导入</Button>
-    </div>
-
-    <div class="filter-bar">
-      <div class="filter-item">
-        <span class="filter-label">匹配状态:</span>
-        <Select v-model:value="status" class="filter-select" :options="statusOptions" />
-      </div>
-      <div class="filter-summary"
-        >共 {{ totalCount }} 个工作表,成功 {{ successList.length }} 个,失败 {{ failList.length }} 个</div
-      >
-    </div>
-
-    <div class="stats-grid">
-      <div class="stat-card">
-        <div class="stat-label">全部文件</div>
-        <div class="stat-value">{{ totalCount }}</div>
-      </div>
-      <div class="stat-card success">
-        <div class="stat-label">匹配成功</div>
-        <div class="stat-value">{{ successList.length }}</div>
-      </div>
-      <div class="stat-card error">
-        <div class="stat-label">匹配失败</div>
-        <div class="stat-value">{{ failList.length }}</div>
-      </div>
-    </div>
-
-    <div class="sections-scroll">
-      <div v-for="section in visibleSections" :key="section.key" class="section-card">
-        <div class="panel-header">
-          <div>
-            <div class="panel-title">{{ section.title }} ({{ section.items.length }})</div>
-            <div class="panel-desc">{{ section.desc }}</div>
-          </div>
-        </div>
-
-        <div v-if="section.items.length" class="match-list">
-          <div
-            v-for="item in section.items"
-            :key="item.key"
-            class="match-row"
-            :class="{ 'is-active': activeMatchKey === item.key }"
-            @click="handleSelectItem(item)"
-          >
-            <span class="match-name">{{ item.name }}</span>
-            <span class="match-status" :class="{ error: !item.success }">{{ item.status }}</span>
-            <div class="match-actions">
-              <Button type="link" class="action-link" @click.stop="handleManualClean(item)">手动清洗</Button>
-              <Button type="link" class="action-link danger" @click.stop="handleDeleteItem(item)">删除</Button>
-            </div>
-          </div>
-        </div>
-        <div v-else class="empty-state">当前筛选条件下暂无数据。</div>
-      </div>
-
-      <div v-if="!visibleSections.length" class="empty-state">当前筛选条件下暂无匹配结果。</div>
-    </div>
-  </div>
-</template>
-
-<script lang="ts" setup name="ViewsDataMatch">
-  import { computed, nextTick, onMounted, ref } from 'vue';
-  import { LeftOutlined } from '@ant-design/icons-vue';
-  import { Button, Select } from 'ant-design-vue';
-  import { useGo, useQuery } from '@/core/hooks/web/usePage';
-  import { PageEnum } from '@/core/enums/pageEnum';
-  import { useDesign } from '@/core/hooks/web/useDesign';
-  import { useMessage } from '@/core/hooks/web/useMessage';
-  import { useEmitter } from '@/core/store/modules/case';
-  import { cancelClean } from '@/case/api/govern/governApi';
-  import { resetImportProgressSession } from './importProgressSession';
-
-  const { prefixCls } = useDesign('case-match');
-  const go = useGo();
-  const pageQuery = useQuery();
-  const emitter = useEmitter();
-  const { createMessage } = useMessage();
-  const CASE_DATA_REFRESH_EVENT = 'case-data:refresh';
-
-  type MatchStatus = 'all' | 'success' | 'fail';
-
-  const status = ref<MatchStatus>('all');
-  const FILE_INFO_STORAGE_KEY = 'case_clean_file_infos';
-  const MATCH_KEY_FIELD = '__matchKey';
-  const statusOptions = [
-    { label: '全部', value: 'all' },
-    { label: '匹配成功', value: 'success' },
-    { label: '匹配失败', value: 'fail' },
-  ];
-
-  type MatchItem = {
-    key: string;
-    focusKey: string;
-    name: string;
-    status: string;
-    success: boolean;
-  };
-
-  const matchFileInfos = ref<Recordable[]>([]);
-  const activeMatchKey = ref('');
-  const normalizeMatchParentId = (value?: string | number | null) => {
-    const normalized = String(value ?? '').trim();
-    return !normalized || normalized === '0' ? '' : normalized;
-  };
-  const isMatchFileRootItem = (item?: Recordable | null) => !!item && !normalizeMatchParentId(item.pid);
-  const buildMatchItem = (item: Recordable): MatchItem => {
-    const name = item.sheetName || item.fileName || '未命名文件';
-    const mapped = mapStatus(item.fileStatus);
-    const matchKey = String(item[MATCH_KEY_FIELD]);
-    return {
-      key: matchKey,
-      focusKey: matchKey,
-      name,
-      status: mapped.label,
-      success: mapped.success,
-    };
-  };
-  const matchItems = computed(() =>
-    matchFileInfos.value.filter((item) => !isMatchFileRootItem(item)).map(buildMatchItem),
-  );
-  const totalCount = computed(() => matchItems.value.length);
-  const successList = computed(() => matchItems.value.filter((item) => item.success));
-  const failList = computed(() => matchItems.value.filter((item) => !item.success));
-  const visibleSections = computed(() => {
-    const sections = [
-      {
-        key: 'success',
-        title: '匹配成功',
-        desc: '已成功识别模板和数据结构,可直接进入清洗导入流程。',
-        items: successList.value,
-      },
-      {
-        key: 'fail',
-        title: '未匹配成功',
-        desc: '建议先检查文件格式或执行手动清洗后再重新导入。',
-        items: failList.value,
-      },
-    ];
-
-    if (status.value === 'success') {
-      return sections.filter((item) => item.key === 'success');
-    }
-    if (status.value === 'fail') {
-      return sections.filter((item) => item.key === 'fail');
-    }
-    return sections;
-  });
-
-  const resolveBatchId = () => {
-    const matchedItem = matchFileInfos.value.find((item) => item?.batchId);
-    const batchId = String(matchedItem?.batchId ?? '').trim();
-    return batchId || undefined;
-  };
-
-  const handleBack = async () => {
-    const batchId = resolveBatchId();
-
-    if (batchId) {
-      try {
-        await cancelClean({ batchId });
-      } catch (error) {
-        createMessage.warning('取消清洗失败,已返回案件数据页面');
-      }
-    }
-
-    await go(PageEnum.BASE_HOME, true);
-    await nextTick();
-    emitter.emit(CASE_DATA_REFRESH_EVENT);
-  };
-
-  const mapStatus = (status?: string) => {
-    if (!status) return { success: false, label: '待处理' };
-    if (status.includes('SUCCESS') || status.includes('COMPLETE')) return { success: true, label: '匹配成功' };
-    if (status.includes('FAIL')) return { success: false, label: '匹配错误' };
-    if (status.includes('PASSWORD')) return { success: false, label: '密码未识别' };
-    if (status.includes('FORMAT')) return { success: false, label: '格式不正确' };
-    if (status.includes('EMPTY')) return { success: false, label: '内容为空' };
-    return { success: false, label: status };
-  };
-  const normalizeMatchNodeId = (value?: string | number | null) => String(value ?? '').trim();
-  const getMatchNodeFallbackKey = (item: Recordable) =>
-    [
-      item.filePath || item.fileName || 'file',
-      item.sheetName || 'root',
-      item.tableName || '',
-      item.lineNo ?? '',
-      item.createDateTime || '',
-    ].join('__');
-  const getMatchNodeKey = (item: Recordable, index: number) =>
-    normalizeMatchNodeId(item.id) || normalizeMatchNodeId(getMatchNodeFallbackKey(item)) || String(index);
-
-  const normalizeQueryText = (value?: string | string[] | null) =>
-    Array.isArray(value) ? String(value[0] ?? '').trim() : String(value ?? '').trim();
-  const restoreMatchStatusFromQuery = () => {
-    const nextStatus = normalizeQueryText(pageQuery.value?.status);
-    if (['all', 'success', 'fail'].includes(nextStatus)) {
-      status.value = nextStatus as MatchStatus;
-    }
-  };
-  const restoreActiveMatchKeyFromQuery = () => {
-    const nextFocusKey = normalizeQueryText(pageQuery.value?.focusKey);
-    if (!nextFocusKey) return;
-    const matchedItem = matchItems.value.find((item) => item.key === nextFocusKey || item.focusKey === nextFocusKey);
-    if (matchedItem) {
-      activeMatchKey.value = matchedItem.key;
-    }
-  };
-
-  const loadMatchItems = () => {
-    const raw = sessionStorage.getItem(FILE_INFO_STORAGE_KEY);
-    if (!raw) {
-      matchFileInfos.value = [];
-      return;
-    }
-    try {
-      const parsed = JSON.parse(raw) as Recordable[];
-      if (!Array.isArray(parsed)) {
-        matchFileInfos.value = [];
-        return;
-      }
-      const fileInfos = parsed.map((item, index) => ({
-        ...item,
-        [MATCH_KEY_FIELD]: item[MATCH_KEY_FIELD] || getMatchNodeKey(item, index),
-      }));
-      matchFileInfos.value = fileInfos;
-    } catch (error) {
-      matchFileInfos.value = [];
-    }
-  };
-  const handleSelectItem = (item: MatchItem) => {
-    activeMatchKey.value = item.key;
-  };
-
-  const handleManualClean = (item: MatchItem) => {
-    handleSelectItem(item);
-    if (!matchFileInfos.value.length) {
-      createMessage.warning('未找到可清洗文件,请先上传并匹配文件');
-      return;
-    }
-    sessionStorage.setItem(FILE_INFO_STORAGE_KEY, JSON.stringify(matchFileInfos.value));
-    go({
-      path: PageEnum.BASE_CLEANING,
-      query: {
-        focusKey: item.focusKey,
-        from: 'match',
-        matchStatus: status.value,
-      },
-    });
-  };
-
-  const handleDeleteItem = (item: MatchItem) => {
-    handleSelectItem(item);
-    const targetInfo = matchFileInfos.value.find((fileInfo) => String(fileInfo[MATCH_KEY_FIELD]) === item.key);
-    const targetParentId = normalizeMatchParentId(targetInfo?.pid);
-    const nextFileInfos = matchFileInfos.value.filter((fileInfo) => String(fileInfo[MATCH_KEY_FIELD]) !== item.key);
-
-    if (targetParentId) {
-      const hasSiblingSheet = nextFileInfos.some((fileInfo) => normalizeMatchParentId(fileInfo.pid) === targetParentId);
-      if (!hasSiblingSheet) {
-        matchFileInfos.value = nextFileInfos.filter((fileInfo) => String(fileInfo.id ?? '').trim() !== targetParentId);
-      } else {
-        matchFileInfos.value = nextFileInfos;
-      }
-    } else {
-      matchFileInfos.value = nextFileInfos;
-    }
-
-    sessionStorage.setItem(FILE_INFO_STORAGE_KEY, JSON.stringify(matchFileInfos.value));
-    if (activeMatchKey.value === item.key) {
-      const nextActiveItem = matchItems.value.find((matchItem) => matchItem.key !== item.key);
-      activeMatchKey.value = nextActiveItem?.key || '';
-    }
-    createMessage.success('删除成功');
-  };
-
-  const handleCleanImport = () => {
-    if (!matchItems.value.length) {
-      createMessage.warning('未找到可清洗文件,请先上传并匹配文件');
-      return;
-    }
-    resetImportProgressSession();
-    go(PageEnum.BASE_CLEAN_PROGRESS);
-  };
-
-  onMounted(() => {
-    restoreMatchStatusFromQuery();
-    loadMatchItems();
-    restoreActiveMatchKeyFromQuery();
-  });
-</script>
-
-<style lang="less">
-  @prefix-cls: ~'jeesite-case-match';
-
-  .@{prefix-cls}.case-match-page {
-    min-height: 100%;
-    height: 100%;
-    padding: 12px 16px 24px;
-    background: #fff;
-    display: flex;
-    flex-direction: column;
-    gap: 12px;
-    box-sizing: border-box;
-    overflow: auto;
-
-    .page-header {
-      display: flex;
-      align-items: center;
-      justify-content: space-between;
-      gap: 16px;
-    }
-
-    .page-title-wrap {
-      display: flex;
-      align-items: flex-start;
-      gap: 12px;
-      min-width: 0;
-    }
-
-    .back-btn {
-      display: inline-flex;
-      align-items: center;
-      gap: 4px;
-      padding: 0 6px 0 0;
-      height: 36px;
-      border-radius: 8px;
-      color: #2563eb;
-      font-size: 16px;
-      font-weight: 600;
-      line-height: 1;
-      flex-shrink: 0;
-
-      :deep(.ant-btn-icon) {
-        font-size: 18px;
-      }
-
-      &:hover {
-        color: #1d4ed8;
-      }
-    }
-
-    .page-title {
-      font-size: 18px;
-      line-height: 1.4;
-      font-weight: 600;
-      color: #111827;
-    }
-
-    .page-subtitle {
-      margin-top: 4px;
-      font-size: 13px;
-      line-height: 1.6;
-      color: #6b7280;
-    }
-
-    .page-action {
-      height: 36px;
-      padding: 0 18px;
-      border-radius: 8px;
-      flex-shrink: 0;
-    }
-
-    .filter-bar {
-      display: flex;
-      align-items: center;
-      gap: 12px;
-      flex-wrap: wrap;
-      padding: 12px 16px;
-      border: 1px solid #e5e7eb;
-      border-radius: 12px;
-      background: #fafafa;
-      box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
-    }
-
-    .filter-item {
-      display: flex;
-      align-items: center;
-      gap: 8px;
-    }
-
-    .filter-label {
-      color: #4b5563;
-      font-size: 13px;
-      white-space: nowrap;
-    }
-
-    .filter-select {
-      width: 160px;
-    }
-
-    .filter-summary {
-      margin-left: auto;
-      color: #6b7280;
-      font-size: 12px;
-      white-space: nowrap;
-    }
-
-    .stats-grid {
-      display: grid;
-      grid-template-columns: repeat(3, minmax(0, 1fr));
-      gap: 12px;
-    }
-
-    .stat-card {
-      padding: 16px 18px;
-      border: 1px solid #e5e7eb;
-      border-radius: 12px;
-      background: #fff;
-      box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
-    }
-
-    .stat-label {
-      color: #6b7280;
-      font-size: 13px;
-    }
-
-    .stat-value {
-      margin-top: 8px;
-      font-size: 28px;
-      line-height: 1;
-      font-weight: 600;
-      color: #111827;
-    }
-
-    .stat-card.success .stat-value {
-      color: #15803d;
-    }
-
-    .stat-card.error .stat-value {
-      color: #dc2626;
-    }
-
-    .section-card {
-      flex: 0 0 auto;
-      border: 1px solid #e5e7eb;
-      border-radius: 12px;
-      background: #fff;
-      box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
-      overflow: hidden;
-    }
-
-    .sections-scroll {
-      min-height: 0;
-      flex: 1 1 auto;
-      display: flex;
-      flex-direction: column;
-      gap: 12px;
-      overflow-y: auto;
-      padding-right: 4px;
-      padding-bottom: 2px;
-    }
-
-    .panel-header {
-      display: flex;
-      align-items: center;
-      justify-content: space-between;
-      gap: 12px;
-      padding: 16px 18px 12px;
-      border-bottom: 1px solid #eef2f7;
-    }
-
-    .panel-title {
-      font-size: 15px;
-      font-weight: 600;
-      color: #111827;
-    }
-
-    .panel-desc {
-      margin-top: 4px;
-      font-size: 12px;
-      color: #6b7280;
-      line-height: 1.6;
-    }
-
-    .match-list {
-      display: flex;
-      flex-direction: column;
-      padding: 12px 18px 18px;
-    }
-
-    .match-row {
-      display: grid;
-      grid-template-columns: minmax(0, 1fr) 140px 180px;
-      align-items: center;
-      gap: 12px;
-      position: relative;
-      margin: 0 -10px;
-      min-height: 52px;
-      padding: 10px 10px;
-      border-radius: 10px;
-      border-bottom: 1px solid #eef2f7;
-      cursor: pointer;
-      transition:
-        background-color 0.2s ease,
-        box-shadow 0.2s ease;
-
-      &:last-child {
-        border-bottom: none;
-      }
-
-      &:hover {
-        background: #f8fbff;
-      }
-
-      &.is-active {
-        background: #eef4ff;
-        box-shadow:
-          inset 3px 0 0 #3651d9,
-          inset 0 0 0 1px rgba(54, 81, 217, 0.12);
-
-        .match-name {
-          color: #1d4ed8;
-          font-weight: 600;
-        }
-      }
-    }
-
-    .match-name {
-      color: #111827;
-      font-size: 13px;
-      line-height: 1.6;
-    }
-
-    .match-status {
-      display: inline-flex;
-      align-items: center;
-      justify-content: center;
-      width: fit-content;
-      min-width: 88px;
-      padding: 4px 10px;
-      border-radius: 999px;
-      background: #ecfdf3;
-      color: #15803d;
-      font-size: 12px;
-      font-weight: 600;
-    }
-
-    .match-status.error {
-      background: #fef2f2;
-      color: #dc2626;
-    }
-
-    .match-actions {
-      display: flex;
-      justify-content: flex-end;
-      gap: 8px;
-    }
-
-    .action-link {
-      padding: 0;
-      height: auto;
-    }
-
-    .action-link.danger {
-      color: #ef4444;
-    }
-
-    .empty-state {
-      padding: 28px 18px;
-      border: 1px dashed #d1d5db;
-      border-radius: 12px;
-      background: #fafafa;
-      color: #9ca3af;
-      text-align: center;
-      font-size: 13px;
-    }
-
-    @media (max-width: 960px) {
-      .page-header {
-        flex-direction: column;
-        align-items: flex-start;
-      }
-
-      .filter-summary {
-        margin-left: 0;
-      }
-
-      .stats-grid {
-        grid-template-columns: 1fr;
-      }
-
-      .match-row {
-        grid-template-columns: 1fr;
-      }
-
-      .match-actions {
-        justify-content: flex-start;
-      }
-    }
-  }
-</style>

+ 308 - 41
ai-frontend/src/case/views/data/upload.vue

@@ -12,9 +12,8 @@
         </div>
       </div>
       <div class="page-header__actions">
-        <Button type="primary" class="next-btn" :disabled="!hasSuccessResult" @click="handleGoMatch">
-          下一步:数据匹配
-        </Button>
+        <Button type="primary" class="next-btn" :disabled="!hasSuccessResult" @click="handleSmartClean"> 智能 </Button>
+        <Button class="next-btn" :disabled="!resultTrees.length" @click="handleManualClean">手动清洗</Button>
       </div>
     </div>
 
@@ -142,19 +141,26 @@
             <div class="panel-title">解析结果(实时)</div>
             <div class="panel-desc">每完成一份文件解析,结果树会实时追加到下方</div>
           </div>
+          <div class="panel-header__actions">
+            <Button size="small" :disabled="!expandableCount" @click="toggleExpandAllRows">
+              {{ allExpanded ? '全部收起' : '全部展开' }}
+            </Button>
+          </div>
           <div class="panel-stats">已解析 {{ resultTrees.length }} 个文件</div>
         </div>
         <div class="table-wrapper">
           <Table
             class="result-tree-table"
             :columns="resultTableColumns"
-            :data-source="resultTrees"
+            :data-source="tableDataSource"
             :loading="tableLoading"
             :pagination="false"
             row-key="id"
             :children-column-name="'children'"
+            :expanded-row-keys="expandedRowKeys"
             size="small"
-            :scroll="{ x: 760 }"
+            :scroll="{ x: 840 }"
+            @expandedRowsChange="onExpandedRowsChange"
           />
         </div>
       </section>
@@ -163,7 +169,7 @@
 </template>
 
 <script lang="ts" setup name="ViewsDataUpload">
-  import { computed, h, ref } from 'vue';
+  import { computed, h, onMounted, ref } from 'vue';
   import { onBeforeRouteLeave } from 'vue-router';
   import { CloseOutlined, LeftOutlined } from '@ant-design/icons-vue';
   import { Button, Modal, Table, type TableColumnsType } from 'ant-design-vue';
@@ -172,8 +178,9 @@
   import { PageEnum } from '@/core/enums/pageEnum';
   import { useMessage } from '@/core/hooks/web/useMessage';
   import { useEmitter } from '@/core/store/modules/case';
-  import { clearUploadBatch, preFileUpload } from '@/case/api/govern/governApi';
+  import { clearUploadBatch, deletedFileList, preFileUpload } from '@/case/api/govern/governApi';
   import { FileStatusEnum } from '@/case/types/enum';
+  import { resetImportProgressSession } from './importProgressSession';
   import type { FileInfo } from '@/types/api';
 
   const { prefixCls } = useDesign('case-upload');
@@ -182,8 +189,9 @@
   const emitter = useEmitter();
   const { createMessage } = useMessage();
   const FILE_INFO_STORAGE_KEY = 'case_clean_file_infos';
+  const IMPORT_FILE_INFO_STORAGE_KEY = 'case_clean_import_file_infos';
+  const RECLEAN_CONTEXT_STORAGE_KEY = 'case_clean_reclean_context';
   const CASE_DATA_REFRESH_EVENT = 'case-data:refresh';
-  const CASE_IMPORT_FILE_REFRESH_EVENT = 'case-import-file:refresh';
   const VALID_UPLOAD_EXTS = ['.xls', '.xlsx', '.csv'];
 
   type UploadMode = 'single' | 'folder';
@@ -210,6 +218,42 @@
   const allFileInfos = ref<Recordable[]>([]);
   const tableLoading = ref(false);
 
+  // 受控展开:默认全部展开,新解析的文件根节点自动展开
+  // (键类型与 ant-design-vue Table 的 expandedRowKeys 保持一致:string | number)
+  const expandedRowKeys = ref<(string | number)[]>([]);
+  const expandableCount = computed(() => resultTrees.value.filter((root) => (root.children || []).length > 0).length);
+  const allExpanded = computed(
+    () => expandableCount.value > 0 && expandedRowKeys.value.length >= expandableCount.value,
+  );
+
+  const collectExpandableKeys = () =>
+    resultTrees.value.filter((root) => (root.children || []).length > 0).map((root) => String(root.id ?? ''));
+
+  const expandAllRows = () => {
+    expandedRowKeys.value = collectExpandableKeys();
+  };
+
+  const toggleExpandAllRows = () => {
+    expandedRowKeys.value = allExpanded.value ? [] : collectExpandableKeys();
+  };
+
+  // 用户手动展开/收起时同步受控 keys
+  const onExpandedRowsChange = (keys: (string | number)[]) => {
+    expandedRowKeys.value = keys;
+  };
+
+  // 表格数据源:递归剥离空 children。
+  // 后端 FileInfo.children 恒为空数组(非 undefined),ant-design-vue 树形模式下
+  // 只要 record.children 为真值就渲染展开图标,空数组也算,必须逐层剥掉
+  const stripEmptyChildren = (node: Recordable): Recordable => {
+    const children = node.children || [];
+    if (!children.length) {
+      return { ...node, children: undefined };
+    }
+    return { ...node, children: children.map(stripEmptyChildren) };
+  };
+  const tableDataSource = computed(() => resultTrees.value.map(stripEmptyChildren));
+
   // 离开放行标记:点「下一步」或已确认清理后的程序化跳转置为 true
   const allowedToLeave = ref(false);
   // 放弃标记:确认离开后中断上传循环,避免组件卸载后继续写结果
@@ -367,6 +411,33 @@
     sessionStorage.setItem(FILE_INFO_STORAGE_KEY, JSON.stringify(infos));
   };
 
+  /**
+   * 从 storage 恢复已解析结果(从清洗页返回时右侧表格还原)
+   * 同时把批次号恢复为原批次,保证后续上传/删除/清理与原批次数据一致
+   */
+  const restoreParsedResults = () => {
+    try {
+      const raw = sessionStorage.getItem(FILE_INFO_STORAGE_KEY);
+      if (!raw) return;
+      const parsed = JSON.parse(raw);
+      if (!Array.isArray(parsed) || !parsed.length) return;
+      allFileInfos.value = parsed;
+      resultTrees.value = parsed;
+      // 恢复后默认全部展开
+      expandAllRows();
+      const storedBatchId = parsed[0]?.batchId;
+      if (storedBatchId !== null && storedBatchId !== undefined && String(storedBatchId).trim() !== '') {
+        uploadBatchId.value = storedBatchId as number;
+      }
+    } catch {
+      // 无效缓存忽略,保持新批次
+    }
+  };
+
+  onMounted(() => {
+    restoreParsedResults();
+  });
+
   const isOwnBatchStorage = () => {
     const raw = sessionStorage.getItem(FILE_INFO_STORAGE_KEY);
     if (!raw) return true;
@@ -385,6 +456,20 @@
     }
   };
 
+  /**
+   * 离开上传页时清空本流程的 sessionStorage 缓存,避免上一批已上传文件被后续流程复用:
+   * - case_clean_file_infos        已上传文件的解析结果(右侧表格数据源)
+   * - case_clean_import_file_infos 手动清洗页提交给清洗进度页的导入文件列表
+   * - case_clean_reclean_context   重新清洗上下文(reClean=1 + fileId)
+   * - case_clean_import_progress   清洗进度快照,连同运行时状态与 SSE 连接一起重置
+   */
+  const clearCleanFlowSessionCache = () => {
+    clearStoredFileInfos();
+    sessionStorage.removeItem(IMPORT_FILE_INFO_STORAGE_KEY);
+    sessionStorage.removeItem(RECLEAN_CONTEXT_STORAGE_KEY);
+    resetImportProgressSession();
+  };
+
   /**
    * 自动上传队列:选择文件后自动触发,按序消费列表中的待上传文件;
    * 上传解析成功即从列表移除,失败保留(标记错误,可手动移除)。
@@ -428,9 +513,12 @@
           if (fileNode) {
             // 右侧 treetable 直接渲染树(文件根 → sheet 子节点)
             resultTrees.value = [...resultTrees.value, fileNode];
-            // 持久化给 match/清洗流程的数据保持平铺(根 + 各 sheet 同层,pid 关联),与历史契约一致
-            const flatList: FileInfo[] = [fileNode, ...(fileNode.children ?? [])];
-            allFileInfos.value = [...allFileInfos.value, ...flatList];
+            // 新文件根自动展开(受控展开,默认全部展开)
+            if ((fileNode.children || []).length > 0) {
+              expandedRowKeys.value = [...expandedRowKeys.value, String(fileNode.id ?? '')];
+            }
+            // 持久化给 match/清洗流程的数据按后端返回的树结构存储(文件根 + children sheet)
+            allFileInfos.value = [...allFileInfos.value, fileNode];
             persistFileInfos(allFileInfos.value);
           }
           // 上传成功:从列表移除该文件
@@ -483,7 +571,7 @@
     'SHEET_TEMPLATE_MATCHED_FAIL',
   ]);
 
-  const isSuccessStatus = (status?: string) => {
+  const isSuccessStatus = (status?: string | null) => {
     const normalized = String(status || '').trim();
     return !!normalized && SUCCESS_FILE_STATUSES.has(normalized);
   };
@@ -525,19 +613,6 @@
       width: 90,
       customRender: ({ record }: any) => record.dataNum ?? '—',
     },
-    {
-      title: '成功',
-      key: 'successNum',
-      width: 90,
-      customRender: ({ record }: any) =>
-        h('span', { class: 'cell-num is-success' }, [String(record.successNum ?? '—')]),
-    },
-    {
-      title: '失败',
-      key: 'failNum',
-      width: 90,
-      customRender: ({ record }: any) => h('span', { class: 'cell-num is-fail' }, [String(record.failNum ?? '—')]),
-    },
     {
       title: '状态',
       key: 'status',
@@ -548,6 +623,54 @@
         return h('span', { class: ['status-tag', cls] }, [mapped.label]);
       },
     },
+    {
+      title: '操作',
+      key: 'action',
+      width: 150,
+      customRender: ({ record }: any) => {
+        // 文件根行:删除整个文件(级联全部工作表)
+        if (isRootNode(record)) {
+          return h('div', { class: 'cell-actions' }, [
+            h(
+              Button,
+              {
+                type: 'link',
+                size: 'small',
+                class: 'action-link is-danger',
+                disabled: isUploading.value,
+                onClick: () => handleRowDelete(record),
+              },
+              () => '删除',
+            ),
+          ]);
+        }
+        // 工作表行:手动清洗 + 删除
+        return h('div', { class: 'cell-actions' }, [
+          h(
+            Button,
+            {
+              type: 'link',
+              size: 'small',
+              class: 'action-link',
+              disabled: isUploading.value,
+              onClick: () => handleRowManualClean(record),
+            },
+            () => '手动清洗',
+          ),
+          h(
+            Button,
+            {
+              type: 'link',
+              size: 'small',
+              class: 'action-link is-danger',
+              disabled: isUploading.value,
+              onClick: () => handleRowDelete(record),
+            },
+            () => '删除',
+          ),
+        ]);
+      },
+    },
   ];
 
   const cleanupAndLeave = async () => {
@@ -558,7 +681,7 @@
     } catch (error: any) {
       createMessage.warning(error?.message || '清理本批次数据失败,可稍后在导入文件管理中删除');
     } finally {
-      clearStoredFileInfos();
+      clearCleanFlowSessionCache();
       await go(PageEnum.BASE_HOME, true);
       emitter.emit(CASE_DATA_REFRESH_EVENT);
     }
@@ -567,6 +690,8 @@
   const handleBack = () => {
     if (!hasActivity.value) {
       allowedToLeave.value = true;
+      // 返回案件数据:清空已上传文件与清洗流程缓存,避免下次进入上传页还原上一批文件
+      clearCleanFlowSessionCache();
       go(PageEnum.BASE_HOME, true);
       emitter.emit(CASE_DATA_REFRESH_EVENT);
       return;
@@ -582,17 +707,134 @@
     });
   };
 
-  const handleGoMatch = () => {
+  /** 智能清洗:直接进入清洗导入流程(自动按已匹配模板执行) */
+  const handleSmartClean = () => {
     if (!hasSuccessResult.value) return;
     allowedToLeave.value = true;
+    resetImportProgressSession();
+    go(PageEnum.BASE_CLEAN_PROGRESS);
+  };
+
+  /** 手动清洗:进入手动清洗页逐个处理(含模板匹配失败的表) */
+  const handleManualClean = () => {
+    if (!resultTrees.value.length) return;
+    allowedToLeave.value = true;
+    go(PageEnum.BASE_CLEANING);
+  };
+
+  /** 行级手动清洗:定位到指定工作表进入手动清洗页 */
+  const handleRowManualClean = (record: Recordable) => {
+    const focusKey = String(record.id ?? '').trim();
+    if (!focusKey) {
+      createMessage.warning('未获取到工作表ID,暂时无法手动清洗');
+      return;
+    }
+    allowedToLeave.value = true;
+    go({ path: PageEnum.BASE_CLEANING, query: { focusKey } });
+  };
+
+  /** 本地移除整个文件节点并同步 sessionStorage */
+  const removeFileNodeSync = (rootId: string) => {
+    resultTrees.value = resultTrees.value.filter((item) => String(item.id ?? '') !== rootId);
+    allFileInfos.value = allFileInfos.value.filter((item) => String(item.id ?? '') !== rootId);
+    // 同步移除已删除文件根的展开状态
+    expandedRowKeys.value = expandedRowKeys.value.filter((key) => String(key) !== rootId);
+    persistFileInfos(allFileInfos.value);
+  };
+
+  /** 本地移除单个工作表节点并同步 sessionStorage */
+  const removeSheetNodeSync = (rootId: string, sheetId: string) => {
+    const stripSheet = (item: Recordable) =>
+      String(item.id ?? '') === rootId
+        ? {
+            ...item,
+            children: (item.children || []).filter((child) => String(child.id ?? '') !== sheetId),
+          }
+        : item;
+    resultTrees.value = resultTrees.value.map(stripSheet);
+    allFileInfos.value = allFileInfos.value.map(stripSheet);
     persistFileInfos(allFileInfos.value);
-    emitter.emit(CASE_IMPORT_FILE_REFRESH_EVENT);
-    go(PageEnum.BASE_MATCH);
+  };
+
+  /** 行级删除:文件根行删除整个文件(级联全部工作表),工作表行删除单个工作表(仅剩此表时连同文件根) */
+  const handleRowDelete = (record: Recordable) => {
+    // 文件根行:整文件删除
+    if (isRootNode(record)) {
+      const fileRootId = String(record.id ?? '').trim();
+      const fileName = record.fileName || '未命名文件';
+      if (!fileRootId) {
+        createMessage.warning('未获取到文件ID,暂时无法删除');
+        return;
+      }
+      Modal.confirm({
+        title: '删除确认',
+        content: `确定删除文件「${fileName}」及其全部工作表吗?`,
+        okText: '删除',
+        okType: 'danger',
+        cancelText: '取消',
+        onOk: async () => {
+          try {
+            // 后端按 id 级联删除(id 匹配 + pid 匹配),传根 id 即删整文件
+            await deletedFileList({ ids: [fileRootId] });
+            removeFileNodeSync(fileRootId);
+            createMessage.success('删除成功');
+          } catch (error: any) {
+            createMessage.error(error?.message || '删除失败');
+          }
+        },
+      });
+      return;
+    }
+
+    // 工作表行:单表删除(该文件仅剩此表时连同文件根一起删除)
+    const rootId = String(record.pid ?? '').trim();
+    const root = resultTrees.value.find((item) => String(item.id ?? '') === rootId);
+    const siblings = root?.children || [];
+    const isLastSheet = siblings.length <= 1;
+    const sheetId = String(record.id ?? '').trim();
+    const sheetName = record.sheetName || '未命名工作表';
+    const fileName = root?.fileName || '未命名文件';
+
+    Modal.confirm({
+      title: '删除确认',
+      content: isLastSheet
+        ? `「${fileName}」仅剩此工作表,删除后将移除整个文件,是否继续?`
+        : `确定删除工作表「${sheetName}」吗?`,
+      okText: '删除',
+      okType: 'danger',
+      cancelText: '取消',
+      onOk: async () => {
+        try {
+          // 后端按 id 级联删除(id 匹配 + pid 匹配):仅剩此表时传根 id 删整文件,否则传 sheet id 删单表
+          const deleteIds = isLastSheet && root ? [String(root.id ?? '')] : [sheetId];
+          const validIds = deleteIds.filter(Boolean);
+          if (!validIds.length) {
+            createMessage.warning('未获取到ID,暂时无法删除');
+            return;
+          }
+          await deletedFileList({ ids: validIds });
+          if (isLastSheet) {
+            removeFileNodeSync(rootId);
+          } else {
+            removeSheetNodeSync(rootId, sheetId);
+          }
+          createMessage.success('删除成功');
+        } catch (error: any) {
+          createMessage.error(error?.message || '删除失败');
+        }
+      },
+    });
   };
 
   // 兜底浏览器返回 / 标签页关闭等非按钮离开
-  onBeforeRouteLeave((_to, _from, next) => {
+  onBeforeRouteLeave((to, _from, next) => {
     if (allowedToLeave.value || !hasActivity.value) {
+      // 进入清洗流程(清洗页 / 清洗进度页)时保留缓存,供下游页面读取;
+      // 其余离开上传页的场景(返回案件数据、切菜单等)一律清空已上传文件与清洗流程缓存
+      const toPath = String(to?.path ?? '');
+      if (toPath !== PageEnum.BASE_CLEANING && toPath !== PageEnum.BASE_CLEAN_PROGRESS) {
+        clearCleanFlowSessionCache();
+      }
       next();
       return;
     }
@@ -742,6 +984,13 @@
       line-height: 1.5;
     }
 
+    .panel-header__actions {
+      display: flex;
+      align-items: center;
+      gap: 8px;
+      margin-left: auto;
+    }
+
     .panel-stats {
       font-size: 12px;
       color: #64748b;
@@ -756,7 +1005,7 @@
     }
 
     .result-tree-table {
-      :deep(.ant-table-thead > tr > th) {
+      .ant-table-thead > tr > th {
         padding: 6px 8px;
         font-size: 12px;
         font-weight: 600;
@@ -765,20 +1014,25 @@
         border-bottom: 1px solid #eef2f7;
       }
 
-      :deep(.ant-table-tbody > tr > td) {
+      .ant-table-tbody > tr > td {
         padding: 6px 8px;
         font-size: 13px;
         border-bottom: 1px solid #f6f8fa;
       }
 
-      :deep(.ant-table-tbody > tr:hover > td) {
+      .ant-table-tbody > tr:hover > td {
         background: #f8fafc;
       }
 
-      :deep(.ant-table-row-expand-icon) {
+      .ant-table-row-expand-icon {
         margin-right: 6px;
         border-radius: 3px;
       }
+
+      /* 无子集的行:隐藏展开占位图标(样式块非 scoped,直接用普通选择器) */
+      .ant-table-row-expand-icon-spaced {
+        display: none;
+      }
     }
 
     .cell-name {
@@ -790,15 +1044,28 @@
       }
     }
 
-    .cell-num {
-      font-size: 13px;
+    .cell-actions {
+      display: inline-flex;
+      align-items: center;
+      gap: 2px;
 
-      &.is-success {
-        color: #16a34a;
-      }
+      .action-link {
+        padding: 0 4px;
+        height: 24px;
+        font-size: 12px;
+        color: #2563eb;
 
-      &.is-fail {
-        color: #dc2626;
+        &:hover {
+          color: #1d4ed8;
+        }
+
+        &.is-danger {
+          color: #dc2626;
+
+          &:hover {
+            color: #b91c1c;
+          }
+        }
       }
     }
 

+ 0 - 1
ai-frontend/src/core/enums/pageEnum.ts

@@ -6,7 +6,6 @@ export enum PageEnum {
   // basic home path
   BASE_HOME = '/data/index',
   BASE_UPLOAD = '/data/upload',
-  BASE_MATCH = '/data/match',
   BASE_CLEANING = '/data/cleaning',
   BASE_CLEAN_PROGRESS = '/data/cleanProgress',
   // error page path

+ 0 - 11
ai-frontend/src/core/router/routes/index.ts

@@ -53,17 +53,6 @@ export const DataRoute: AppRouteRecordRaw = {
         affix: true,
       },
     },
-    {
-      path: 'match',
-      name: 'CaseMatch',
-      component: () => import('@/case/views/data/match.vue'),
-      meta: {
-        title: '数据匹配结果',
-        hideMenu: true,
-        hideTab: true,
-        currentActiveMenu: PageEnum.BASE_HOME,
-      },
-    },
     {
       path: 'cleaning',
       name: 'CaseCleaning',

+ 1 - 1
ai-frontend/src/core/store/modules/multipleTab.ts

@@ -29,7 +29,7 @@ const cacheTab = projectSetting.multiTabsSetting.cache;
 const BEHAVIOR_SPACETIME_TAB_PATH = '/behaviorSpacetime/index';
 const HOME_TAB_PATH = PageEnum.BASE_HOME;
 const HOME_TAB_TITLE = '案件数据';
-const HIDDEN_FLOW_TAB_PATHS = new Set([PageEnum.BASE_MATCH, PageEnum.BASE_CLEANING, PageEnum.BASE_CLEAN_PROGRESS]);
+const HIDDEN_FLOW_TAB_PATHS = new Set([PageEnum.BASE_CLEANING, PageEnum.BASE_CLEAN_PROGRESS]);
 const resolveTabFullPath = (tab: Partial<RouteLocationNormalized>) => tab.fullPath || tab.path || '';
 const resolveTabBasePath = (tab: Partial<RouteLocationNormalized>) => resolveTabFullPath(tab).split('?')[0];
 const resolveTabMatchKey = (tab: Partial<RouteLocationNormalized>) => {

+ 24 - 0
ai-server/src/main/java/com/zsjz/ai/common/model/dm/dto/RawPreviewDTO.java

@@ -0,0 +1,24 @@
+package com.zsjz.ai.common.model.dm.dto;
+
+import lombok.Data;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * sheet 原始数据预览结果
+ * 与原 Electron 端 readPreviewFile 返回形状一致:headers + rows
+ */
+@Data
+public class RawPreviewDTO {
+
+    /**
+     * 表头(表头行各列的原始值,含空串,未识别时为空列表)
+     */
+    private List<String> headers;
+
+    /**
+     * 数据行(从文件第一行开始的所有行,含表头上方内容与表头行),key 为表头名
+     */
+    private List<Map<String, String>> rows;
+}

+ 32 - 0
ai-server/src/main/java/com/zsjz/ai/common/model/dm/query/RawPreviewQuery.java

@@ -0,0 +1,32 @@
+package com.zsjz.ai.common.model.dm.query;
+
+import com.zsjz.ai.common.base.Query;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+import java.util.List;
+
+/**
+ * sheet 原始数据预览查询参数
+ * 查询预览阶段动态创建的 DuckDB 表 raw_{sheetId},替代原 Electron 端本地文件读取
+ */
+@Data
+@EqualsAndHashCode(callSuper = true)
+public class RawPreviewQuery extends Query {
+
+    /**
+     * 工作表 ID(即动态表名后缀,sheet 节点的 FileInfo.id)
+     */
+    private Long sheetId;
+
+    /**
+     * 表头行索引(0 开始,对应 FileInfo.lineNo - 1)
+     * 有效时取该行作为表头;无效时回退使用 headers
+     */
+    private Integer headerRowIndex;
+
+    /**
+     * 兜底表头(模板匹配结果 FileInfo.header),headerRowIndex 无效时使用
+     */
+    private List<String> headers;
+}

+ 2 - 2
ai-server/src/main/java/com/zsjz/ai/module/dm/clean/CleanTask.java

@@ -119,9 +119,9 @@ public record CleanTask(FileInfo fileInfo, List<FileInfo> sheetList) {
             }
         }
         log.info("清洗任务结束, fileId={}, fileName={}, extractedSheetCount={}", fileInfo.getId(), fileInfo.getFileName(), extractSheetList.size());
-        // 批量插入文件信息到数据库
+        // 批量落库文件信息:解析阶段(preFileUpload)已入库的记录按 id 更新,未入库的插入
         FileInfoMapper fileInfoMapper = SpringUtil.getBean(FileInfoMapper.class);
-        fileInfoMapper.insert(extractSheetList);
+        fileInfoMapper.insertOrUpdate(extractSheetList);
         if (CollUtil.isNotEmpty(sheetLogs)) {
             CleanErrorLogMapper cleanErrorLogMapper = SpringUtil.getBean(CleanErrorLogMapper.class);
             cleanErrorLogMapper.insert(sheetLogs);

+ 15 - 0
ai-server/src/main/java/com/zsjz/ai/module/dm/controller/DmController.java

@@ -4,8 +4,10 @@ import com.zsjz.ai.common.model.dm.dto.DeletedFilesDTO;
 import com.zsjz.ai.common.model.dm.dto.DoCleanDTO;
 import com.zsjz.ai.common.config.Result;
 import com.zsjz.ai.common.model.dm.dto.PrepareProcessFileDTO;
+import com.zsjz.ai.common.model.dm.dto.RawPreviewDTO;
 import com.zsjz.ai.common.model.dm.entity.FileInfo;
 import com.zsjz.ai.common.model.dm.query.FileInfoQuery;
+import com.zsjz.ai.common.model.dm.query.RawPreviewQuery;
 import com.zsjz.ai.common.model.govern.dto.CalcDataDTO;
 import com.zsjz.ai.common.model.govern.entity.GovernConf;
 import com.zsjz.ai.common.utils.Json;
@@ -80,6 +82,19 @@ public class DmController {
         return Result.succeed(dmService.preProcessUploadedFile(file, batchId, reClean));
     }
 
+    /**
+     * 查询 sheet 原始数据预览
+     * 从预览阶段动态创建的 DuckDB 表 raw_{sheetId} 读取数据,替代原 Electron 端 readPreviewFile
+     * 返回 headers + rows(从文件第一行开始的所有行),供手动清洗页面渲染预览表格
+     *
+     * @param query 查询参数(sheetId 必填;headerRowIndex 表头行索引 0 开始;
+     *              headers 兜底模板表头;limit 预览行数,默认 2000)
+     */
+    @PostMapping("/rawPreview")
+    public Result<RawPreviewDTO> rawPreview(@RequestBody RawPreviewQuery query) {
+        return Result.succeed(dmService.rawPreview(query));
+    }
+
     /**
      * 执行数据清洗任务
      * 根据传入的文件信息和清洗配置,执行数据清洗和入库操作

+ 16 - 2
ai-server/src/main/java/com/zsjz/ai/module/dm/pre/PreDataListener.java

@@ -95,6 +95,12 @@ public class PreDataListener extends AnalysisEventListener<Map<Integer, String>>
      */
     private boolean rawTableInited;
 
+    /**
+     * 当前 sheet 已读取行数(数据量)
+     */
+    private int rowCount;
+
+
     /**
      * 构造函数
      *
@@ -137,6 +143,7 @@ public class PreDataListener extends AnalysisEventListener<Map<Integer, String>>
      * @param rowData 当前行数据,key 为列索引
      */
     private void appendRawRow(Map<Integer, String> rowData) {
+        rowCount++;
         if (!rawTableInited) {
             initRawTable(rowData);
         }
@@ -308,10 +315,17 @@ public class PreDataListener extends AnalysisEventListener<Map<Integer, String>>
      */
     @Override
     public void doAfterAllAnalysed(AnalysisContext analysisContext) {
-        // 关闭当前 sheet 的动态表资源并重置状态
+        // 关闭当前 sheet 的动态表资源
         closeRawTable();
-        rawTableInited = false;
+        // 回填本 sheet 计数:数据量=读取行数,成功=写入动态表行数,失败=差值(含写入失败与未入库行)
+        if (fileSheet != null) {
+            fileSheet.setDataNum(rowCount);
+            fileSheet.setSuccessNum(0);
+            fileSheet.setFailNum(0);
+        }
         // 重置状态,准备处理下一个工作表
+        rowCount = 0;
+        rawTableInited = false;
         fileSheet = null;
         matched.set(false);
     }

+ 109 - 0
ai-server/src/main/java/com/zsjz/ai/module/dm/service/DmService.java

@@ -5,18 +5,23 @@ import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.util.IdUtil;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.crypto.digest.DigestUtil;
+import cn.hutool.extra.spring.SpringUtil;
+import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.zsjz.ai.common.cache.GlobalCache;
 import com.zsjz.ai.common.constants.PathConst;
+import com.zsjz.ai.common.constants.StrConsts;
 import com.zsjz.ai.common.enums.FileSheetStateEnum;
 import com.zsjz.ai.common.enums.HasInnerEnum;
 import com.zsjz.ai.common.exception.ServerException;
 import com.zsjz.ai.common.model.dm.dto.DoCleanDTO;
 import com.zsjz.ai.common.model.dm.dto.PrepareProcessFileDTO;
+import com.zsjz.ai.common.model.dm.dto.RawPreviewDTO;
 import com.zsjz.ai.common.model.dm.entity.FileInfo;
 import com.zsjz.ai.common.model.dm.query.FileInfoQuery;
+import com.zsjz.ai.common.model.dm.query.RawPreviewQuery;
 import com.zsjz.ai.common.model.govern.dto.CalcDataDTO;
 import com.zsjz.ai.common.model.plat.dto.SeeDataDTO;
 import com.zsjz.ai.common.model.plat.dto.SseDTO;
@@ -46,6 +51,12 @@ import java.io.InputStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.StandardCopyOption;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.Statement;
+
+import javax.sql.DataSource;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.util.*;
@@ -162,10 +173,108 @@ public class DmService {
         // 单文件串行解析,无需并发控制信号量;返回树形根节点(含 children sheets),重复文件返回 null
         FileInfo root = buildPreviewTree(processPreviewFile(saved, currentBatchId)).stream().findFirst().orElse(null);
         backfillFileSize(root, saved);
+        saveParsedFileInfos(root);
         log.info("上传文件解析完成: name={}, batchId={}", originalName, currentBatchId);
         return root;
     }
 
+    /**
+     * 解析结果入库(file_info,含数据量/成功/失败计数)
+     * 上传页删除、MD5 去重与列表查询依赖这些记录;入库失败仅记日志,不影响解析返回
+     *
+     * @param root 文件根节点(children 为各 sheet)
+     */
+    private void saveParsedFileInfos(FileInfo root) {
+        if (root == null) {
+            return;
+        }
+        List<FileInfo> records = Lists.newArrayList(root);
+        if (CollUtil.isNotEmpty(root.getChildren())) {
+            records.addAll(root.getChildren());
+        }
+        try {
+            fileInfoMapper.insert(records);
+        } catch (Exception e) {
+            log.error("解析结果入库失败, fileId={}, fileName={}", root.getId(), root.getFileName(), e);
+        }
+    }
+
+    /**
+     * 查询 sheet 原始数据预览
+     * 从预览阶段动态创建的 DuckDB 表 raw_{sheetId} 读取数据,替代原 Electron 端 readPreviewFile
+     * 表头行索引有效时取该行作为表头,否则回退使用前端传入的模板表头;
+     * 返回从文件第一行开始的所有行(含表头上方内容与表头行),与原 Electron 返回形状一致
+     *
+     * @param query 查询参数(sheetId 必填,headerRowIndex / headers 可选,limit 预览行数)
+     * @return 表头与数据行;查询失败或无数据时返回空集合
+     */
+    public RawPreviewDTO rawPreview(RawPreviewQuery query) {
+        RawPreviewDTO dto = new RawPreviewDTO();
+        dto.setHeaders(List.of());
+        dto.setRows(List.of());
+        if (query == null || query.getSheetId() == null) {
+            return dto;
+        }
+        // 预览行数上限(Query.limit 默认 20,显式传入时以传入为准)
+        long limit = query.getLimit() > 0 ? query.getLimit() : 2000;
+        String tableName = "raw_" + query.getSheetId();
+        // 从 raw 表读取全部行网格:只取 col_x 数据列,忽略 file_id / sheet_id 关联列
+        List<List<String>> grid = new ArrayList<>();
+        try {
+            DynamicRoutingDataSource ds = (DynamicRoutingDataSource) SpringUtil.getBean(DataSource.class);
+            try (Connection conn = ds.getDataSource(StrConsts.DS_KEY_SLAVE).getConnection();
+                 Statement st = conn.createStatement();
+                 ResultSet rs = st.executeQuery("SELECT * FROM " + tableName + " LIMIT " + limit)) {
+                ResultSetMetaData meta = rs.getMetaData();
+                List<Integer> colIndexes = new ArrayList<>();
+                for (int i = 1; i <= meta.getColumnCount(); i++) {
+                    if (meta.getColumnLabel(i).startsWith("col_")) {
+                        colIndexes.add(i);
+                    }
+                }
+                while (rs.next()) {
+                    List<String> row = new ArrayList<>(colIndexes.size());
+                    for (Integer idx : colIndexes) {
+                        String value = rs.getString(idx);
+                        row.add(value == null ? "" : value);
+                    }
+                    grid.add(row);
+                }
+            }
+        } catch (Exception e) {
+            // 典型场景:未开案 slave 非 DuckDB、动态表不存在
+            log.error("查询动态表预览数据失败, table={}", tableName, e);
+            return dto;
+        }
+        if (grid.isEmpty()) {
+            return dto;
+        }
+        // 表头:headerRowIndex 指向网格中的表头行;无效时回退模板表头
+        Integer headerRowIndex = query.getHeaderRowIndex();
+        List<String> headers;
+        if (headerRowIndex != null && headerRowIndex >= 0 && headerRowIndex < grid.size()) {
+            headers = grid.get(headerRowIndex);
+        } else {
+            headers = CollUtil.isEmpty(query.getHeaders()) ? List.of() : query.getHeaders();
+        }
+        if (CollUtil.isEmpty(headers)) {
+            return dto;
+        }
+        // 全部行按表头映射(重复表头后者覆盖,缺列补空串),保持与原 Electron 返回形状一致
+        List<Map<String, String>> rows = new ArrayList<>(grid.size());
+        for (List<String> row : grid) {
+            Map<String, String> rowMap = new LinkedHashMap<>();
+            for (int i = 0; i < headers.size(); i++) {
+                String header = headers.get(i);
+                rowMap.put(header, i < row.size() ? row.get(i) : "");
+            }
+            rows.add(rowMap);
+        }
+        dto.setHeaders(headers);
+        dto.setRows(rows);
+        return dto;
+    }
+
     /** 解析器返回的平铺节点(根 pid=0 + 各 sheet, pid=文件id)组装成树;单文件只有一个根 */
     private List<FileInfo> buildPreviewTree(List<FileInfo> flat) {
         if (CollUtil.isEmpty(flat)) {

+ 2 - 2
ai-server/src/main/java/com/zsjz/ai/module/person/controller/DataProfileController.java

@@ -186,8 +186,8 @@ public class DataProfileController {
     //"亲密度-汇总")
     @GetMapping("/intimacySummary")
     //@Cache(key = "dp_intimacySummary_${personName}", tags = StrConsts.CACHE_TAG_QING_JIAN)
-    public List<IntimacyDTO> intimacySummary(String personName) {
-        return intimacyService.intimacySummary(personName);
+    public Result<List<IntimacyDTO>> intimacySummary(String personName) {
+        return Result.succeed(intimacyService.intimacySummary(personName));
     }
 
 }