cc 4 napja
szülő
commit
7f4c56aec8
36 módosított fájl, 354 hozzáadás és 1785 törlés
  1. 0 133
      ai-electron/electron/controller/downloadCtl.js
  2. 15 0
      ai-electron/electron/controller/osCtl.js
  3. 0 336
      ai-electron/electron/service/download/downloadService.js
  4. 21 0
      ai-electron/electron/service/os/os.js
  5. 9 9
      ai-electron/frontend/src/call/views/components/CallRecordModal.vue
  6. 1 1
      ai-electron/frontend/src/case/views/data/cleanProgress.vue
  7. 1 1
      ai-electron/frontend/src/case/views/data/cleaning.vue
  8. 2 5
      ai-electron/frontend/src/case/views/data/components/CaseFlowTopBar.vue
  9. 1 1
      ai-electron/frontend/src/case/views/data/edsUpload.vue
  10. 9 10
      ai-electron/frontend/src/case/views/data/importList.vue
  11. 17 20
      ai-electron/frontend/src/case/views/data/index.vue
  12. 1 1
      ai-electron/frontend/src/case/views/data/upload.vue
  13. 5 8
      ai-electron/frontend/src/core/api/sys/login.ts
  14. 0 4
      ai-electron/frontend/src/core/components/Application/index.ts
  15. 0 717
      ai-electron/frontend/src/core/components/Application/src/AppDownloadManager.vue
  16. 1 5
      ai-electron/frontend/src/core/layouts/default/header/index.vue
  17. 0 112
      ai-electron/frontend/src/core/utils/desktop/downloader.ts
  18. 26 0
      ai-electron/frontend/src/core/utils/desktop/openFile.ts
  19. 7 174
      ai-electron/frontend/src/core/utils/file/download.ts
  20. 14 37
      ai-electron/frontend/src/core/utils/openOfficeFile.ts
  21. 9 0
      ai-electron/frontend/src/eds/api/edsMediaApi.ts
  22. 0 16
      ai-electron/frontend/src/eds/api/edsTreeApi.ts
  23. 16 10
      ai-electron/frontend/src/eds/components/EdsMediaGallery.vue
  24. 5 5
      ai-electron/frontend/src/eds/config/edsMediaGalleryConfig.ts
  25. 0 29
      ai-electron/frontend/src/eds/utils/edsFormatters.ts
  26. 3 5
      ai-electron/frontend/src/plat/views/case/case.vue
  27. 20 46
      ai-electron/frontend/src/trans/api/baseStationQueryApi.ts
  28. 20 26
      ai-electron/frontend/src/trans/views/aiBaseStation/index.vue
  29. 9 9
      ai-electron/frontend/src/trans/views/components/TransRecordModal.vue
  30. 0 2
      ai-electron/frontend/uno.config.ts
  31. 7 0
      ai-server/pom.xml
  32. 6 0
      ai-server/src/main/java/com/zsjz/ai/module/eds/controller/EdsMediaController.java
  33. 51 0
      ai-server/src/main/java/com/zsjz/ai/module/eds/service/EdsMediaService.java
  34. 9 13
      ai-server/src/main/java/com/zsjz/ai/module/plat/controller/TowerController.java
  35. 25 4
      ai-server/src/main/java/com/zsjz/ai/module/plat/service/SystemService.java
  36. 44 46
      ai-server/src/main/java/com/zsjz/ai/module/plat/service/TowerService.java

+ 0 - 133
ai-electron/electron/controller/downloadCtl.js

@@ -1,133 +0,0 @@
-'use strict';
-
-import { BrowserWindow } from 'electron';
-import { downloadService } from '../service/download/downloadService';
-import { logger } from 'ee-core/log';
-
-/** 进度推送通道:界面订阅它刷新"下载中"的进度与状态 */
-export const DOWNLOAD_PROGRESS_CHANNEL = 'downloadCtl:progress';
-
-/**
- * 把 in-flight 状态推给所有渲染进程。
- *
- * <p>智能工作台顶栏也挂了下载管理器,且 AI 工具产物多半在那边产生;
- * 只发主窗口会让智能窗口永远看不到进度。
- */
-function broadcast(item) {
-  for (const win of BrowserWindow.getAllWindows()) {
-    if (win.isDestroyed() || win.webContents.isDestroyed()) continue;
-    try {
-      win.webContents.send(DOWNLOAD_PROGRESS_CHANNEL, item);
-    } catch (e) {
-      logger.warn('[downloadCtl] 广播下载进度失败:', e instanceof Error ? e.message : String(e));
-    }
-  }
-}
-
-/**
- * 下载管理器 IPC:通道名 controller/downloadCtl/<方法>(ee-core 按文件名自动注册)。
- *
- * 统一返回项目约定 {success, data|message}:失败(路径非法/记录不存在/文件被移走)不抛到 Electron 层,
- * 前端看 message 即可提示。
- */
-class DownloadCtl {
-  /** 保存一次下载:params { fileName, mime?, data(ArrayBuffer|base64), source? } */
-  async saveDownload(params) {
-    try {
-      return { success: true, data: downloadService.save(params) };
-    } catch (e) {
-      return { success: false, message: this.message(e, '下载失败') };
-    }
-  }
-
-  /**
-   * 后台下载:主进程流式拉取 URL 落盘并推送进度。
-   * params { url, fileName?, headers?, source?, mime? }
-   */
-  async startDownload(params) {
-    try {
-      downloadService.setNotifier(broadcast);
-      return { success: true, data: downloadService.start(params) };
-    } catch (e) {
-      return { success: false, message: this.message(e, '下载失败') };
-    }
-  }
-
-  /** 下载清单 + 当前生效目录 */
-  async listDownloads() {
-    try {
-      return { success: true, data: { dir: downloadService.getDownloadDir(), items: downloadService.list() } };
-    } catch (e) {
-      return { success: false, message: this.message(e, '读取下载列表失败') };
-    }
-  }
-
-  async getDownloadDir() {
-    try {
-      return { success: true, data: { dir: downloadService.getDownloadDir() } };
-    } catch (e) {
-      return { success: false, message: this.message(e, '读取下载目录失败') };
-    }
-  }
-
-  /** 设置下载目录;params { dir } 传空恢复系统默认 */
-  async setDownloadDir(params) {
-    try {
-      return { success: true, data: { dir: downloadService.setDownloadDir(params?.dir) } };
-    } catch (e) {
-      return { success: false, message: this.message(e, '设置下载目录失败') };
-    }
-  }
-
-  /** 用系统默认程序打开已下载的文件 */
-  async openDownloadFile(params) {
-    try {
-      return { success: true, data: await downloadService.openFile(params?.id) };
-    } catch (e) {
-      return { success: false, message: this.message(e, '打开文件失败') };
-    }
-  }
-
-  /** 在文件管理器里定位已下载的文件 */
-  async revealDownload(params) {
-    try {
-      return { success: true, data: downloadService.revealFile(params?.id) };
-    } catch (e) {
-      return { success: false, message: this.message(e, '定位文件失败') };
-    }
-  }
-
-  /** 打开下载目录 */
-  async openDownloadDir() {
-    try {
-      return { success: true, data: await downloadService.openDir() };
-    } catch (e) {
-      return { success: false, message: this.message(e, '打开下载目录失败') };
-    }
-  }
-
-  /** 只从清单移除记录,不删磁盘上的文件 */
-  async removeDownload(params) {
-    try {
-      return { success: true, data: downloadService.remove(params?.id) };
-    } catch (e) {
-      return { success: false, message: this.message(e, '移除记录失败') };
-    }
-  }
-
-  async clearDownloads() {
-    try {
-      return { success: true, data: downloadService.clear() };
-    } catch (e) {
-      return { success: false, message: this.message(e, '清空记录失败') };
-    }
-  }
-
-  message(error, fallback) {
-    const msg = error instanceof Error ? error.message : String(error);
-    logger.warn('[downloadCtl]', fallback, msg);
-    return msg || fallback;
-  }
-}
-
-export default DownloadCtl;

+ 15 - 0
ai-electron/electron/controller/osCtl.js

@@ -112,6 +112,21 @@ class OsCtl {
       return { success: false, message: msg };
     }
   }
