feat(file-check): 增加文件检核 Excel 下载链接解析与展示功能

This commit is contained in:
hugo committed 2026-07-10 13:28:41 +08:00
1 parent 5e7e5a8717
commit f21216f81e
21 files changed
+885 -125

No files matched your search

@@ -6,10 +6,16 @@
*/
import { computed } from 'vue';
import { marked } from 'marked';
import { useMessage } from '@/shared/composables/useMessage';
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../types/chat.types';
import type { ShippingMatchResultPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
import {
downloadFileCheckExcelByRunId,
parseFileCheckExcelRunId,
rewriteFileCheckExcelLinksForDisplay,
} from '../utils/fileCheckExcelDownload';
marked.setOptions({ gfm: true, breaks: true });
@@ -330,6 +336,8 @@ function enhanceAssetHistoryTableLinks(html: string): string {
}
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const message = useMessage();
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
if (msgItem?.type === 'shipping-parse-review') return false;
@@ -416,6 +424,15 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
void ctx.openPreview(preview);
return;
}
const fileCheckRunId = parseFileCheckExcelRunId(rawHref);
if (fileCheckRunId) {
event.preventDefault();
void downloadFileCheckExcelByRunId(fileCheckRunId).catch((error: unknown) => {
const text = error instanceof Error ? error.message : '下载 Excel 失败';
message.error(text);
});
return;
}
ctx.handleLeaveMarkdownClick(event);
};
@@ -428,7 +445,9 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const renderMarkdown = (text: string) => {
if (!text) return '';
const extracted = safeExtractInlineDownloadFiles(text);
const displayText = ctx.prepareMarkdownDisplayText(extracted.cleanedText);
const displayText = rewriteFileCheckExcelLinksForDisplay(
ctx.prepareMarkdownDisplayText(extracted.cleanedText),
);
try {
const rendered = marked.parse(displayText);
const html = typeof rendered === 'string' ? rendered : displayText;
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest';
import {
parseFileCheckExcelRunId,
rewriteFileCheckExcelLinksForDisplay,
} from './fileCheckExcelDownload';
describe('fileCheckExcelDownload', () => {
it('parses tool api excel link with token', () => {
expect(parseFileCheckExcelRunId(
'http://192.168.100.230:8890/api/file-check/tools/runs/187/excel?token=abc',
)).toBe(187);
});
it('parses workspace excel link', () => {
expect(parseFileCheckExcelRunId('/api/workspace/file-check/runs/42/excel')).toBe(42);
});
it('rewrites tool api links to workspace paths for display', () => {
const input = '下载:[链接](http://ai.example.com/api/file-check/tools/runs/9/excel?token=xyz)';
expect(rewriteFileCheckExcelLinksForDisplay(input)).toBe(
'下载:[链接](/api/workspace/file-check/runs/9/excel)',
);
});
});
@@ -0,0 +1,106 @@
/**
* features/chat/utils/fileCheckExcelDownload.ts
* 用途:解析文件检核 Excel 下载链接,并通过 Workspace 会话鉴权下载(不依赖短期 JWT)。
* 依赖:getAuthHeaders。
* 逻辑:ChatMessageBubble 点击 Dify 返回的 Tool API 链接时,改走 workspace 下载接口以支持历史对话。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
const FILE_CHECK_TOOL_EXCEL_PATH_RE = /\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?.*)?$/i;
const FILE_CHECK_WORKSPACE_EXCEL_PATH_RE = /\/api\/workspace\/file-check\/runs\/(\d+)\/excel(?:\?.*)?$/i;
/**
* 从 Tool API 或 Workspace 下载链中解析检核批次 ID。
* @param href - 原始链接(可为绝对或相对路径)。
* @returns 批次 ID;无法解析时返回 null。
*/
export function parseFileCheckExcelRunId(href: string): number | null {
const normalized = String(href || '').trim();
if (!normalized) return null;
let pathname = normalized;
try {
if (/^https?:\/\//i.test(normalized)) {
pathname = new URL(normalized).pathname;
} else {
pathname = normalized.split('?')[0] || normalized;
}
} catch {
pathname = normalized.split('?')[0] || normalized;
}
const match = pathname.match(FILE_CHECK_TOOL_EXCEL_PATH_RE)
|| pathname.match(FILE_CHECK_WORKSPACE_EXCEL_PATH_RE);
if (!match?.[1]) return null;
const runId = Number(match[1]);
return Number.isFinite(runId) && runId > 0 ? runId : null;
}
/**
* 将 Dify Tool API 的 Excel 下载链改写为 Workspace 相对路径,供 Markdown 展示。
* @param text - 原始聊天文本。
* @returns 改写后的文本。
*/
export function rewriteFileCheckExcelLinksForDisplay(text: string): string {
const source = String(text || '');
if (!source) return '';
return source
.replace(
/https?:\/\/[^\s)\]]+\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?[^\s)\]]*)?/gi,
'/api/workspace/file-check/runs/$1/excel',
)
.replace(
/\/api\/file-check\/tools\/runs\/(\d+)\/excel(?:\?[^\s)\]]*)?/gi,
'/api/workspace/file-check/runs/$1/excel',
);
}
const parseDownloadFilename = (disposition: string | null, fallback: string) => {
const value = disposition || '';
const utf8Match = value.match(/filename\*=UTF-8''([^;]+)/i);
const raw = utf8Match?.[1] || value.match(/filename="?([^";]+)"?/i)?.[1] || fallback;
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
};
/**
* 通过 Workspace 接口下载检核 Excel(使用登录态,不依赖 Tool API 短期 token)。
* @param runId - 检核批次 ID。
* @param fallbackName - 默认文件名。
*/
export async function downloadFileCheckExcelByRunId(
runId: number,
fallbackName = `file-check-run-${runId}.xlsx`,
): Promise<void> {
const url = `/api/workspace/file-check/runs/${encodeURIComponent(String(runId))}/excel`;
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
const message = typeof body?.message === 'string'
? body.message
: typeof body?.error?.message === 'string'
? body.error.message
: `下载失败:${res.status}`;
throw new Error(message);
}
const blob = await res.blob();
const filename = parseDownloadFilename(
res.headers.get('content-disposition'),
fallbackName,
);
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(objectUrl);
}