+  /**
+   * 用系统默认关联程序打开本机文件(params: { filePath })。
+   *
+   * 路径由后端查库解析后传来;返回项目统一的 {success,data|message} 信封,
+   * 打开失败(路径非法/文件不存在/无文件关联等)不抛到 Electron 层,调用方看 message 即可。
+   */
+  async openPath(params) {
+    try {
+      return { success: true, data: await os.openPath(params) };
+    } catch (e) {
+      const msg = e instanceof Error ? e.message : String(e);
+      logger.warn('[osCtl] openPath failed:', msg);
+      return { success: false, message: msg };
+    }
+  }
   /**
    * 读取本机离线地图目录(未设置为空串)。
    *

+ 0 - 336
ai-electron/electron/service/download/downloadService.js

@@ -1,336 +0,0 @@
-'use strict';
-
-import { app, shell } from 'electron';
-import { getDataDir } from 'ee-core/ps';
-import { logger } from 'ee-core/log';
-import path from 'node:path';
-import fs from 'node:fs';
-import { randomUUID } from 'node:crypto';
-import { pipeline } from 'node:stream/promises';
-import { Readable, Transform } from 'node:stream';
-import { localSettingsService } from '../setting/localSettings';
-
-/** 本机设置里存下载目录的键名 */
-const DOWNLOAD_DIR_KEY = 'downloadDir';
-/** 下载清单:放在数据目录,不放进下载目录本身,免得混进用户的文件列表 */
-const MANIFEST_NAME = 'downloads.json';
-/** 清单最多保留多少条(文件仍在磁盘上,只是不再列出) */
-const MAX_ITEMS = 300;
-
-/**
- * 下载服务:把渲染进程拿到的文件流写进**本机下载目录**,并维护一份下载清单。
- *
- * <p>为什么放在主进程:浏览器另存(<a download>)在桌面端会落到系统默认下载目录、也留不下记录;
- * 这里统一落盘到可配置的目录,清单供「下载管理器」展示,并且能直接打开文件/所在目录。
- */
-class DownloadService {
-  get manifestPath() {
-    return path.join(getDataDir(), MANIFEST_NAME);
-  }
-
-  /** 生效的下载目录:本机设置优先,未配置用系统「下载」目录 */
-  getDownloadDir() {
-    const configured = localSettingsService.get(DOWNLOAD_DIR_KEY);
-    if (configured) return configured;
-    try {
-      return app.getPath('downloads');
-    } catch {
-      return path.join(getDataDir(), 'downloads');
-    }
-  }
-
-  /** 设置下载目录(必须是已存在的绝对目录;传空表示恢复系统默认) */
-  setDownloadDir(dir) {
-    const target = typeof dir === 'string' ? dir.trim() : '';
-    if (target) {
-      if (!path.isAbsolute(target)) throw new Error('只支持绝对路径');
-      if (!fs.existsSync(target)) throw new Error(`目录不存在:${target}`);
-      if (!fs.statSync(target).isDirectory()) throw new Error('请选择目录,而不是文件');
-    }
-    localSettingsService.set(DOWNLOAD_DIR_KEY, target);
-    return this.getDownloadDir();
-  }
-
-  /**
-   * 启动时清理「僵死」的下载中记录:进程重启后没有下载线程了,
-   * 这类记录若继续显示"下载中"会一直转不完,统一标成失败说明原因。
-   */
-  reconcileOnce() {
-    if (this.reconciled) return;
-    this.reconciled = true;
-    const items = this.readManifest();
-    const stale = items.filter((item) => item.status === 'downloading');
-    if (!stale.length) return;
-    this.writeManifest(
-      items.map((item) =>
-        item.status === 'downloading' ? { ...item, status: 'failed', message: '应用重启,下载已中断' } : item,
-      ),
-    );
-  }
-
-  readManifest() {
-    try {
-      const file = this.manifestPath;
-      if (!fs.existsSync(file)) return [];
-      const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
-      return Array.isArray(parsed?.items) ? parsed.items.filter((item) => item && typeof item.id === 'string') : [];
-    } catch (e) {
-      logger.warn('[download] 读取清单失败:', e instanceof Error ? e.message : String(e));
-      return [];
-    }
-  }
-
-  list() {
-    this.reconcileOnce();
-    return this.readManifest().map((item) => ({
-      ...item,
-      exists: !!item.savedPath && fs.existsSync(item.savedPath),
-    }));
-  }
-
-  writeManifest(items) {
-    const file = this.manifestPath;
-    fs.mkdirSync(path.dirname(file), { recursive: true });
-    fs.writeFileSync(file, `${JSON.stringify({ items: items.slice(0, MAX_ITEMS) }, null, 2)}\n`, 'utf8');
-  }
-
-  /** 文件名只保留纯名字,挡掉路径分隔符与相对路径,避免写出目录之外 */
-  sanitizeFileName(fileName) {
-    const base = String(fileName || '').split(/[\\/]/).pop() || '';
-    const cleaned = base.replace(/[\u0000-\u001f<>:"|?*]/g, '_').trim();
-    return cleaned || `download-${Date.now()}`;
-  }
-
-  /** 重名时自动加 (1)(2)…,不覆盖用户已有文件 */
-  resolveUniquePath(dir, fileName) {
-    const ext = path.extname(fileName);
-    const stem = fileName.slice(0, fileName.length - ext.length);
-    let candidate = path.join(dir, fileName);
-    let index = 0;
-    while (fs.existsSync(candidate)) {
-      index += 1;
-      candidate = path.join(dir, `${stem} (${index})${ext}`);
-    }
-    return candidate;
-  }
-
-  /**
-   * 保存一次下载。
-   * @param params { fileName: string, mime?: string, data: ArrayBuffer|Uint8Array|string(base64), source?: string }
-   */
-  save(params = {}) {
-    const fileName = this.sanitizeFileName(params?.fileName);
-    const raw = params?.data;
-    let buffer;
-    if (typeof raw === 'string') {
-      buffer = Buffer.from(raw, 'base64');
-    } else if (raw instanceof Uint8Array) {
-      buffer = Buffer.from(raw);
-    } else if (raw instanceof ArrayBuffer) {
-      buffer = Buffer.from(new Uint8Array(raw));
-    } else if (ArrayBuffer.isView(raw)) {
-      buffer = Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength);
-    } else {
-      throw new Error('下载内容为空或格式不支持');
-    }
-    if (!buffer.length) throw new Error('下载内容为空');
-
-    const dir = this.getDownloadDir();
-    fs.mkdirSync(dir, { recursive: true });
-    const target = this.resolveUniquePath(dir, fileName);
-    fs.writeFileSync(target, buffer);
-
-    const item = {
-      id: randomUUID(),
-      fileName: path.basename(target),
-      savedPath: target,
-      dir,
-      bytes: buffer.length,
-      status: 'done',
-      received: buffer.length,
-      total: buffer.length,
-      mime: typeof params?.mime === 'string' ? params.mime : '',
-      source: typeof params?.source === 'string' ? params.source : '',
-      at: new Date().toISOString(),
-    };
-    this.writeManifest([item, ...this.list()]);
-    logger.info('[download] 已保存:', target);
-    return item;
-  }
-
-  /** 进度回调:由 controller 接到 webContents.send 上,把 in-flight 状态推给界面 */
-  setNotifier(notifier) {
-    this.notifier = typeof notifier === 'function' ? notifier : null;
-  }
-
-  notify(item) {
-    try {
-      this.notifier?.(item);
-    } catch (e) {
-      logger.warn('[download] 进度推送失败:', e instanceof Error ? e.message : String(e));
-    }
-  }
-
-  /** 更新清单里的一条记录(不动其它条目),并把最新状态推给界面 */
-  patchItem(id, patch) {
-    const items = this.list();
-    const index = items.findIndex((item) => item.id === id);
-    if (index < 0) return null;
-    const next = { ...items[index], ...patch };
-    items[index] = next;
-    this.writeManifest(items);
-    this.notify(next);
-    return next;
-  }
-
-  /**
-   * 后台下载:主进程直接拉取 URL 落盘,边下边报进度(渲染进程不承担大文件内存与阻塞)。
-   *
-   * <p>先写 {@code <名字>.part},下完再改名,避免下载中就被当成完整文件用;
-   * 同名文件自动加 (1)(2),不覆盖已有文件。
-   *
-   * @param params { url, fileName?, headers?, source?, mime? }
-   */
-  start(params = {}) {
-    const url = String(params?.url || '').trim();
-    if (!url) throw new Error('下载地址为空');
-    if (!this.notifier) logger.warn('[download] 未设置进度回调,界面拿不到进度');
-
-    const fileName = this.sanitizeFileName(params?.fileName || '');
-    const dir = this.getDownloadDir();
-    fs.mkdirSync(dir, { recursive: true });
-
-    const item = {
-      id: randomUUID(),
-      fileName,
-      savedPath: '',
-      dir,
-      bytes: 0,
-      status: 'downloading',
-      received: 0,
-      total: 0,
-      mime: typeof params?.mime === 'string' ? params.mime : '',
-      source: typeof params?.source === 'string' ? params.source : '',
-      at: new Date().toISOString(),
-    };
-    this.writeManifest([item, ...this.list()]);
-    this.notify(item);
-
-    // 后台跑,不阻塞调用方;失败也只是把这条记录标成 failed
-    void this.run(item, url, params);
-    return item;
-  }
-
-  async run(item, url, params) {
-    const partPath = path.join(item.dir, `${item.fileName}.part`);
-    let lastNotify = 0;
-    try {
-      const response = await fetch(url, { headers: (params?.headers || {}) });
-      if (!response.ok) {
-        // 后端报错时响应体是 JSON({code,message}),尽量把原因带出来
-        let message = `下载失败:HTTP ${response.status}`;
-        try {
-          const text = await response.text();
-          const parsed = JSON.parse(text);
-          if (parsed?.message) message = parsed.message;
-        } catch {
-          // 不是 JSON 就沿用状态码
-        }
-        throw new Error(message);
-      }
-
-      const total = Number(response.headers.get('content-length') || 0);
-      this.patchItem(item.id, { total, mime: response.headers.get('content-type') || item.mime });
-
-      if (response.body) {
-        const counter = new Transform({
-          transform: (chunk, _encoding, callback) => {
-            item.received += chunk.length;
-            const now = Date.now();
-            if (now - lastNotify > 150) {
-              lastNotify = now;
-              this.patchItem(item.id, { received: item.received });
-            }
-            callback(null, chunk);
-          },
-        });
-        await pipeline(Readable.fromWeb(response.body), counter, fs.createWriteStream(partPath));
-      } else {
-        const buffer = Buffer.from(await response.arrayBuffer());
-        await fs.promises.writeFile(partPath, buffer);
-        item.received = buffer.length;
-      }
-
-      const target = this.resolveUniquePath(item.dir, item.fileName);
-      await fs.promises.rename(partPath, target);
-      const size = fs.statSync(target).size;
-      const finished = this.patchItem(item.id, {
-        status: 'done',
-        savedPath: target,
-        fileName: path.basename(target),
-        bytes: size,
-        received: size,
-        total: size,
-      });
-      logger.info('[download] 已保存:', target);
-      return finished;
-    } catch (e) {
-      const message = e instanceof Error ? e.message : String(e);
-      await fs.promises.rm(partPath, { force: true }).catch(() => undefined);
-      logger.warn('[download] 下载失败:', message);
-      return this.patchItem(item.id, { status: 'failed', message });
-    }
-  }
-
-  find(id) {
-    const item = this.list().find((entry) => entry.id === id);
-    if (!item) throw new Error('下载记录不存在');
-    return item;
-  }
-
-  remove(id) {
-    const items = this.list();
-    const next = items.filter((item) => item.id !== id);
-    if (next.length === items.length) throw new Error('下载记录不存在');
-    this.writeManifest(next);
-    return { removed: true };
-  }
-
-  clear() {
-    const count = this.list().length;
-    this.writeManifest([]);
-    return { cleared: count };
-  }
-
-  /** 用系统默认程序打开已下载的文件 */
-  async openFile(id) {
-    const item = this.find(id);
-    if (!fs.existsSync(item.savedPath)) {
-      throw new Error(`文件已被移动或删除:${item.savedPath}`);
-    }
-    const message = await shell.openPath(item.savedPath);
-    if (message) throw new Error(message);
-    return { path: item.savedPath };
-  }
-
-  /** 在文件管理器里定位到已下载的文件 */
-  revealFile(id) {
-    const item = this.find(id);
-    if (!fs.existsSync(item.savedPath)) {
-      throw new Error(`文件已被移动或删除:${item.savedPath}`);
-    }
-    shell.showItemInFolder(item.savedPath);
-    return { path: item.savedPath };
-  }
-
-  /** 打开下载目录本身 */
-  async openDir() {
-    const dir = this.getDownloadDir();
-    fs.mkdirSync(dir, { recursive: true });
-    const message = await shell.openPath(dir);
-    if (message) throw new Error(message);
-    return { path: dir };
-  }
-}
-
-export const downloadService = new DownloadService();

+ 21 - 0
ai-electron/electron/service/os/os.js

@@ -120,6 +120,27 @@ class Os {
     return fs.readFileSync(filePath, encoding);
   }
 
+  /**
+   * 用系统默认关联程序打开本机文件。
+   *
+   * 路径由后端查库解析后传来(后端与客户端同机),这里只做「绝对路径 + 真实文件」校验,
+   * 不限文件类型 —— 能不能打开交给操作系统关联决定,无关联时 openPath 会返回错误串。
+   *
+   * @param params { filePath: string }
+   * @returns { path: 已打开的绝对路径 }
+   */
+  async openPath(params = {}) {
+    const filePath = typeof params?.filePath === 'string' ? params.filePath.trim() : '';
+    if (!filePath) throw new Error('文件路径不能为空');
+    if (!path.isAbsolute(filePath)) throw new Error('只支持绝对路径');
+    if (!fs.existsSync(filePath)) throw new Error(`文件不存在:${filePath}`);
+    if (!fs.statSync(filePath).isFile()) throw new Error('目标是目录,不是文件');
+    // shell.openPath 成功返回空串,失败返回 OS 的错误描述(不抛异常),必须显式检查
+    const message = await shell.openPath(filePath);
+    if (message) throw new Error(message);
+    return { path: filePath };
+  }
+
   async getAppInfo() {
     return {
       version: app.getVersion(),

+ 9 - 9
ai-electron/frontend/src/call/views/components/CallRecordModal.vue

@@ -35,7 +35,7 @@
   import componentSetting from '@/core/settings/componentSetting';
   import { useMessage } from '@/core/hooks/web/useMessage';
   import {
-    downloadOfficeFileById,
+    openOfficeFileById,
     getOpenOfficeFileErrorMessage,
     resolveOfficeFileId,
   } from '@/core/utils/openOfficeFile';
@@ -215,18 +215,18 @@
     });
   };
 
-  /** 下载关联的归档表格(Web 化:浏览器另存,不再调起本地应用打开) */
-  const handleDownloadFile = async (record?: CallRecord) => {
+  /** 打开关联的归档表格:后端查库定位本机路径,交给系统默认关联程序打开 */
+  const handleOpenFile = async (record?: CallRecord) => {
     const fileId = resolveOfficeFileId(record);
     if (!fileId) {
-      createMessage.warning('当前记录没有关联的源文件,无法下载');
+      createMessage.warning('当前记录没有关联的源文件,无法打开');
       return;
     }
 
     try {
-      await downloadOfficeFileById(fileId);
+      await openOfficeFileById(fileId);
     } catch (error: any) {
-      createMessage.error(getOpenOfficeFileErrorMessage(error, '文件下载失败'));
+      createMessage.error(getOpenOfficeFileErrorMessage(error, '文件打开失败'));
     }
   };
 
@@ -242,9 +242,9 @@
       const query = buildJumpQuery(rawRecord);
       return [
         {
-          label: '下载文件',
-          // 不再按 fileId 置灰:没有来源文件时由 handleDownloadFile 明确提示原因
-          onClick: () => void handleDownloadFile(rawRecord),
+          label: '打开文件',
+          // 不再按 fileId 置灰:没有来源文件时由 handleOpenFile 明确提示原因
+          onClick: () => void handleOpenFile(rawRecord),
         },
         {
           label: '跳转',

+ 1 - 1
ai-electron/frontend/src/case/views/data/cleanProgress.vue

@@ -1,6 +1,6 @@
 <template>
   <div :class="prefixCls" class="case-clean-progress">
-    <!-- 清洗流程公共顶栏:品牌 / 案件 / 模板库 / 下载管理 / 窗口控制 -->
+    <!-- 清洗流程公共顶栏:品牌 / 案件 / 模板库 / 设置 / 窗口控制 -->
     <CaseFlowTopBar />
 
     <div class="page-body">

+ 1 - 1
ai-electron/frontend/src/case/views/data/cleaning.vue

@@ -1,6 +1,6 @@
 <template>
   <div :class="prefixCls" class="case-data-cleaning-page">
-    <!-- 清洗流程公共顶栏:品牌 / 案件 / 模板库 / 下载管理 / 窗口控制 -->
+    <!-- 清洗流程公共顶栏:品牌 / 案件 / 模板库 / 设置 / 窗口控制 -->
     <CaseFlowTopBar />
 
     <div class="page-body">

+ 2 - 5
ai-electron/frontend/src/case/views/data/components/CaseFlowTopBar.vue

@@ -8,9 +8,6 @@
         </Button>
       </Tooltip>
 
-      <!-- 下载管理:下载记录、保存位置与清空 / 刷新等操作,按主界面顶栏同款入口提供 -->
-      <AppDownloadManager />
-
       <!-- 设置:与主壳同一套侧边栏(地图 / 服务地址 / 系统服务 / 授权 / 关于产品) -->
       <SettingDrawer v-if="getShowSettingButton" />
     </template>
@@ -25,11 +22,11 @@
    *
    * 这三页是不套 LAYOUT 的全屏路由,公共顶栏只能由页面自己渲染;
    * 除品牌、案件、模式切换、账号与窗口控制外,这里补齐主界面顶栏的
-   * 「模板库」「下载管理」「设置」三个入口,避免进入清洗流程后功能断档。
+   * 「模板库」「设置」两个入口,避免进入清洗流程后功能断档。
    */
   import { computed, ref } from 'vue';
   import { Button, Tooltip } from 'ant-design-vue';
-  import { AppDownloadManager, AppTopBar } from '@/core/components/Application';
+  import { AppTopBar } from '@/core/components/Application';
   import { createAsyncComponent } from '@/core/utils/factory/createAsyncComponent';
   import { useRootSetting } from '@/core/hooks/setting/useRootSetting';
   import { Icon } from '@/core/components/Icon';

+ 1 - 1
ai-electron/frontend/src/case/views/data/edsUpload.vue

@@ -1,6 +1,6 @@
 <template>
   <div :class="prefixCls" class="case-eds-upload-page">
-    <!-- 清洗流程公共顶栏:品牌 / 案件 / 模板库 / 下载管理 / 窗口控制 -->
+    <!-- 清洗流程公共顶栏:品牌 / 案件 / 模板库 / 设置 / 窗口控制 -->
     <CaseFlowTopBar />
 
     <div class="page-body">

+ 9 - 10
ai-electron/frontend/src/case/views/data/importList.vue

@@ -86,7 +86,7 @@
   import type { FormProps } from '@/core/components/Form';
   import type { FileInfo } from '@/types';
   import { importFileList, deletedFileList, preFile } from '@/case/api/govern/governApi';
-  import { getOpenOfficeFileErrorMessage, downloadOfficeFileById } from '@/core/utils/openOfficeFile';
+  import { getOpenOfficeFileErrorMessage, openOfficeFileById } from '@/core/utils/openOfficeFile';
   import { FileStatusEnum } from '@/case/types/enum';
   import componentSetting from '@/core/settings/componentSetting';
   import CleanLogModal from './components/CleanLogModal.vue';
@@ -385,9 +385,9 @@
           },
         },
         {
-          label: '下载',
-          title: '下载',
-          onClick: handleDownloadFile.bind(this, record),
+          label: '打开文件',
+          title: '打开文件',
+          onClick: handleOpenFile.bind(this, record),
         },
       ];
     },
@@ -611,19 +611,18 @@
     }
   }
 
-  /** 下载该文件(Web 化:只传文件ID,服务端查库定位文件流,浏览器另存) */
-  async function handleDownloadFile(record: Partial<FileInfo>) {
+  /** 打开该文件:只传文件ID,后端查库定位本机路径,交给系统默认关联程序打开 */
+  async function handleOpenFile(record: Partial<FileInfo>) {
     const fileId = String(record.id ?? '').trim();
     if (!fileId) {
-      createMessage.warning('未获取到文件ID,暂时无法下载文件');
+      createMessage.warning('未获取到文件ID,暂时无法打开文件');
       return;
     }
 
     try {
-      const fileName = String(record.fileName ?? '').trim();
-      await downloadOfficeFileById(fileId, fileName || '文件');
+      await openOfficeFileById(fileId);
     } catch (error: any) {
-      createMessage.error(getOpenOfficeFileErrorMessage(error, '文件下载失败'));
+      createMessage.error(getOpenOfficeFileErrorMessage(error, '文件打开失败'));
     }
   }
 

+ 17 - 20
ai-electron/frontend/src/case/views/data/index.vue

@@ -282,7 +282,7 @@
   import GovernProgressModal from './components/GovernProgressModal.vue';
   import { getActiveImportProgress } from './importProgressSession';
   import {
-    downloadOfficeFileById,
+    openOfficeFileById,
     getOpenOfficeFileErrorMessage,
     resolveOfficeFileId,
   } from '@/core/utils/openOfficeFile';
@@ -318,7 +318,7 @@
   const CASE_IMPORT_FILE_REFRESH_EVENT = 'case-import-file:refresh';
 
   /**
-   * 记录里「下载文件」需要的字段:fileId 回查后端取文件流,fileName 只用于展示与兜底命名。
+   * 记录里「打开文件」需要的字段:fileId 回查后端取本机路径,fileName 只用于展示。
    * 其余列由后端表头决定(同一行既可能是话单字段也可能是勘察字段),不参与判断。
    */
   interface DownloadableFileRecord {
@@ -996,20 +996,20 @@
   };
 
   /**
-   * 下载记录关联的源文件(Web 化:只传文件ID,服务端查库定位文件流,浏览器另存)。
+   * 打开记录关联的源文件:只传文件ID,后端查库定位本机路径,再交给系统默认关联程序打开。
    *
-   * 下载落盘走统一出口(桌面端由下载管理器写到你配置的目录,见 core/utils/file/download.ts)。
+   * 统一出口见 core/utils/desktop/openFile.ts;非桌面端会提示「请在桌面客户端内打开」。
    */
-  const handleDownloadRecordFile = async (record: DownloadableFileRecord) => {
+  const handleOpenRecordFile = async (record: DownloadableFileRecord) => {
     const fileId = resolveOfficeFileId(record);
     if (!fileId) {
-      createMessage.warning('当前记录没有关联的源文件,无法下载');
+      createMessage.warning('当前记录没有关联的源文件,无法打开');
       return;
     }
     try {
-      await downloadOfficeFileById(fileId, String(record.fileName ?? '').trim() || '文件');
+      await openOfficeFileById(fileId);
     } catch (error) {
-      createMessage.error(getOpenOfficeFileErrorMessage(error, '文件下载失败'));
+      createMessage.error(getOpenOfficeFileErrorMessage(error, '文件打开失败'));
     }
   };
 
@@ -1021,7 +1021,7 @@
     fixed: 'right',
     align: 'center',
     customRender: ({ record }: { record: DownloadableFileRecord }) => {
-      // 不按 fileId 置灰:汇总行没有来源文件时由 handleDownloadRecordFile 明确提示原因
+      // 不按 fileId 置灰:汇总行没有来源文件时由 handleOpenRecordFile 明确提示原因
       return h(
         Button,
         {
@@ -1029,10 +1029,10 @@
           size: 'small',
           onClick: (event: MouseEvent) => {
             event.stopPropagation();
-            void handleDownloadRecordFile(record);
+            void handleOpenRecordFile(record);
           },
         },
-        { default: () => '下载文件' },
+        { default: () => '打开文件' },
       );
     },
   });
@@ -1240,7 +1240,7 @@
               },
               [
                 rawDisplayText ? h('span', rawDisplayText) : null,
-                // 不按 fileId 置灰:汇总行没有来源文件时由 handleDownloadRecordFile 明确提示原因
+                // 不按 fileId 置灰:汇总行没有来源文件时由 handleOpenRecordFile 明确提示原因
                 h(
                   Button,
                   {
@@ -1248,10 +1248,10 @@
                     size: 'small',
                     onClick: (event: MouseEvent) => {
                       event.stopPropagation();
-                      void handleDownloadRecordFile(record);
+                      void handleOpenRecordFile(record);
                     },
                   },
-                  { default: () => '下载文件' },
+                  { default: () => '打开文件' },
                 ),
               ],
             );
@@ -2500,8 +2500,7 @@
       }
 
       .disposition-modal,
-      .import-modal,
-      .download-modal {
+      .import-modal {
         display: flex;
         flex-direction: column;
         gap: 16px;
@@ -2525,15 +2524,13 @@
       }
 
       .disposition-actions,
-      .import-actions,
-      .download-actions {
+      .import-actions {
         display: flex;
         justify-content: flex-end;
         gap: 10px;
       }
 
-      .import-desc,
-      .download-tip {
+      .import-desc {
         color: #6b7280;
         font-size: 13px;
       }

+ 1 - 1
ai-electron/frontend/src/case/views/data/upload.vue

@@ -1,6 +1,6 @@
 <template>
   <div :class="prefixCls" class="case-upload-page">
-    <!-- 清洗流程公共顶栏:品牌 / 案件 / 模板库 / 下载管理 / 窗口控制 -->
+    <!-- 清洗流程公共顶栏:品牌 / 案件 / 模板库 / 设置 / 窗口控制 -->
     <CaseFlowTopBar />
 
     <div class="page-body">

+ 5 - 8
ai-electron/frontend/src/core/api/sys/login.ts

@@ -3,11 +3,11 @@
  * No deletion without permission, or be held responsible to law.
  * @author ThinkGem
  */
-import type { AxiosResponse } from 'axios';
 import { defHttp } from '@/core/utils/http/axios';
 import { Result } from '@/types/axios';
 import { useGlobSetting } from '@/core/hooks/setting';
 import { useAppStore } from '@/core/store/modules/app';
+import type { LocalFileRef } from '@/core/utils/desktop/openFile';
 
 const { adminPath, ctxPath } = useGlobSetting();
 
@@ -39,16 +39,13 @@ export const machineCodeApi = () =>
   defHttp.get<string>({ url: adminPath + '/sys/code', timeout: 10 * 1000 }, { errorMessageMode: 'none' });
 
 /**
- * 下载文件(原 /sys/openLocalFile、/sys/openOfficeFile 合并而来)。
+ * 取文件在本机的绝对路径,供桌面端用系统默认关联程序打开。
  *
  * <p>入参只传文件ID,服务端路径由后端查库得到(不接受任意路径);
- * 以 blob 读取、返回原生响应以便从 Content-Disposition 取文件名。
+ * 工作表行没有自身路径时后端会回退到所属文件根。
  */
-export const downloadFileApi = (fileId: string | number): Promise<AxiosResponse<Blob>> =>
-  defHttp.get<AxiosResponse<Blob>>(
-    { url: adminPath + '/sys/downloadFile', params: { fid: fileId }, responseType: 'blob', timeout: 3 * 60 * 1000 },
-    { errorMessageMode: 'none', skipErrorMessage: true, isReturnNativeResponse: true },
-  );
+export const getFilePathApi = (fileId: string | number) =>
+  defHttp.get<LocalFileRef>({ url: adminPath + '/sys/getFilePath', params: { fileId } });
 
 /**
  * 无外网授权激活(离线授权)。

+ 0 - 4
ai-electron/frontend/src/core/components/Application/index.ts

@@ -8,7 +8,6 @@ import windowControls from './src/WindowControls.vue';
 import appLocalePicker from './src/AppLocalePicker.vue';
 import appDarkModeToggle from './src/AppDarkModeToggle.vue';
 import appTopBar from './src/AppTopBar.vue';
-import appDownloadManager from './src/AppDownloadManager.vue';
 
 export { useAppProviderContext } from './src/useAppContext';
 
@@ -19,9 +18,6 @@ export const AppLocalePicker = withInstall(appLocalePicker);
 export const AppDarkModeToggle = withInstall(appDarkModeToggle);
 export const AppTopBar = withInstall(appTopBar);
 
-// 下载管理器(顶栏设置图标前):下载记录 + 下载目录设置
-export const AppDownloadManager = withInstall(appDownloadManager);
-
 // 无边框窗口的标题栏:与主界面 LayoutHeader 同款外观(logo + 操作区 + 窗口控制)
 export const AppHeader = withInstall(appHeader);
 

+ 0 - 717
ai-electron/frontend/src/core/components/Application/src/AppDownloadManager.vue

@@ -1,717 +0,0 @@
-<template>
-  <div
-    :class="['jeesite-header-action-button', `${prefixCls}-trigger`, { 'is-busy': activeCount > 0 }]"
-    @click="openModal(true)"
-  >
-    <span class="dl-trigger__icon"><Icon icon="i-mdi:download-outline" :size="20" /></span>
-    <span v-if="activeCount > 0" class="dl-trigger__badge">{{ activeCount }}</span>
-    <span v-else-if="items.length" class="dl-trigger__dot"></span>
-  </div>
-
-  <BasicModal v-bind="$attrs" title="下载管理" :width="720" :centered="true" :footer="null" @register="registerModal">
-    <div :class="prefixCls">
-      <!-- 保存位置:一行紧凑展示 -->
-      <div class="dl-path">
-        <span class="dl-path__icon"><FolderOutlined /></span>
-        <span class="dl-path__label">保存到</span>
-        <span class="dl-path__value">{{ downloadDir || '未获取到下载目录' }}</span>
-        <span class="dl-path__actions">
-          <button class="dl-text-btn" type="button" :disabled="!desktop || busy" @click="handleChangeDir">更改</button>
-          <button class="dl-text-btn" type="button" :disabled="!desktop || busy" @click="handleOpenDir">打开</button>
-        </span>
-      </div>
-
-      <!-- 下载记录 -->
-      <header class="dl-head">
-        <span class="dl-head__title">下载记录</span>
-        <span class="dl-head__count">{{ items.length }}</span>
-        <span class="dl-head__spacer"></span>
-        <Tooltip title="刷新列表">
-          <button class="dl-icon-btn" type="button" :disabled="!desktop || busy" @click="handleRefresh">
-            <ReloadOutlined />
-          </button>
-        </Tooltip>
-        <Tooltip title="清空记录(不删文件)">
-          <button
-            class="dl-icon-btn is-danger"
-            type="button"
-            :disabled="!desktop || !items.length || busy"
-            @click="handleClear"
-          >
-            <DeleteOutlined />
-          </button>
-        </Tooltip>
-      </header>
-
-      <div v-if="!desktop" class="dl-blank">
-        <DesktopOutlined class="dl-blank__icon" />
-        <div class="dl-blank__title">当前不在桌面客户端内</div>
-        <div class="dl-blank__desc">下载记录保存在本机,请在桌面客户端里查看与管理。</div>
-      </div>
-
-      <div v-else-if="!items.length" class="dl-blank">
-        <InboxOutlined class="dl-blank__icon" />
-        <div class="dl-blank__title">还没有下载记录</div>
-        <div class="dl-blank__desc">下载文件、导出报告后,会按上面的保存位置存到本机并出现在这里。</div>
-      </div>
-
-      <ul v-else class="dl-list">
-        <li v-for="item in items" :key="item.id" class="dl-item">
-          <div class="dl-item__icon" :class="`is-${fileKind(item.fileName)}`">
-            <SyncOutlined v-if="item.status === 'downloading'" spin />
-            <component :is="fileIcon(item.fileName)" v-else />
-          </div>
-
-          <div class="dl-item__main">
-            <div class="dl-item__name">{{ item.fileName }}</div>
-
-            <!-- 下载中:进度条 + 百分比 -->
-            <div v-if="item.status === 'downloading'" class="dl-item__progress">
-              <span class="dl-item__bar">
-                <span class="dl-item__bar-fill" :style="{ width: `${progressPercent(item)}%` }"></span>
-              </span>
-              <span class="dl-item__percent">{{ progressText(item) }}</span>
-            </div>
-
-            <div v-else-if="item.status === 'failed'" class="dl-item__meta is-failed">
-              <span>{{ item.message || '下载失败' }}</span>
-            </div>
-
-            <div v-else class="dl-item__meta">
-              <span>{{ formatSize(item.bytes) }}</span>
-              <span class="dl-item__dot">·</span>
-              <span>{{ formatTime(item.at) }}</span>
-              <span v-if="item.exists === false" class="dl-item__missing">
-                <ExclamationCircleOutlined />
-                文件已不在原位置
-              </span>
-            </div>
-          </div>
-
-          <!-- 行操作:文字按钮(下载中的记录不给「打开/所在目录」) -->
-          <div class="dl-item__actions">
-            <button
-              class="dl-text-btn"
-              type="button"
-              :disabled="busy || item.status === 'downloading'"
-              @click="handleOpenFile(item)"
-            >
-              打开
-            </button>
-            <button
-              class="dl-text-btn"
-              type="button"
-              :disabled="busy || item.status === 'downloading'"
-              @click="handleReveal(item)"
-            >
-              所在目录
-            </button>
-            <button class="dl-text-btn is-danger" type="button" :disabled="busy" @click="handleRemove(item)">
-              移除
-            </button>
-          </div>
-        </li>
-      </ul>
-    </div>
-  </BasicModal>
-</template>
-
-<script lang="ts" setup name="AppDownloadManager">
-  /**
-   * 下载管理器:弹框形式列出本机下载记录,支持打开文件 / 定位文件 / 移除记录与更改保存位置。
-   *
-   * <p>记录由主进程维护(见 electron/service/download/downloadService.js):页面里的下载都经
-   * core/utils/file/download.ts 落到「保存位置」这个目录,这里只是它的界面。入口在顶栏设置图标前。
-   */
-  import { computed, onBeforeUnmount, ref, unref, watch } from 'vue';
-  import { Tooltip } from 'ant-design-vue';
-  import {
-    DeleteOutlined,
-    DesktopOutlined,
-    ExclamationCircleOutlined,
-    FileExcelOutlined,
-    FileImageOutlined,
-    FilePdfOutlined,
-    FileTextOutlined,
-    FileWordOutlined,
-    FileZipOutlined,
-    FolderOpenOutlined,
-    FolderOutlined,
-    InboxOutlined,
-    ReloadOutlined,
-    SyncOutlined,
-  } from '@ant-design/icons-vue';
-  import { BasicModal, useModal } from '@/core/components/Modal';
-  import { Icon } from '@/core/components/Icon';
-  import { useDesign } from '@/core/hooks/web/useDesign';
-  import { useMessage } from '@/core/hooks/web/useMessage';
-  import { pickDirectory } from '@/core/utils/desktop/pathPicker';
-  import {
-    clearDownloads,
-    isDesktopDownloadAvailable,
-    listDownloads,
-    openDownloadDir,
-    openDownloadFile,
-    onDownloadProgress,
-    removeDownload,
-    revealDownload,
-    setDownloadDir,
-    type DownloadItem,
-  } from '@/core/utils/desktop/downloader';
-
-  const { prefixCls } = useDesign('app-download-manager');
-  const { createMessage, createConfirm } = useMessage();
-  const [registerModal, { openModal, closeModal, getOpen }] = useModal();
-
-  const desktop = isDesktopDownloadAvailable();
-  const busy = ref(false);
-  const downloadDir = ref('');
-  const items = ref<DownloadItem[]>([]);
-
-  /** 正在下载的条数:>0 时顶栏图标做动画 */
-  const activeCount = computed(() => items.value.filter((item) => item.status === 'downloading').length);
-
-  /** 进度百分比;服务端没给总大小时按"已下载多少"显示,不编造百分比 */
-  const progressPercent = (item: DownloadItem) => {
-    const total = Number(item.total) || 0;
-    const received = Number(item.received) || 0;
-    if (!total) return received > 0 ? 100 : 0;
-    return Math.min(100, Math.round((received / total) * 100));
-  };
-
-  const progressText = (item: DownloadItem) => {
-    const total = Number(item.total) || 0;
-    if (!total) return `已接收 ${formatSize(Number(item.received) || 0)}`;
-    return `${progressPercent(item)}%(${formatSize(Number(item.received) || 0)} / ${formatSize(total)})`;
-  };
-
-  /**
-   * 订阅主进程的进度推送:下载中/完成/失败都会来。
-   * 新记录(弹框没打开时开始的下载)也会在这里进列表,所以顶栏小圆点/动画一直准。
-   */
-  const stopProgress = onDownloadProgress((item) => {
-    if (!item?.id) return;
-    const index = items.value.findIndex((entry) => entry.id === item.id);
-    if (index >= 0) {
-      items.value[index] = { ...items.value[index], ...item };
-      return;
-    }
-    items.value = [item, ...items.value];
-  });
-
-  onBeforeUnmount(() => stopProgress());
-
-  /** 打开弹框时刷一次;关闭时也顺带取一次,用来决定顶栏入口要不要亮小圆点 */
-  watch(
-    () => unref(getOpen),
-    (open) => {
-      void refresh();
-    },
-    { immediate: false },
-  );
-  void refresh();
-
-  async function refresh() {
-    if (!desktop) return;
-    if (unref(getOpen)) busy.value = true;
-    try {
-      const result = await listDownloads();
-      downloadDir.value = result.dir;
-      items.value = result.items;
-    } catch (error) {
-      // 顶栏入口上的静默拉取失败不打扰用户;弹框打开时的失败要提示
-      if (unref(getOpen)) createMessage.error(error instanceof Error ? error.message : '读取下载列表失败');
-    } finally {
-      busy.value = false;
-    }
-  }
-
-  const handleRefresh = () => void refresh();
-
-  const formatSize = (bytes: number) => {
-    const size = Number(bytes) || 0;
-    if (size < 1024) return `${size} B`;
-    if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
-    if (size < 1024 * 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`;
-    return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`;
-  };
-
-  const formatTime = (at: string) => {
-    const date = new Date(at);
-    if (Number.isNaN(date.getTime())) return '';
-    const pad = (value: number) => String(value).padStart(2, '0');
-    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
-  };
-
-  /** 按扩展名归类,图标与底色跟着变(用 antd 图标组件,避免 UnoCSS 扫不到运行时拼的类名) */
-  const fileKind = (fileName: string) => {
-    const ext =
-      String(fileName || '')
-        .split('.')
-        .pop()
-        ?.toLowerCase() || '';
-    if (['xls', 'xlsx', 'csv'].includes(ext)) return 'excel';
-    if (['doc', 'docx'].includes(ext)) return 'word';
-    if (ext === 'pdf') return 'pdf';
-    if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg'].includes(ext)) return 'image';
-    if (['zip', 'rar', '7z', 'gz', 'tar'].includes(ext)) return 'zip';
-    return 'file';
-  };
-
-  const fileIcon = (fileName: string) => {
-    const kind = fileKind(fileName);
-    if (kind === 'excel') return FileExcelOutlined;
-    if (kind === 'word') return FileWordOutlined;
-    if (kind === 'pdf') return FilePdfOutlined;
-    if (kind === 'image') return FileImageOutlined;
-    if (kind === 'zip') return FileZipOutlined;
-    return FileTextOutlined;
-  };
-
-  async function handleChangeDir() {
-    const picked = await pickDirectory();
-    if (!picked) return;
-    busy.value = true;
-    try {
-      downloadDir.value = await setDownloadDir(picked);
-      createMessage.success('保存位置已更新');
-    } catch (error) {
-      createMessage.error(error instanceof Error ? error.message : '设置下载目录失败');
-    } finally {
-      busy.value = false;
-    }
-  }
-
-  async function handleOpenDir() {
-    try {
-      await openDownloadDir();
-    } catch (error) {
-      createMessage.error(error instanceof Error ? error.message : '打开下载目录失败');
-    }
-  }
-
-  async function handleOpenFile(item: DownloadItem) {
-    try {
-      await openDownloadFile(item.id);
-    } catch (error) {
-      // 文件被移动/删除时主进程会给出具体路径,顺便刷新一下列表状态
-      createMessage.error(error instanceof Error ? error.message : '打开文件失败');
-      void refresh();
-    }
-  }
-
-  async function handleReveal(item: DownloadItem) {
-    try {
-      await revealDownload(item.id);
-    } catch (error) {
-      createMessage.error(error instanceof Error ? error.message : '定位文件失败');
-    }
-  }
-
-  async function handleRemove(item: DownloadItem) {
-    try {
-      await removeDownload(item.id);
-      items.value = items.value.filter((entry) => entry.id !== item.id);
-    } catch (error) {
-      createMessage.error(error instanceof Error ? error.message : '移除记录失败');
-    }
-  }
-
-  function handleClear() {
-    createConfirm({
-      iconType: 'warning',
-      title: '清空下载记录',
-      content: '只清空列表,磁盘上的文件不会被删除。',
-      okText: '清空',
-      okType: 'primary',
-      okButtonProps: { danger: true },
-      cancelText: '取消',
-      onOk: async () => {
-        try {
-          await clearDownloads();
-          items.value = [];
-          createMessage.success('已清空下载记录');
-        } catch (error) {
-          createMessage.error(error instanceof Error ? error.message : '清空记录失败');
-        }
-      },
-    });
-  }
-</script>
-
-<style lang="less">
-  @prefix-cls: ~'jeesite-app-download-manager';
-
-  .@{prefix-cls}-trigger {
-    position: relative;
-
-    /* 图标盒自带字号与行高(不继承外层),保证传统壳与智能壳下大小、垂直居中一致 */
-    .dl-trigger__icon {
-      display: inline-flex;
-      align-items: center;
-      font-size: 20px;
-      line-height: 1;
-    }
-
-    /* 下载中:箭头上下轻跳,提示还有任务在跑 */
-    &.is-busy .dl-trigger__icon {
-      animation: dl-trigger-bob 1.1s ease-in-out infinite;
-    }
-
-    &__badge {
-      position: absolute;
-      top: 2px;
-      right: 3px;
-      min-width: 15px;
-      height: 15px;
-      padding: 0 4px;
-      font-size: 10px;
-      line-height: 15px;
-      color: #fff;
-      text-align: center;
-      background: #2f54eb;
-      border: 1px solid #fff;
-      border-radius: 8px;
-    }
-
-    &__dot {
-      position: absolute;
-      top: 9px;
-      right: 11px;
-      width: 6px;
-      height: 6px;
-      background: #2f54eb;
-      border: 1px solid #fff;
-      border-radius: 50%;
-    }
-  }
-
-  .@{prefix-cls} {
-    display: flex;
-    flex-direction: column;
-
-    /* 保存位置:一行,不占高度 */
-    .dl-path {
-      display: flex;
-      align-items: center;
-      gap: 8px;
-      height: 34px;
-      padding: 0 10px;
-      font-size: 12.5px;
-      background: #f6f8fc;
-      border: 1px solid #e8ecf4;
-      border-radius: 8px;
-
-      &__icon {
-        display: inline-flex;
-        font-size: 14px;
-        color: #2f54eb;
-        flex: 0 0 auto;
-      }
-
-      &__label {
-        color: #6b7280;
-        flex: 0 0 auto;
-      }
-
-      &__value {
-        min-width: 0;
-        overflow: hidden;
-        font-family: Consolas, Monaco, 'Courier New', monospace;
-        color: #374151;
-        white-space: nowrap;
-        text-overflow: ellipsis;
-        flex: 1 1 auto;
-      }
-
-      &__actions {
-        display: flex;
-        gap: 2px;
-        flex: 0 0 auto;
-      }
-    }
-
-    /* 纯文字小按钮(保存位置、行操作) */
-    .dl-text-btn {
-      padding: 0 8px;
-      font-size: 12px;
-      line-height: 22px;
-      color: #2f54eb;
-      background: transparent;
-      border: 0;
-      border-radius: 6px;
-      white-space: nowrap;
-      cursor: pointer;
-      transition: background 0.15s ease-out;
-
-      &:hover:not(:disabled) {
-        background: #e8eeff;
-      }
-
-      &.is-danger {
-        color: #d4380d;
-
-        &:hover:not(:disabled) {
-          background: #fdeceb;
-        }
-      }
-
-      &:disabled {
-        color: #b6bec9;
-        cursor: not-allowed;
-      }
-    }
-
-    /* 图标元素按钮(刷新 / 清空 / 行操作),与顶栏动作按钮同一观感 */
-    .dl-icon-btn {
-      display: inline-flex;
-      align-items: center;
-      justify-content: center;
-      width: 26px;
-      height: 26px;
-      padding: 0;
-      font-size: 14px;
-      color: #5b6472;
-      background: transparent;
-      border: 0;
-      border-radius: 7px;
-      cursor: pointer;
-      transition:
-        background 0.15s ease-out,
-        color 0.15s ease-out;
-
-      &:hover:not(:disabled) {
-        color: #2f54eb;
-        background: #e8eeff;
-      }
-
-      &.is-danger:hover:not(:disabled) {
-        color: #d4380d;
-        background: #fdeceb;
-      }
-
-      &:disabled {
-        color: #c9cfd8;
-        cursor: not-allowed;
-      }
-    }
-
-    .dl-head {
-      display: flex;
-      align-items: center;
-      gap: 6px;
-      margin-top: 12px;
-      padding-bottom: 8px;
-      border-bottom: 1px solid #eef1f6;
-
-      &__title {
-        font-size: 13.5px;
-        font-weight: 600;
-        color: #111827;
-      }
-
-      &__count {
-        padding: 0 7px;
-        font-size: 11px;
-        line-height: 17px;
-        color: #4b5563;
-        background: #eef2f7;
-        border-radius: 9px;
-      }
-
-      &__spacer {
-        flex: 1 1 auto;
-      }
-    }
-
-    .dl-list {
-      display: flex;
-      flex-direction: column;
-      gap: 6px;
-      margin: 10px 0 0;
-      padding: 0 4px 0 0;
-      max-height: 46vh;
-      overflow: auto;
-      list-style: none;
-    }
-
-    .dl-item {
-      display: flex;
-      align-items: center;
-      gap: 10px;
-      padding: 8px 10px;
-      border: 1px solid transparent;
-      border-radius: 9px;
-      transition:
-        border-color 0.15s ease-out,
-        background 0.15s ease-out;
-
-      &:hover {
-        background: #f8fafd;
-        border-color: #e8eefb;
-      }
-
-      &__icon {
-        display: flex;
-        align-items: center;
-        justify-content: center;
-        width: 34px;
-        height: 34px;
-        font-size: 16px;
-        border-radius: 9px;
-        flex: 0 0 auto;
-
-        &.is-excel {
-          color: #15803d;
-          background: #e8f7ee;
-        }
-
-        &.is-word {
-          color: #1d4ed8;
-          background: #e8efff;
-        }
-
-        &.is-pdf {
-          color: #b91c1c;
-          background: #fdecec;
-        }
-
-        &.is-image {
-          color: #7c3aed;
-          background: #f1ebfe;
-        }
-
-        &.is-zip {
-          color: #b45309;
-          background: #fdf1e3;
-        }
-
-        &.is-file {
-          color: #4b5563;
-          background: #eef1f6;
-        }
-      }
-
-      &__main {
-        min-width: 0;
-        flex: 1 1 auto;
-      }
-
-      &__name {
-        overflow: hidden;
-        font-size: 13px;
-        font-weight: 500;
-        color: #111827;
-        white-space: nowrap;
-        text-overflow: ellipsis;
-      }
-
-      &__meta {
-        display: flex;
-        align-items: center;
-        gap: 6px;
-        margin-top: 2px;
-        font-size: 11.5px;
-        color: #9ca3af;
-
-        &.is-failed {
-          color: #d4380d;
-        }
-      }
-
-      /* 下载进度 */
-      &__progress {
-        display: flex;
-        align-items: center;
-        gap: 8px;
-        margin-top: 4px;
-      }
-
-      &__bar {
-        position: relative;
-        height: 4px;
-        overflow: hidden;
-        background: #eef2f7;
-        border-radius: 3px;
-        flex: 1 1 auto;
-      }
-
-      &__bar-fill {
-        display: block;
-        height: 100%;
-        background: linear-gradient(90deg, #4f7cf7 0%, #2f54eb 100%);
-        border-radius: 3px;
-        transition: width 0.2s ease-out;
-      }
-
-      &__percent {
-        flex: 0 0 auto;
-        font-size: 11px;
-        color: #2f54eb;
-      }
-
-      &__dot {
-        color: #d1d5db;
-      }
-
-      &__missing {
-        display: inline-flex;
-        align-items: center;
-        gap: 3px;
-        padding: 0 6px;
-        font-size: 11px;
-        line-height: 16px;
-        color: #b45309;
-        background: #fdf1e3;
-        border-radius: 8px;
-      }
-
-      &__actions {
-        display: flex;
-        align-items: center;
-        gap: 4px;
-        flex: 0 0 auto;
-      }
-    }
-
-    @keyframes dl-trigger-bob {
-      0%,
-      100% {
-        transform: translateY(0);
-      }
-
-      50% {
-        transform: translateY(2px);
-      }
-    }
-
-    .dl-blank {
-      display: flex;
-      flex-direction: column;
-      align-items: center;
-      justify-content: center;
-      gap: 6px;
-      padding: 44px 0 34px;
-
-      &__icon {
-        margin-bottom: 4px;
-        font-size: 38px;
-        color: #cbd5e1;
-      }
-
-      &__title {
-        font-size: 13.5px;
-        font-weight: 600;
-        color: #4b5563;
-      }
-
-      &__desc {
-        max-width: 320px;
-        font-size: 12px;
-        line-height: 1.7;
-        color: #9ca3af;
-        text-align: center;
-      }
-    }
-  }
-</style>

+ 1 - 5
ai-electron/frontend/src/core/layouts/default/header/index.vue

@@ -43,9 +43,6 @@
 
       <!-- <FullScreen v-if="getShowFullScreen" class="fullscreen-item" /> -->
 
-      <!-- 下载管理器:放在设置图标前面 -->
-      <AppDownloadManager />
-
       <SettingDrawer v-if="getShowSetting" />
     </template>
   </AppTopBar>
@@ -59,7 +56,7 @@
   import { useRoute } from 'vue-router';
   import { propTypes } from '@/core/utils/propTypes';
   import { Button, Tooltip } from 'ant-design-vue';
-  import { AppDownloadManager, AppTopBar } from '@/core/components/Application';
+  import { AppTopBar } from '@/core/components/Application';
   import { AppSearch } from '@/core/components/Application';
   import { Icon } from '@/core/components/Icon';
   import { PageEnum } from '@/core/enums/pageEnum';
@@ -96,7 +93,6 @@
       FullScreen,
       AppSearch,
       ErrorAction,
-      AppDownloadManager,
       SettingDrawer,
       Tooltip,
       Icon,

+ 0 - 112
ai-electron/frontend/src/core/utils/desktop/downloader.ts

@@ -1,112 +0,0 @@
-import { invokeIpc, isDesktopDialogAvailable, onIpc } from '@/core/utils/desktop/ipcRenderer';
-
-/** 主进程 downloadCtl 的统一信封(见 electron/controller/downloadCtl.js) */
-type DownloadRpc<T> = { success: true; data: T } | { success: false; message: string };
-
-/** 一条下载记录 */
-export interface DownloadItem {
-  id: string;
-  /** 落盘后的文件名(重名时会加 (1)) */
-  fileName: string;
-  /** 本机绝对路径 */
-  savedPath: string;
-  /** 当时生效的下载目录 */
-  dir: string;
-  bytes: number;
-  mime: string;
-  /** 触发来源(页面/功能名,便于回查) */
-  source: string;
-  /** ISO 时间 */
-  at: string;
-  /** 下载状态:下载中 / 已完成 / 失败 */
-  status?: 'downloading' | 'done' | 'failed';
-  /** 已接收字节(下载中会不断更新) */
-  received?: number;
-  /** 总字节;服务端没给 content-length 时为 0 */
-  total?: number;
-  /** 失败原因(status=failed 时) */
-  message?: string;
-  /** 清单返回时带上的状态:文件是否还在原位置 */
-  exists?: boolean;
-}
-
-/** 进度推送通道,与主进程 downloadCtl 里的常量保持一致 */
-const DOWNLOAD_PROGRESS_CHANNEL = 'downloadCtl:progress';
-
-/** 订阅下载进度(下载中/完成/失败都会推),返回取消订阅函数 */
-export function onDownloadProgress(handler: (item: DownloadItem) => void): () => void {
-  return onIpc<DownloadItem>(DOWNLOAD_PROGRESS_CHANNEL, handler);
-}
-
-/**
- * 后台下载:让主进程直接拉 URL 落盘,返回初始记录(状态 downloading),
- * 进度通过 onDownloadProgress 推送。
- */
-export function startDownload(params: {
-  url: string;
-  fileName: string;
-  headers?: Record<string, string>;
-  mime?: string;
-  source?: string;
-}): Promise<DownloadItem> {
-  return callDownload<DownloadItem>('startDownload', params);
-}
-
-export interface DownloadListResult {
-  dir: string;
-  items: DownloadItem[];
-}
-
-/** 桌面端才有下载管理器;浏览器里退回浏览器另存 */
-export const isDesktopDownloadAvailable = () => isDesktopDialogAvailable();
-
-/** 解包信封:失败抛错,调用方负责提示(方法注册在 downloadCtl 控制器下,通道为 controller/downloadCtl/<method>) */
-async function callDownload<T>(method: string, params?: unknown): Promise<T> {
-  const result = await invokeIpc<DownloadRpc<T>>(method, params, 'downloadCtl');
-  if (!result) throw new Error(`桌面端无响应:${method}`);
-  if (!result.success) throw new Error(result.message || '操作失败');
-  return result.data;
-}
-
-/** 保存一次下载(data 直接传 ArrayBuffer,结构化克隆,不再转 base64) */
-export function saveDownload(params: {
-  fileName: string;
-  mime?: string;
-  data: ArrayBuffer | Uint8Array;
-  source?: string;
-}): Promise<DownloadItem> {
-  return callDownload<DownloadItem>('saveDownload', params);
-}
-
-export function listDownloads(): Promise<DownloadListResult> {
-  return callDownload<DownloadListResult>('listDownloads');
-}
-
-export function getDownloadDir(): Promise<string> {
-  return callDownload<{ dir: string }>('getDownloadDir').then((data) => data.dir);
-}
-
-/** 设置下载目录(传空恢复系统默认) */
-export function setDownloadDir(dir: string): Promise<string> {
-  return callDownload<{ dir: string }>('setDownloadDir', { dir }).then((data) => data.dir);
-}
-
-export function openDownloadFile(id: string): Promise<{ path: string }> {
-  return callDownload<{ path: string }>('openDownloadFile', { id });
-}
-
-export function revealDownload(id: string): Promise<{ path: string }> {
-  return callDownload<{ path: string }>('revealDownload', { id });
-}
-
-export function openDownloadDir(): Promise<{ path: string }> {
-  return callDownload<{ path: string }>('openDownloadDir');
-}
-
-export function removeDownload(id: string): Promise<{ removed: boolean }> {
-  return callDownload<{ removed: boolean }>('removeDownload', { id });
-}
-
-export function clearDownloads(): Promise<{ cleared: number }> {
-  return callDownload<{ cleared: number }>('clearDownloads');
-}

+ 26 - 0
ai-electron/frontend/src/core/utils/desktop/openFile.ts

@@ -0,0 +1,26 @@
+import { invokeIpc, isDesktopDialogAvailable } from '@/core/utils/desktop/ipcRenderer';
+
+export { isDesktopDialogAvailable };
+
+/** 主进程 osCtl.openPath 的返回(见 ai-electron/electron/controller/osCtl.js) */
+type OpenPathResult = { success: true; data: { path: string } } | { success: false; message: string };
+
+/** 后端各「取本机路径」接口统一返回的形状 */
+export interface LocalFileRef {
+  path: string;
+  fileName: string;
+}
+
+/**
+ * 用系统默认关联程序打开本机文件 —— 全项目唯一的「打开文件」原语。
+ *
+ * <p>路径一律由后端查库解析后传来(后端与客户端同机),前端不自己拼路径。
+ * 非桌面端由 invokeIpc 抛「当前环境不可用:请在桌面客户端内打开」;
+ * 打开失败(文件不存在、无文件关联等)抛主进程给出的 message,调用方负责提示。
+ */
+export async function openLocalPath(filePath: string): Promise<{ path: string }> {
+  const result = await invokeIpc<OpenPathResult>('openPath', { filePath });
+  if (!result) throw new Error('桌面端无响应:openPath');
+  if (!result.success) throw new Error(result.message || '打开文件失败');
+  return result.data;
+}

+ 7 - 174
ai-electron/frontend/src/core/utils/file/download.ts

@@ -1,50 +1,15 @@
 // import { openWindow } from '..';
-import type { AxiosResponse } from 'axios';
-import { dataURLtoBlob, urlToBase64 } from './base64Conver';
 import { defHttp } from '@/core/utils/http/axios';
-import { isDesktopDownloadAvailable, saveDownload } from '@/core/utils/desktop/downloader';
-import { useMessage } from '@/core/hooks/web/useMessage';
 
 /**
- * Download online pictures
- * @param url
- * @param filename
- * @param mime
- * @param bom
- */
-export function downloadByOnlineUrl(url: string, filename: string, mime?: string, bom?: BlobPart) {
-  urlToBase64(url).then((base64) => {
-    downloadByBase64(base64, filename, mime, bom);
-  });
-}
-
-/**
- * Download pictures based on base64
- * @param buf
- * @param filename
- * @param mime
- * @param bom
- */
-export function downloadByBase64(buf: string, filename: string, mime?: string, bom?: BlobPart) {
-  const base64Buf = dataURLtoBlob(buf);
-  downloadByData(base64Buf, filename, mime, bom);
-}
-
-/**
- * Download according to the background interface file stream
- * @param {*} data
- * @param {*} filename
- * @param {*} mime
- * @param {*} bom
+ * 浏览器里把 blob 另存为文件。
+ *
+ * <p>桌面端的「打开文件」一律走 {@code core/utils/desktop/openFile} 的 openLocalPath
+ * (系统默认关联程序),不再经过这里;本函数只剩浏览器场景与 dormant 的 Qrcode 组件在用。
  */
 export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
   const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
   const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
-  // 桌面端:交给主进程写到「下载目录」(可配置、有下载记录、能直接打开),不再用浏览器另存
-  if (isDesktopDownloadAvailable()) {
-    void saveBlobToManager(blob, filename);
-    return;
-  }
   const nav = window.navigator as any;
   if (typeof nav.msSaveBlob !== 'undefined') {
     nav.msSaveBlob(blob, filename);
@@ -90,109 +55,9 @@ export async function downloadByUrl({
   name = name && name.length >= 1 && name[1].replace("utf-8'zh_cn'", '');
   name = (name && decodeURIComponent(name)) || fileName || 'jeesite';
   downloadByData(res.data, name);
-  // axios({
-  //   url: url,
-  //   method: 'post',
-  //   data: data,
-  //   responseType: 'blob',
-  // })
-  //   .then((response) => {
-  //     let name = response.headers['content-disposition'];
-  //     name = name && name.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
-  //     name = name && name.length >= 1 && name[1].replace("utf-8'zh_cn'", '');
-  //     name = name && (decodeURIComponent(name) || fileName || 'jeesite');
-  //     downloadByData(response.data, name);
-  //   })
-  //   .catch((error) => {
-  //     console.error(error);
-  //   });
-
-  // const isChrome = window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
-  // const isSafari = window.navigator.userAgent.toLowerCase().indexOf('safari') > -1;
-
-  // if (/(iP)/g.test(window.navigator.userAgent)) {
-  //   console.error('Your browser does not support download!');
-  //   return false;
-  // }
-  // if (isChrome || isSafari) {
-  //   const link = document.createElement('a');
-  //   link.href = url;
-  //   link.target = target;
-
-  //   if (link.download !== undefined) {
-  //     link.download = fileName || url.substring(url.lastIndexOf('/') + 1, url.length);
-  //   }
-
-  //   if (document.createEvent) {
-  //     const e = document.createEvent('MouseEvents');
-  //     e.initEvent('click', true, true);
-  //     link.dispatchEvent(e);
-  //     return true;
-  //   }
-  // }
-  // if (url.indexOf('?') === -1) {
-  //   url += '?download';
-  // }
-
-  // openWindow(url, { target });
   return true;
 }
 
-/** 把字节串按 UTF-8 解码(RFC 2047 的 Q/B 两种编码最终都是字节流) */
-function decodeUtf8Bytes(bytes: string): string {
-  return new TextDecoder('utf-8').decode(Uint8Array.from(bytes, (c) => c.charCodeAt(0)));
-}
-
-/** 解码 RFC 2047 编码字(Spring 会在 filename="=?UTF-8?Q?...?=" 里用这种写法) */
-function decodeRfc2047(value: string): string {
-  const matched = value.match(/^=\?UTF-8\?([QB])\?(.+)\?=$/i);
-  if (!matched) return value;
-  const [, mode, payload] = matched;
-  try {
-    if (mode.toUpperCase() === 'B') {
-      return decodeUtf8Bytes(atob(payload));
-    }
-    const bytes = payload
-      .replace(/_/g, ' ')
-      .replace(/=([0-9A-F]{2})/gi, (_m, hex) => String.fromCharCode(parseInt(hex, 16)));
-    return decodeUtf8Bytes(bytes);
-  } catch {
-    return value;
-  }
-}
-
-/**
- * 从 Content-Disposition 响应头解析下载文件名。
- *
- * <p>兼容 Spring 生成的两种写法:RFC 5987 的 `filename*=UTF-8''%E4%B8%AD%E6%96%87.xlsx`
- * 优先,其次 ISO-8859-1/RFC 2047 的 `filename="=?UTF-8?Q?...?="`;
- * 都解析不到时回退到传入的默认名。
- */
-export function resolveDownloadFileName(disposition?: string | null, fallback = 'download'): string {
-  const raw = String(disposition ?? '');
-  if (!raw) return fallback;
-
-  const encoded = raw.match(/filename\*\s*=\s*([^;]+)/i);
-  if (encoded) {
-    const value = encoded[1].trim().replace(/^["']|["']$/g, '');
-    const sepIdx = value.indexOf("''");
-    const text = sepIdx === -1 ? value : value.slice(sepIdx + 2);
-    try {
-      const decoded = decodeURIComponent(text);
-      if (decoded) return decoded;
-    } catch {
-      if (text) return text;
-    }
-  }
-
-  const plain = raw.match(/filename\s*=\s*([^;]+)/i);
-  if (plain) {
-    const value = plain[1].trim().replace(/^["']|["']$/g, '');
-    if (value) return decodeRfc2047(value);
-  }
-  return fallback;
-}
-
 /** 后端异常时会以 JSON 返回(ResponseType 为 blob 时需手动识别),取出其中的 message */
 async function readBlobJsonMessage(blob: Blob): Promise<string> {
   if (!blob.type?.includes('json')) return '';
@@ -205,25 +70,9 @@ async function readBlobJsonMessage(blob: Blob): Promise<string> {
 }
 
 /**
- * 把「文件流响应」保存为浏览器下载。
- *
- * <p>配合 `defHttp` 的 `responseType: 'blob'` + `isReturnNativeResponse: true` 使用:
- * 从响应头取文件名,若响应体其实是后端错误 JSON 则抛出可读错误。
- */
-export async function saveBlobResponse(res: AxiosResponse<Blob>, fallbackName = 'download'): Promise<void> {
-  const blob = res?.data;
-  if (!(blob instanceof Blob)) {
-    throw new Error('文件下载失败:响应内容异常');
-  }
-  const errorMessage = await readBlobJsonMessage(blob);
-  if (errorMessage) throw new Error(errorMessage);
-  downloadByData(blob, resolveDownloadFileName(res?.headers?.['content-disposition'], fallbackName));
-}
-
-/**
- * 归一化下载失败的错误信息:blob 响应体里的后端 message 优先,其次 error.message
+ * 归一化文件操作失败的错误信息:blob 响应体里的后端 message 优先,其次 error.message
  */
-export async function resolveDownloadErrorMessage(error: any, fallback = '文件下载失败'): Promise<string> {
+export async function resolveDownloadErrorMessage(error: any, fallback = '文件操作失败'): Promise<string> {
   const data = error?.response?.data;
   if (data instanceof Blob) {
     const message = await readBlobJsonMessage(data);
@@ -233,20 +82,4 @@ export async function resolveDownloadErrorMessage(error: any, fallback = '文件
   if (/Network Error/i.test(raw)) return '网络异常,请检查网络连接';
   if (/timeout/i.test(raw)) return '请求超时,请稍后重试';
   return raw || fallback;
-}
-
-/** 桌面端下载:把 blob 交给主进程落盘,并提示结果(下载记录在「下载管理器」里) */
-async function saveBlobToManager(blob: Blob, fileName: string) {
-  const { createMessage } = useMessage();
-  try {
-    const item = await saveDownload({
-      fileName,
-      mime: blob.type || 'application/octet-stream',
-      data: await blob.arrayBuffer(),
-      source: window.location.hash || window.location.pathname,
-    });
-    createMessage.success(`已下载:${item.fileName}`);
-  } catch (error) {
-    createMessage.error(error instanceof Error ? error.message : '下载失败');
-  }
-}
+}

+ 14 - 37
ai-electron/frontend/src/core/utils/openOfficeFile.ts

@@ -1,8 +1,6 @@
-import { downloadFileApi } from '@/core/api/sys/login';
-import { resolveDownloadErrorMessage, saveBlobResponse } from '@/core/utils/file/download';
-import { isDesktopDownloadAvailable, startDownload } from '@/core/utils/desktop/downloader';
-import { useGlobSetting } from '@/core/hooks/setting';
-import { useMessage } from '@/core/hooks/web/useMessage';
+import { getFilePathApi } from '@/core/api/sys/login';
+import { resolveDownloadErrorMessage } from '@/core/utils/file/download';
+import { isDesktopDialogAvailable, openLocalPath } from '@/core/utils/desktop/openFile';
 
 const normalizeOfficeFileKey = (value: string) =>
   value
@@ -54,46 +52,25 @@ export const resolveOfficeFileId = (source: unknown): string | undefined => {
 };
 
 /**
- * 按文件ID下载文件(Web 端:浏览器另存为,不再调起服务端的本地应用程序打开)。
+ * 按文件ID打开文件:后端查库解析出本机绝对路径,再交给系统默认关联程序打开。
  *
- * <p>只传文件ID,服务端路径由后端查库定位(表行没有 filePath 时后端自动回退到所属文件根)。
+ * <p>只传文件ID,服务端路径由后端定位(工作表行没有 filePath 时后端自动回退到所属文件根)。
+ * 非桌面端直接抛「请在桌面客户端内打开」,不做浏览器另存回退。
  *
- * @param fileId       文件/工作表ID(file_info.id)
- * @param fallbackName 响应头里拿不到文件名时的兜底名
+ * @param fileId 文件/工作表ID(file_info.id)
  */
-/** 拼出后端下载接口的绝对地址(后台下载在主进程里跑,需要完整 URL 与鉴权头) */
-const buildDownloadUrl = (fileId: string | number) => {
-  const { apiUrl, urlPrefix, adminPath } = useGlobSetting();
-  const prefix = `${apiUrl || ''}${urlPrefix || ''}${adminPath || ''}`.replace(/\/+$/, '');
-  return `${prefix}/sys/downloadFile?fid=${encodeURIComponent(String(fileId))}`;
-};
-
-export const downloadOfficeFileById = async (fileId: string | number, fallbackName = '文件') => {
-  // 桌面端:交给主进程后台流式下载(能显示进度、不占渲染进程内存,下载记录里可打开)
-  if (isDesktopDownloadAvailable()) {
-    const { createMessage } = useMessage();
-    try {
-      const item = await startDownload({
-        url: buildDownloadUrl(fileId),
-        fileName: fallbackName,
-        source: '案件数据',
-      });
-      createMessage.success(`已开始下载:${item.fileName}`);
-      return;
-    } catch (error) {
-      throw new Error(getOpenOfficeFileErrorMessage(error, '文件下载失败'));
-    }
+export const openOfficeFileById = async (fileId: string | number) => {
+  if (!isDesktopDialogAvailable()) {
+    throw new Error('当前环境不可用:请在桌面客户端内打开');
   }
-
-  // 浏览器:沿用原来的「取 blob 再另存」
   try {
-    const response = await downloadFileApi(fileId);
-    await saveBlobResponse(response, fallbackName);
+    const { path } = await getFilePathApi(fileId);
+    await openLocalPath(path);
   } catch (error: any) {
     // 后端以 JSON 报错时(如文件不存在),把原始 message 提取出来
-    throw new Error(await resolveDownloadErrorMessage(error, '文件下载失败'));
+    throw new Error(await resolveDownloadErrorMessage(error, '文件打开失败'));
   }
 };
 
-export const getOpenOfficeFileErrorMessage = (error: any, fallback = '文件下载失败') =>
+export const getOpenOfficeFileErrorMessage = (error: any, fallback = '文件打开失败') =>
   error?.response?.data?.message || error?.message || fallback;

+ 9 - 0
ai-electron/frontend/src/eds/api/edsMediaApi.ts

@@ -1,6 +1,7 @@
 import { defHttp } from '@/core/utils/http/axios';
 import type { EdsMediaFile, EdsMediaTypeSummary, EdsPageResult } from './edsDto';
 import { edsPath, edsUrl } from './edsApiHelper';
+import type { LocalFileRef } from '@/core/utils/desktop/openFile';
 
 /** 媒体类型及后缀分组统计 */
 export const getEdsMediaTypeSummary = (collectTargetId: string, mediaType: string) =>
@@ -25,3 +26,11 @@ export const getEdsMediaDetailList = (
     url: edsUrl(`/media/getMediaDetail/${edsPath(collectTargetId)}/${edsPath(mediaType)}`),
     params: { suffixName, page, limit },
   });
+
+/**
+ * 取媒体文件在本机的绝对路径,供桌面端用系统默认关联程序打开。
+ *
+ * <p>预览仍走列表返回的 mediaUrl(URL 直接访问),本接口只服务「打开文件」动作。
+ */
+export const getEdsMediaLocalPath = (id: string | number) =>
+  defHttp.get<LocalFileRef>({ url: edsUrl('/media/getLocalPath'), params: { id } });

+ 0 - 16
ai-electron/frontend/src/eds/api/edsTreeApi.ts

@@ -9,22 +9,6 @@ export const getEdsDirTree = (collectTargetId: string) =>
     url: edsUrl(`/materialInfo/getDirTree/${edsPath(collectTargetId)}`),
   });
 
-/** 下载检材文件;返回 blob 与文件名,供页面触发保存 */
-export const downloadEdsMaterialFile = async (edsPathValue: string) => {
-  const response = await defHttp.get<any>(
-    {
-      url: edsUrl('/materialInfo/downloadFile'),
-      params: { edsPath: edsPathValue },
-      responseType: 'blob',
-    },
-    { isReturnNativeResponse: true, errorMessageMode: 'none' },
-  );
-  const contentDisposition = response.headers?.['content-disposition'] as string | undefined;
-  const matched = contentDisposition?.match(/filename\*=UTF-8''([^;]+)/i);
-  const fileName = matched?.[1] ? decodeURIComponent(matched[1]) : '';
-  return { blob: response.data as Blob, fileName };
-};
-
 /** 媒体/检材文件大小等静态参数占位,保持分页类型可复用 */
 export type EdsTreePageQuery = EdsPageQuery & { collectTargetId?: string };
 

+ 16 - 10
ai-electron/frontend/src/eds/components/EdsMediaGallery.vue

@@ -48,12 +48,12 @@
               </div>
             </template>
 
-            <div v-if="config.showPreviewButton || config.showDownloadButton" class="eds-media-gallery__actions">
+            <div v-if="config.showPreviewButton || config.showOpenButton" class="eds-media-gallery__actions">
               <Button v-if="config.showPreviewButton" type="link" size="small" @click="handlePreview(item)">
                 预览
               </Button>
-              <Button v-if="config.showDownloadButton" type="link" size="small" @click="handleDownload(item)">
-                下载
+              <Button v-if="config.showOpenButton" type="link" size="small" @click="handleOpen(item)">
+                打开文件
               </Button>
             </div>
           </div>
@@ -94,7 +94,10 @@
   import AnalysisPagination from '@/core/components/AnalysisPagination/src/AnalysisPagination.vue';
   import EdsMediaPreview from './EdsMediaPreview.vue';
   import type { EdsMediaFile } from '../api/edsDto';
-  import { downloadEdsRemoteFile, formatEdsBytes } from '../utils/edsFormatters';
+  import { formatEdsBytes } from '../utils/edsFormatters';
+  import { getEdsMediaLocalPath } from '../api/edsMediaApi';
+  import { openLocalPath } from '@/core/utils/desktop/openFile';
+  import { useMessage } from '@/core/hooks/web/useMessage';
 
   const props = withDefaults(
     defineProps<{
@@ -123,6 +126,8 @@
   const previewName = ref('');
   const previewType = ref<'VIDEO' | 'AUDIO' | 'OTHER'>('OTHER');
 
+  const { createMessage } = useMessage();
+
   const fileIcon = computed(() => {
     if (props.config.video) return VideoCameraOutlined;
     if (props.config.audio) return AudioOutlined;
@@ -192,13 +197,14 @@
     previewOpen.value = true;
   };
 
-  const handleDownload = async (item: EdsMediaFile) => {
-    const url = String(item.mediaSmallPath || item.mediaPath || '');
-    if (!url) return;
+  /** 打开文件:后端按 id 解析本机路径,交给系统默认关联程序;预览仍走 URL,不受影响 */
+  const handleOpen = async (item: EdsMediaFile) => {
+    if (!item.id) return;
     try {
-      await downloadEdsRemoteFile(url, item.mediaName);
-    } catch (error) {
-      console.error('媒体文件下载失败', error);
+      const { path } = await getEdsMediaLocalPath(item.id);
+      await openLocalPath(path);
+    } catch (error: any) {
+      createMessage.error(error?.message || '打开文件失败');
     }
   };
 

+ 5 - 5
ai-electron/frontend/src/eds/config/edsMediaGalleryConfig.ts

@@ -14,7 +14,7 @@ export interface EdsMediaGalleryConfig {
   video: boolean;
   other: boolean;
   showPreviewButton: boolean;
-  showDownloadButton: boolean;
+  showOpenButton: boolean;
   fetch: (
     context: { collectTargetId: string; rawData: EdsTreeNode },
     query: { suffixName: string; page: number; limit: number },
@@ -45,7 +45,7 @@ const configs: Record<string, EdsMediaGalleryConfig> = {
     video: false,
     other: false,
     showPreviewButton: false,
-    showDownloadButton: false,
+    showOpenButton: false,
     fetch: ({ collectTargetId }, { suffixName, page, limit }) =>
       getEdsMediaDetailList(collectTargetId, '02', suffixName, page, limit),
   },
@@ -58,7 +58,7 @@ const configs: Record<string, EdsMediaGalleryConfig> = {
     video: true,
     other: false,
     showPreviewButton: true,
-    showDownloadButton: true,
+    showOpenButton: true,
     fetch: ({ collectTargetId }, { suffixName, page, limit }) =>
       getEdsMediaDetailList(collectTargetId, '04', suffixName, page, limit),
   },
@@ -71,7 +71,7 @@ const configs: Record<string, EdsMediaGalleryConfig> = {
     video: false,
     other: false,
     showPreviewButton: true,
-    showDownloadButton: true,
+    showOpenButton: true,
     fetch: ({ collectTargetId }, { suffixName, page, limit }) =>
       getEdsMediaDetailList(collectTargetId, '03', suffixName, page, limit),
   },
@@ -84,7 +84,7 @@ const configs: Record<string, EdsMediaGalleryConfig> = {
     video: false,
     other: true,
     showPreviewButton: false,
-    showDownloadButton: true,
+    showOpenButton: true,
     fetch: ({ collectTargetId }, { suffixName, page, limit }) =>
       getEdsMediaDetailList(collectTargetId, '99', suffixName, page, limit),
   },

+ 0 - 29
ai-electron/frontend/src/eds/utils/edsFormatters.ts

@@ -68,32 +68,3 @@ export const removeEdsHtmlTags = (value: unknown) => String(value ?? '').replace
 export const scrollEdsElementIntoView = (element?: Element | null) => {
   element?.scrollIntoView({ behavior: 'smooth', block: 'center' });
 };
-
-/** 在浏览器内把远程文件保存到本地(/files/eds/** 免鉴权) */
-export const downloadEdsRemoteFile = async (url: string, fileName?: string) => {
-  const downloadName = fileName || url.split('/').pop() || 'download';
-  try {
-    const response = await fetch(url);
-    if (!response.ok) {
-      throw new Error(`下载失败:${response.status}`);
-    }
-    const blob = await response.blob();
-    const objectUrl = URL.createObjectURL(blob);
-    const link = document.createElement('a');
-    link.href = objectUrl;
-    link.download = downloadName;
-    document.body.appendChild(link);
-    link.click();
-    link.remove();
-    URL.revokeObjectURL(objectUrl);
-  } catch {
-    // 跨域且未开启 CORS 时 fetch 会失败,退回浏览器直接下载/打开
-    const link = document.createElement('a');
-    link.href = url;
-    link.download = downloadName;
-    link.target = '_blank';
-    document.body.appendChild(link);
-    link.click();
-    link.remove();
-  }
-};

+ 3 - 5
ai-electron/frontend/src/plat/views/case/case.vue

@@ -2,7 +2,7 @@
   <div :class="prefixCls" class="case-page">
     <AppHeader>
       <template #actions>
-        <!-- 模板库 / 下载管理 / 设置:与主界面顶栏保持同一套入口 -->
+        <!-- 模板库 / 设置:与主界面顶栏保持同一套入口 -->
         <Tooltip title="模板库">
           <Button
             type="text"
@@ -14,8 +14,6 @@
           </Button>
         </Tooltip>
 
-        <AppDownloadManager />
-
         <SettingDrawer v-if="getShowSettingButton" />
       </template>
     </AppHeader>
@@ -216,7 +214,7 @@
   import { useModal } from '@/core/components/Modal';
   import { useLoading } from '@/core/components/Loading';
   import { EmptyState } from '@/core/components/EmptyState';
-  import { AppDownloadManager, AppHeader } from '@/core/components/Application';
+  import { AppHeader } from '@/core/components/Application';
   import { Icon } from '@/core/components/Icon';
   import { createAsyncComponent } from '@/core/utils/factory/createAsyncComponent';
   import { useRootSetting } from '@/core/hooks/setting/useRootSetting';
@@ -1019,7 +1017,7 @@
 </style>
 
 <style lang="less">
-  /* 顶栏公共入口(模板库 / 下载管理 / 设置):AppHeader 不加载传统壳的动作区样式,这里补一份 */
+  /* 顶栏公共入口(模板库 / 设置):AppHeader 不加载传统壳的动作区样式,这里补一份 */
   .case-page .jeesite-header-action-button {
     display: inline-flex;
     align-items: center;

+ 20 - 46
ai-electron/frontend/src/trans/api/baseStationQueryApi.ts

@@ -5,9 +5,9 @@
  */
 import { defHttp } from '@/core/utils/http/axios';
 import { useGlobSetting } from '@/core/hooks/setting';
-import { downloadByData } from '@/core/utils/file/download';
 import type { Result, UploadFileParams } from '@/types/axios';
-import type { AxiosProgressEvent, AxiosResponse } from 'axios';
+import type { AxiosProgressEvent } from 'axios';
+import type { LocalFileRef } from '@/core/utils/desktop/openFile';
 
 const { adminPath, ctxAdminPath, ctxPath } = useGlobSetting();
 
@@ -80,39 +80,22 @@ export interface BaseStationImportResponse {
   result?: string | Recordable | null;
 }
 
-export type BaseStationTemplateResponse =
-  | string
-  | {
-      code?: number;
-      message?: string;
-      msg?: string;
-      data?: string | { path?: string; filePath?: string; file?: string } | null;
-      path?: string;
-      filePath?: string;
-      file?: string;
-    };
-
-export interface BaseStationConvertResponse {
-  code?: number;
-  message?: string;
-  msg?: string;
-  data?: string | Recordable | null;
-  path?: string;
-  result?: string | Recordable | null;
-}
-
 export const searchBaseStation = (params: BaseStationSearchParams) =>
   defHttp.get<BaseStationSearchResponse>({ url: adminPath + '/tower/qry', params });
 
 /**
- * 上传基站 xls 并转换(Web 化:文件上传到后端转换,结果以附件流返回)。
- * 返回原始 AxiosResponse:data 为转换结果 xlsx(blob),出错时为 JSON 错误体。
+ * 上传基站 xls 并转换,返回结果文件在本机的绝对路径(结果长期保留在 data/tower)。
+ *
+ * <p>uploadFile 直接走 axiosInstance.request、不经 transform,返回原始 AxiosResponse,
+ * 其 data 才是 Result 信封,所以这里手动解包。
  */
-export const uploadBaseStationConvert = (file: File, onUploadProgress?: (percent: number) => void) =>
-  defHttp.uploadFile<Blob>(
+export const uploadBaseStationConvert = async (
+  file: File,
+  onUploadProgress?: (percent: number) => void,
+): Promise<LocalFileRef> => {
+  const response = await defHttp.uploadFile<Result>(
     {
       url: ctxAdminPath + '/tower/covFile',
-      responseType: 'blob',
       timeout: 5 * 60 * 1000,
       onUploadProgress: (progressEvent: AxiosProgressEvent) => {
         if (!onUploadProgress || !progressEvent.total) return;
@@ -121,13 +104,16 @@ export const uploadBaseStationConvert = (file: File, onUploadProgress?: (percent
     },
     { name: 'file', file, filename: file.name },
   );
+  const body = response?.data;
+  if (!body || Number(body.code ?? 200) !== 200) {
+    throw new Error(body?.message || '基站文件转换失败');
+  }
+  return body.data as LocalFileRef;
+};
 
-/** 下载基站转换模板(Web 化:模板文件以附件流返回) */
-export const downloadBaseStationTemplate = (): Promise<AxiosResponse<Blob>> =>
-  defHttp.get<AxiosResponse<Blob>>(
-    { url: ctxAdminPath + '/tower/template', responseType: 'blob', timeout: 3 * 60 * 1000 },
-    { isReturnNativeResponse: true, errorMessageMode: 'none' },
-  );
+/** 取基站转换模板在本机的绝对路径 */
+export const getBaseStationTemplatePath = () =>
+  defHttp.get<LocalFileRef>({ url: ctxAdminPath + '/tower/template' });
 
 export const importBaseStationFile = (
   params: UploadFileParams,
@@ -147,15 +133,3 @@ export const importBaseStationFile = (
     },
     params,
   );
-
-export const fetchBaseStationTemplatePath = () =>
-  defHttp.get<BaseStationTemplateResponse>(
-    { url: adminPath + '/tower/tmpFile' },
-    { isTransformResponse: false, errorMessageMode: 'message' },
-  );
-
-export const convertBaseStationData = (file: string) =>
-  defHttp.get<string>(
-    { url: adminPath + '/tower/covFile', params: { file } },
-    { errorMessageMode: 'none', skipSuccessMessage: true },
-  );

+ 20 - 26
ai-electron/frontend/src/trans/views/aiBaseStation/index.vue

@@ -5,8 +5,8 @@
         <div class="qj-card-title">查询条件</div>
         <div class="qj-filter-actions">
           <div class="side-actions">
-            <!-- Web 化:模版与转换结果都通过浏览器下载,不再依赖 Electron 打开本机目录 -->
-            <Button :loading="templateLoading" @click="handleFetchTemplate">下载转换基站模版</Button>
+            <!-- 后端把模板/转换结果写到系统「下载」目录(文件名带时间戳),再按返回路径用系统默认关联程序打开 -->
+            <Button :loading="templateLoading" @click="handleOpenTemplate">打开转换基站模版</Button>
             <Button :loading="convertLoading" @click="convertFileInputRef?.click()">批量转换基站</Button>
             <input
               ref="convertFileInputRef"
@@ -80,13 +80,14 @@
   import { useMessage } from '@/core/hooks/web/useMessage';
   import { useTableSkill } from '@/core/hooks/web/useTableSkill';
   import {
-    downloadBaseStationTemplate,
+    getBaseStationTemplatePath,
     searchBaseStation,
     uploadBaseStationConvert,
     type BaseStationSearchLocation,
     type BaseStationSearchResponse,
   } from '@/trans/api/baseStationQueryApi';
-  import { downloadByData, resolveDownloadErrorMessage } from '@/core/utils/file/download';
+  import { resolveDownloadErrorMessage } from '@/core/utils/file/download';
+  import { isDesktopDialogAvailable, openLocalPath } from '@/core/utils/desktop/openFile';
   import BaseStationQueryMap, { type BaseStationMapPoint } from './components/BaseStationQueryMap.vue';
 
   type RadixMode = 'dec' | 'hex';
@@ -220,18 +221,14 @@
     } satisfies BaseStationMapPoint;
   };
 
-  /** 下载转换基站模版(Web 化:模板文件以附件流返回,浏览器直接另存) */
-  const handleFetchTemplate = async () => {
+  /** 打开转换基站模版:后端返回本机绝对路径,交给系统默认关联程序打开 */
+  const handleOpenTemplate = async () => {
     templateLoading.value = true;
     try {
-      const response = await downloadBaseStationTemplate();
-      const blob = response?.data;
-      if (!(blob instanceof Blob)) {
-        throw new Error('模版下载失败');
-      }
-      downloadByData(blob, '基站导入模板.xls');
+      const { path } = await getBaseStationTemplatePath();
+      await openLocalPath(path);
     } catch (error: any) {
-      createMessage.error(await resolveDownloadErrorMessage(error, '下载转换基站模版失败'));
+      createMessage.error(await resolveDownloadErrorMessage(error, '打开转换基站模版失败'));
     } finally {
       templateLoading.value = false;
     }
@@ -271,29 +268,26 @@
     mapPoints.value = [];
   };
 
-  /** Web 化:上传基站 xls → 后端转换 → 转换结果以附件流返回,浏览器直接另存 */
+  /** 上传基站 xls → 后端转换 → 用系统默认关联程序打开结果文件(结果长期保留在 data/tower) */
   const handleConvertFileChange = async (event: Event) => {
     const input = event.target as HTMLInputElement;
     const file = input.files?.[0] || null;
     input.value = '';
     if (!file) return;
 
+    // 转换要跑几分钟,浏览器里拿到结果也打不开:上传前先拦住,别白等
+    if (!isDesktopDialogAvailable()) {
+      createMessage.warning('请在桌面客户端内打开');
+      return;
+    }
+
     convertLoading.value = true;
     try {
-      const response = await uploadBaseStationConvert(file, (percent) => {
+      const { path } = await uploadBaseStationConvert(file, (percent) => {
         convertLoading.value = percent < 100;
       });
-      const blob = response?.data;
-      if (!(blob instanceof Blob)) {
-        throw new Error('转换结果下载失败');
-      }
-      if (blob.type?.includes('json')) {
-        // 后端以 JSON 报错(如文件格式问题)
-        const message = String(JSON.parse(await blob.text())?.message || '') || '基站文件转换失败';
-        throw new Error(message);
-      }
-      downloadByData(blob, '基站转换结果' + Date.now() + '.xlsx');
-      createMessage.success('基站转换完成,文件已下载');
+      await openLocalPath(path);
+      createMessage.success('基站转换完成,已保存到下载目录并打开');
     } catch (error: any) {
       createMessage.error(await resolveDownloadErrorMessage(error, '批量转换基站失败'));
     } finally {

+ 9 - 9
ai-electron/frontend/src/trans/views/components/TransRecordModal.vue

@@ -59,7 +59,7 @@
   import { Button, Radio } from 'ant-design-vue';
   import { useMessage } from '@/core/hooks/web/useMessage';
   import {
-    downloadOfficeFileById,
+    openOfficeFileById,
     getOpenOfficeFileErrorMessage,
     resolveOfficeFileId,
   } from '@/core/utils/openOfficeFile';
@@ -316,18 +316,18 @@
     });
   };
 
-  /** 下载关联的归档表格(Web 化:浏览器另存,不再调起本地应用打开) */
-  const handleDownloadFile = async (record?: TransRecord) => {
+  /** 打开关联的归档表格:后端查库定位本机路径,交给系统默认关联程序打开 */
+  const handleOpenFile = async (record?: TransRecord) => {
     const fileId = resolveOfficeFileId(record);
     if (!fileId) {
-      createMessage.warning('当前记录没有关联的源文件,无法下载');
+      createMessage.warning('当前记录没有关联的源文件,无法打开');
       return;
     }
 
     try {
-      await downloadOfficeFileById(fileId);
+      await openOfficeFileById(fileId);
     } catch (error: any) {
-      createMessage.error(getOpenOfficeFileErrorMessage(error, '文件下载失败'));
+      createMessage.error(getOpenOfficeFileErrorMessage(error, '文件打开失败'));
     }
   };
 
@@ -373,9 +373,9 @@
             }
           : null,
         {
-          label: '下载文件',
-          // 不再按 fileId 置灰:没有来源文件时由 handleDownloadFile 明确提示原因
-          onClick: () => void handleDownloadFile(rawRecord),
+          label: '打开文件',
+          // 不再按 fileId 置灰:没有来源文件时由 handleOpenFile 明确提示原因
+          onClick: () => void handleOpenFile(rawRecord),
         },
         {
           label: '跳转',

+ 0 - 2
ai-electron/frontend/uno.config.ts

@@ -57,8 +57,6 @@ export default defineConfig({
     'i-mdi:bank-transfer',
     // 登录页页脚的联系方式(phone-outline 上面已有)
     'i-mdi:email-outline',
-    // 顶栏下载管理器触发图标
-    'i-mdi:download-outline',
   ],
   presets: [
     presetWind3(),

+ 7 - 0
ai-server/pom.xml

@@ -203,6 +203,13 @@
             <version>3.5.17</version>
         </dependency>
 
+        <!-- 跨平台系统目录(下载目录):基站导入模板副本与转换结果落到系统「下载」 -->
+        <dependency>
+            <groupId>net.harawata</groupId>
+            <artifactId>appdirs</artifactId>
+            <version>1.5.0</version>
+        </dependency>
+
         <dependency>
             <groupId>com.baomidou</groupId>
             <artifactId>dynamic-datasource-spring-boot3-starter</artifactId>

+ 6 - 0
ai-server/src/main/java/com/zsjz/ai/module/eds/controller/EdsMediaController.java

@@ -44,6 +44,12 @@ public class EdsMediaController {
                 query(collectTargetId, mediaType, suffixName, page, limit)));
     }
 
+    /** 媒体文件在本机的绝对路径,供桌面端用系统默认关联程序打开(预览仍走 mediaUrl)。 */
+    @GetMapping("/getLocalPath")
+    public Result<EdsMediaService.LocalFile> getLocalPath(@RequestParam Long id) {
+        return Result.succeed(mediaService.getLocalPath(id));
+    }
+
     private EdsMediaQuery query(String collectTargetId, String mediaType, String suffixName,
                                 long page, long limit) {
         EdsMediaQuery query = new EdsMediaQuery();

+ 51 - 0
ai-server/src/main/java/com/zsjz/ai/module/eds/service/EdsMediaService.java

@@ -3,14 +3,22 @@ package com.zsjz.ai.module.eds.service;
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.util.StrUtil;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.zsjz.ai.common.context.CaseContextHolder;
+import com.zsjz.ai.common.exception.ServerException;
+import com.zsjz.ai.common.storage.StorageLayout;
+import com.zsjz.ai.common.utils.WorkspacePathGuard;
 import com.zsjz.ai.module.eds.dto.EdsMediaFileDTO;
 import com.zsjz.ai.module.eds.dto.EdsMediaTypeCountDTO;
 import com.zsjz.ai.module.eds.dto.EdsMediaTypeDTO;
+import com.zsjz.ai.module.eds.mapper.EdsMediaFileMapper;
 import com.zsjz.ai.module.eds.mapper.EdsMediaQueryMapper;
+import com.zsjz.ai.module.eds.po.EdsMediaFile;
 import com.zsjz.ai.module.eds.query.EdsMediaQuery;
 import lombok.RequiredArgsConstructor;
 import org.springframework.stereotype.Service;
 
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -33,6 +41,49 @@ public class EdsMediaService {
     private static final String ALL_SUFFIX = "全部";
 
     private final EdsMediaQueryMapper mediaQueryMapper;
+    private final EdsMediaFileMapper mediaFileMapper;
+    private final StorageLayout storageLayout;
+    private final WorkspacePathGuard workspacePathGuard;
+
+    /**
+     * 媒体文件在本机的绝对路径 + 展示名,供桌面端用系统默认关联程序打开。
+     *
+     * <p>path 直接用 String:全局 ObjectMapper 未注册 {@code java.nio.file.Path} 序列化器。
+     */
+    public record LocalFile(String path, String fileName) {
+    }
+
+    /**
+     * 按媒体文件 id 取本机路径。
+     *
+     * <p>入参只接受 id、不接受服务端路径,与 {@code /sys/downloadFile} 同一套安全约定。
+     * 预览仍走 {@code mediaUrl} 那条 URL 链路,本方法不影响它。
+     *
+     * <p>{@code eds_media_file} 在案件 DuckDB(mapper 标了 {@code @DS(slave)}),必须开案才能查。
+     */
+    public LocalFile getLocalPath(Long id) {
+        if (id == null) {
+            throw ServerException.build("媒体文件ID不能为空!");
+        }
+        EdsMediaFile media = mediaFileMapper.selectById(id);
+        if (media == null) {
+            throw ServerException.build("媒体文件不存在!");
+        }
+        String storedPath = media.getMediaPath();
+        if (StrUtil.isBlank(storedPath)) {
+            throw ServerException.build("该媒体文件没有本机存储路径!");
+        }
+        Long caseId = CaseContextHolder.currentCaseId();
+        Path path = (caseId != null)
+                ? workspacePathGuard.requireInsideWorkspace(caseId, storedPath)
+                : storageLayout.resolve(storedPath);
+        if (!Files.isRegularFile(path)) {
+            throw ServerException.build("文件不存在或已被清理!");
+        }
+        String fileName = StrUtil.isBlank(media.getMediaName())
+                ? path.getFileName().toString() : media.getMediaName();
+        return new LocalFile(path.toAbsolutePath().toString(), fileName);
+    }
 
     public EdsMediaTypeDTO getMediaType(EdsMediaQuery query) {
         List<String> mediaTypes = parseMediaTypes(query.getMediaType());

+ 9 - 13
ai-server/src/main/java/com/zsjz/ai/module/plat/controller/TowerController.java

@@ -1,25 +1,22 @@
 package com.zsjz.ai.module.plat.controller;
 
+import com.zsjz.ai.module.plat.service.SystemService;
 import com.zsjz.ai.module.plat.service.TowerService;
 import com.zsjz.ai.common.config.Result;
 
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.Resource;
-import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestPart;
 import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.multipart.MultipartFile;
 
 import java.util.List;
 
 /**
  * 基站查询与基站文件转换
  *
- * <p>注意:{@code /covFile}(上传 xls 并转换)与 {@code /template}(下载转换模板)是**文件接口**,
- * 刻意不返回 {@code Result} 包装(前者响应体是转换后的 xlsx 文件流,后者是模板文件流)。
+ * <p>{@code /covFile}(上传 xls 并转换)与 {@code /template}(取转换模板)都返回
+ * {@code Result<DownloadFile>},即结果文件在本机的绝对路径 —— 桌面端据此用系统默认关联程序打开。
  */
 @RestController
 @RequestMapping("/tower")
@@ -34,21 +31,20 @@ public class TowerController {
     }
 
     /**
-     * 上传基站 xls 并转换,转换结果以附件流返回(Web 化:浏览器直接另存,
-     * 替代原「前端传服务端路径转换 + Electron 打开文件夹」的方式)。
+     * 上传基站 xls 并转换,返回结果文件的绝对路径(结果长期保留在 data/tower)。
      *
      * @param file 基站数据文件(xls/xlsx,按模板填写)
      */
     @PostMapping(value = "/covFile", consumes = org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE)
-    public ResponseEntity<Resource> covFile(@org.springframework.web.bind.annotation.RequestPart("file") org.springframework.web.multipart.MultipartFile file) {
-        return towerService.convertUpload(file);
+    public Result<SystemService.DownloadFile> covFile(@org.springframework.web.bind.annotation.RequestPart("file") org.springframework.web.multipart.MultipartFile file) {
+        return Result.succeed(towerService.convertUpload(file));
     }
 
     /**
-     * 下载基站转换模板(Web 化:替代原「返回模板路径 + Electron 打开文件夹」)。
+     * 取基站转换模板的绝对路径。
      */
     @GetMapping("/template")
-    public ResponseEntity<Resource> template() {
-        return towerService.downloadTemplate();
+    public Result<SystemService.DownloadFile> template() {
+        return Result.succeed(towerService.downloadTemplate());
     }
 }

+ 25 - 4
ai-server/src/main/java/com/zsjz/ai/module/plat/service/SystemService.java

@@ -9,6 +9,8 @@ import cn.hutool.core.util.StrUtil;
 import cn.hutool.core.util.ZipUtil;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.spring.service.impl.ServiceImpl;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
 import com.zsjz.ai.common.cache.CaseDataCache;
 import com.zsjz.ai.common.cache.GlobalCache;
 import com.zsjz.ai.common.constants.CmdConstants;
@@ -391,23 +393,42 @@ public class SystemService extends ServiceImpl<SystemInfoMapper, SystemInfo> {
     }
 
     /**
-     * 待下载文件:服务端绝对路径 + 下载时展示的文件名
+     * 待下载/待打开文件:服务端绝对路径 + 展示的文件名。
+     *
+     * <p>path 显式用 toString 序列化:全局 ObjectMapper 没注册 {@code java.nio.file.Path}
+     * 序列化器,默认会按 WindowsPath 的 getter 递归展开成嵌套对象,前端拿不到可用路径。
+     * 内部仍保留 Path 类型供 {@link #downloadFile} 等使用。
      */
-    public record DownloadFile(Path path, String fileName) {
+    public record DownloadFile(@JsonSerialize(using = ToStringSerializer.class) Path path, String fileName) {
     }
 
 
+    /**
+     * 取文件在本机的绝对路径,供桌面端用系统默认关联程序打开。
+     *
+     * <p>与 {@link #resolveDownloadFile} 的区别:不做 csv/xls/xlsx 白名单 —— 打开文件要支持
+     * pdf/图片/音视频/docx 等,能不能打开交给操作系统关联决定。
+     */
     public DownloadFile getFilePath(String fileId) {
         FileInfo fileInfo = fileInfoMapper.selectById(fileId);
         if (fileInfo == null) {
             throw ServerException.build("文件不存在!");
         }
-        String filePath = fileInfo.getFilePath();
+        // 工作表行自身没有 filePath(只有 pid 指向文件根),必须回退,否则归档表格里的行打不开
+        String filePath = resolveFilePath(fileInfo);
+        if (StrUtil.isBlank(filePath)) {
+            throw ServerException.build("该记录没有可打开的源文件!");
+        }
         Long caseId = CaseContextHolder.currentCaseId();
         Path path = (caseId != null)
                 ? workspacePathGuard.requireInsideWorkspace(caseId, filePath)
                 : storageLayout.resolve(filePath);
-        return new DownloadFile(path, fileInfo.getFileName());
+        if (!Files.isRegularFile(path)) {
+            throw ServerException.build("文件不存在或已被清理!");
+        }
+        String fileName = StrUtil.isBlank(fileInfo.getFileName())
+                ? path.getFileName().toString() : fileInfo.getFileName();
+        return new DownloadFile(path.toAbsolutePath(), fileName);
     }
 
 

+ 44 - 46
ai-server/src/main/java/com/zsjz/ai/module/plat/service/TowerService.java

@@ -1,6 +1,5 @@
 package com.zsjz.ai.module.plat.service;
 
-import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.lang.Assert;
 import cn.hutool.core.util.ObjectUtil;
 import cn.hutool.core.util.StrUtil;
@@ -10,23 +9,16 @@ import com.zsjz.ai.common.model.plat.dto.TowerConvertDTO;
 import com.zsjz.ai.common.storage.StorageLayout;
 import com.zsjz.ai.common.utils.TowerUtils;
 import lombok.extern.slf4j.Slf4j;
+import net.harawata.appdirs.AppDirsFactory;
 import org.apache.fesod.sheet.FesodSheet;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.FileSystemResource;
-import org.springframework.core.io.Resource;
-import org.springframework.http.ContentDisposition;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.IOException;
 import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.nio.file.Paths;
 import java.nio.file.StandardCopyOption;
 import java.util.ArrayList;
 import java.util.List;
@@ -35,9 +27,23 @@ import java.util.List;
 @Service
 public class TowerService {
 
+    /** 模板副本、转换结果都落到系统「下载」目录 */
+    private static final String TEMPLATE_BASE_NAME = "基站导入模板";
+    private static final String RESULT_BASE_NAME = "基站转换结果";
+
     @Autowired
     private StorageLayout storageLayout;
 
+    /**
+     * 系统下载目录(跨平台:Windows「下载」/ Linux XDG / macOS ~/Downloads)。
+     *
+     * <p>appName / appVersion / appAuthor 必须全传 null —— appdirs 会把非空值追加在
+     * 下载目录后面,那就变成自定义子目录而不是系统「下载」了。
+     */
+    private static Path downloadsDir() {
+        return Path.of(AppDirsFactory.getInstance().getUserDownloadsDir(null, null, null));
+    }
+
     public List<String> qry(String mnc, String lac, String ci) {
         if (StrUtil.isEmpty(lac) && StrUtil.isEmpty(ci)) {
             return List.of();
@@ -67,29 +73,16 @@ public class TowerService {
         return record;
     }
 
-    public String covFile(String file) {
-        Path path = Paths.get(file);
-        if (Files.notExists(path)) {
-            throw new ServerException("文件不存在!");
-        }
-        String userDownloadsDir = "AppDirsFactory.getInstance().getUserDownloadsDir(null, null, null)";
-        String fileName = "基站转换结果" + System.currentTimeMillis() + ".xlsx";
-        Path exportPath = Paths.get(userDownloadsDir, fileName);
-        String exportPathStr = exportPath.toAbsolutePath().normalize().toString();
-        TowerListener towerListener = new TowerListener(exportPathStr);
-        FesodSheet.read(path.toFile(), TowerConvertDTO.class, towerListener).sheet().headRowNumber(2).numRows(50000).doRead();
-        return exportPathStr;
-    }
-
     /**
-     * 上传基站 xls 并转换(Web 化:接收浏览器上传的文件,转换结果以附件流返回给浏览器下载)。
+     * 上传基站 xls 并转换,返回结果文件在本机的绝对路径。
      *
-     * <p>原实现「返回服务端路径 + Electron 打开文件夹」依赖客户端与服务端同机,纯 Web 下不成立。
+     * <p>桌面端拿到路径后用系统默认关联程序打开,不再走「附件流 + 浏览器另存」。
+     * 转换结果直接生成到系统「下载」目录(文件名带毫秒时间戳),上传件落 {@code data/tmp} 并即时清理。
      *
      * @param file 按模板填写的基站数据文件(xls/xlsx,≤50000 行)
-     * @return 转换结果 xlsx 的附件响应
+     * @return 转换结果 xlsx 的绝对路径与文件名
      */
-    public ResponseEntity<Resource> convertUpload(MultipartFile file) {
+    public SystemService.DownloadFile convertUpload(MultipartFile file) {
         Assert.isTrue(file != null && !file.isEmpty(), () -> ServerException.build("请选择基站文件!"));
         String originalName = String.valueOf(file.getOriginalFilename());
         String ext = originalName.toLowerCase().endsWith(".xlsx") ? ".xlsx" : ".xls";
@@ -97,17 +90,19 @@ public class TowerService {
             throw new ServerException("仅支持 xls、xlsx 文件!");
         }
 
-        // 落盘到 data/tmp/tower-<ts>/,转换完成后统一清理
+        // 上传件落 data/tmp/tower-<ts>/,转换完成后立即清理
         Path workDir = storageLayout.globalTmpDir().resolve("tower-" + System.currentTimeMillis());
         Path uploaded = null;
-        Path output = null;
+        Path output;
         try {
             Files.createDirectories(workDir);
+            Path downloadDir = downloadsDir();
+            Files.createDirectories(downloadDir);
             uploaded = workDir.resolve("upload" + ext);
             try (InputStream in = file.getInputStream()) {
                 Files.copy(in, uploaded, StandardCopyOption.REPLACE_EXISTING);
             }
-            output = workDir.resolve("基站转换结果" + System.currentTimeMillis() + ".xlsx");
+            output = downloadDir.resolve(RESULT_BASE_NAME + "_" + System.currentTimeMillis() + ".xlsx");
             TowerListener towerListener = new TowerListener(output.toString());
             FesodSheet.read(uploaded.toFile(), TowerConvertDTO.class, towerListener)
                     .sheet()
@@ -122,7 +117,7 @@ public class TowerService {
                 try {
                     Files.deleteIfExists(uploaded);
                 } catch (IOException e) {
-                    log.error("清理上传的临时基站文件失败: {}", uploaded, e);
+                    log.error("清理上传的临时基站文件:", uploaded, e);
                 }
             }
         }
@@ -130,28 +125,31 @@ public class TowerService {
         if (Files.notExists(output)) {
             throw new ServerException("基站文件转换失败!");
         }
-        String fileName = "基站转换结果" + System.currentTimeMillis() + ".xlsx";
-        return ResponseEntity.ok()
-                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
-                .header(HttpHeaders.CONTENT_DISPOSITION,
-                        ContentDisposition.attachment().filename(fileName, StandardCharsets.UTF_8).build().toString())
-                .contentLength(FileUtil.size(output.toFile()))
-                .body(new FileSystemResource(output));
+        return new SystemService.DownloadFile(output.toAbsolutePath(), output.getFileName().toString());
     }
 
     /**
-     * 下载基站转换模板(Web 化:以附件流返回,替代原「复制到下载目录 + Electron 打开文件夹」)。
+     * 把基站导入模板复制一份到系统「下载」目录(文件名带毫秒时间戳),返回副本路径。
+     *
+     * <p>每次调用都生成新副本,不覆盖已有文件 —— 用户拿到的永远是一份独立的模板。
+     * 模板是服务端常量({@code qingjian/system/conf/基站导入模板.xls}),不在任何案件目录内,
+     * 因此不做案件工作区校验。
      */
-    public ResponseEntity<Resource> downloadTemplate() {
+    public SystemService.DownloadFile downloadTemplate() {
         Path template = PathConst.COV_TMP_PATH;
         if (Files.notExists(template)) {
             throw new ServerException("基站导入模板文件不存在!");
         }
-        return ResponseEntity.ok()
-                .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
-                .header(HttpHeaders.CONTENT_DISPOSITION,
-                        ContentDisposition.attachment().filename("基站导入模板.xls", StandardCharsets.UTF_8).build().toString())
-                .contentLength(FileUtil.size(template.toFile()))
-                .body(new FileSystemResource(template));
+        Path target;
+        try {
+            Path downloadDir = downloadsDir();
+            Files.createDirectories(downloadDir);
+            target = downloadDir.resolve(TEMPLATE_BASE_NAME + "_" + System.currentTimeMillis() + ".xls");
+            Files.copy(template, target, StandardCopyOption.REPLACE_EXISTING);
+        } catch (IOException e) {
+            log.error("复制基站导入模板到下载目录失败", e);
+            throw new ServerException("复制基站导入模板失败!");
+        }
+        return new SystemService.DownloadFile(target.toAbsolutePath(), target.getFileName().toString());
     }
 }