fix(chat-fixed-assets): 修复固资连续问答与宽泛查询空字段问题

This commit is contained in:
runny committed 2026-07-03 14:59:51 +08:00
1 parent 599475d4e2
commit 1164ae2e3c
7 files changed
+417 -46

No files matched your search

@@ -162,17 +162,17 @@ const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
specification: '规格型号',
account_period: '账套',
operating_center_code: '账套',
custodian_person: '保管人姓名',
custodian_name: '保管人姓名',
custodian_dept: '保管部门名称',
department_name: '保管部门名称',
custodian_person: '保管人',
custodian_name: '保管人',
custodian_dept: '保管部门',
department_name: '保管部门',
storage_location: '存放位置名称',
location_name: '存放位置名称',
asset_status: '资产状态',
reserved_field: '预留残值',
residual_value: '预留残值',
supplier: '供应厂商',
vendor_name: '供应厂商',
supplier: '供应商',
vendor_name: '供应商',
asset_nature: '资产性质',
nature: '资产性质',
amount_local: '本币金额(元)',
@@ -180,8 +180,8 @@ const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
quantity: '数量',
unit: '计量单位',
unit_of_measurement: '计量单位',
acquisition_date: '取得日期',
acquired_date: '取得日期',
acquisition_date: '取得时间',
acquired_date: '取得时间',
accounting_date: '入账日期',
recorded_date: '入账日期',
created_at: '创建时间',
@@ -189,6 +189,18 @@ const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
updated_at: '更新时间',
snapshot_time: '快照时间',
};
const FIXED_ASSET_CANONICAL_COLUMNS = [
{ key: 'id', label: '序号', aliases: ['id'] },
{ key: 'asset_id', label: '资产编号', aliases: ['asset_id', 'asset_no'] },
{ key: 'asset_name', label: '资产名称', aliases: ['asset_name'] },
{ key: 'custodian_person', label: '保管人', aliases: ['custodian_person', 'custodian_name'] },
{ key: 'custodian_dept', label: '保管部门', aliases: ['custodian_dept', 'department_name'] },
{ key: 'account_period', label: '账套', aliases: ['account_period', 'operating_center_code'] },
{ key: 'supplier', label: '供应商', aliases: ['supplier', 'vendor_name'] },
{ key: 'asset_status', label: '资产状态', aliases: ['asset_status'] },
{ key: 'quantity', label: '数量', aliases: ['quantity'] },
{ key: 'acquisition_date', label: '取得时间', aliases: ['acquisition_date', 'acquired_date'] },
] as const;
const INLINE_DIALOG_PAGE_SIZE = 15;
/**
@@ -237,6 +249,24 @@ function localizeInlineTableHeader(header: string): string {
return FIXED_ASSET_HEADER_LABELS[normalizedHeader] || header || '-';
}
/**
* 将固定资产时间字段统一裁剪为“年月日”。
* 核心逻辑:优先提取 `YYYY-MM-DD` 或 `YYYY/MM/DD` 形式;若无法识别标准日期,则保留原始值避免误改内容。
* @param value - 原始时间文本。
* @returns 仅保留年月日的展示值。
*/
function formatInlineDateOnly(value: string): string {
const normalized = String(value ?? '').trim();
if (!normalized) return '';
const dateMatch = normalized.match(/(\d{4})[-/](\d{1,2})[-/](\d{1,2})/);
if (!dateMatch) return normalized;
const year = dateMatch[1] || '';
const month = dateMatch[2] || '';
const day = dateMatch[3] || '';
if (!year || !month || !day) return normalized;
return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
}
/**
* 统一表格中的空值展示。
* 核心逻辑:对空串、短横线、null/none 等占位值统一显示“无”,但保留数字 0 与正常文本。
@@ -262,6 +292,19 @@ function findInlineTableHeaderIndex(headers: string[], aliases: string[]): numbe
return headers.findIndex((header) => normalizedAliases.includes(String(header || '').trim().toLowerCase()));
}
/**
* 判断当前 CSV 是否为固定资产明细导出结构。
* 核心逻辑:按业务关键列做命中检测,只有命中固定资产列集时才收敛为指定 10 列,避免影响其他 Agent 的 CSV 预览。
* @param headers - CSV 原始表头。
* @returns 是否按固定资产明细规则处理。
*/
function isFixedAssetInlineTable(headers: string[]): boolean {
return FIXED_ASSET_CANONICAL_COLUMNS
.filter((column) => column.key !== 'id')
.filter((column) => findInlineTableHeaderIndex(headers, [...column.aliases]) >= 0)
.length >= 5;
}
/**
* 将用户输入与单元格内容统一成可搜索的文本。
* 核心逻辑:统一 trim + lowerCase,避免筛选时受大小写和首尾空白干扰。
@@ -288,9 +331,37 @@ function serializeCsvRows(rows: string[][]): string {
}).join(',')).join('\r\n');
}
/**
* 按固定资产业务要求抽取并重排列顺序。
* 核心逻辑:只输出指定的 10 个业务字段;若某列缺失则补“无”,并把取得时间统一裁剪为年月日。
* @param rawHeaders - CSV 原始表头。
* @param dataRows - 原始数据行。
* @returns 规范化后的表头与数据行。
*/
function buildFixedAssetInlineTable(rawHeaders: string[], dataRows: string[][]): InlinePreviewTable {
const headers = FIXED_ASSET_CANONICAL_COLUMNS.map((column) => column.label);
const canonicalHeaders = FIXED_ASSET_CANONICAL_COLUMNS.map((column) => column.key);
const allRows = dataRows.map((row, rowIndex) => FIXED_ASSET_CANONICAL_COLUMNS.map((column) => {
if (column.key === 'id') return String(rowIndex + 1);
const columnIndex = findInlineTableHeaderIndex(rawHeaders, [...column.aliases]);
const rawValue = columnIndex >= 0 ? row[columnIndex] ?? '' : '';
const normalizedValue = column.key === 'acquisition_date'
? formatInlineDateOnly(rawValue)
: rawValue;
return normalizeInlineTableCell(normalizedValue);
}));
return {
rawHeaders: canonicalHeaders,
headers,
allRows,
totalRows: dataRows.length,
isCsv: true,
};
}
/**
* 将 CSV 文本转成结构化表格,供聊天文件弹窗展示全部数据。
* 核心逻辑:首行先做中文列名转换;若存在 id 列则重写为从 1 递增的序号,确保弹窗与下载文件显示一致。
* 核心逻辑:固定资产明细优先收敛为指定业务列与日期格式;其他 CSV 保持原表头映射,避免误伤通用附件预览。
* @param file - 当前预览文件。
* @returns 表头、完整数据行和总行数。
*/
@@ -313,6 +384,9 @@ function buildInlinePreviewTable(file: InlineDownloadFile): InlinePreviewTable {
const headerLine = lines[0] || '';
const rawHeaders = parseCsvLine(headerLine);
const dataRows = lines.slice(1).map((line) => parseCsvLine(line));
if (isFixedAssetInlineTable(rawHeaders)) {
return buildFixedAssetInlineTable(rawHeaders, dataRows);
}
const idColumnIndex = rawHeaders.findIndex((header) => String(header || '').trim().toLowerCase() === 'id');
const headers = rawHeaders.map((header) => localizeInlineTableHeader(header));
const allRows = dataRows.map((row, rowIndex) => rawHeaders.map((_, columnIndex) => {
@@ -246,6 +246,22 @@ export function useChat() {
);
};
/**
* 判断当前消息列表里是否已经出现“用户可感知为完成态”的上一轮回答。
*
* 说明:
* - 固资管理的第一轮大结果常常已经把完整表格和分析展示出来,但 SSE 终态还会晚 1~2 秒;
* - 若这时用户继续提问,不应再把发送动作死锁在 `isThinking=true` 上。
*/
const hasVisibleCompletedAssistantReply = (items: ChatMessage[]) => {
for (let i = items.length - 1; i >= 0; i -= 1) {
const message = items[i];
if (message?.role !== 'assistant') continue;
return looksLikeCompletedAssistantReply(String(message.content || ''));
}
return false;
};
/**
* 对“已看到完整报告但流未结束”的情况做兜底收尾。
*
@@ -330,6 +346,41 @@ export function useChat() {
return String(message ?? 'Unknown error');
};
/**
* 从 workflow_finished 失败事件中提取用户可读错误。
*
* 说明:
* - Dify Chatflow 失败时常以 `workflow_finished + data.status=failed` 返回,HTTP 仍是 200;
* - 若这里只按“终态成功”处理,页面会出现“没有任何响应”;
* - 因此需要优先从 top-level / nested data / error 对象里抽取失败文案。
*/
const extractWorkflowFailureMessage = (data: Record<string, unknown>) => {
if (String(data.event || '') !== 'workflow_finished') return '';
const workflowData = data.data && typeof data.data === 'object'
? data.data as Record<string, unknown>
: {};
const isFailed = String(workflowData.status || '').toLowerCase() === 'failed';
if (!isFailed) return '';
const candidates = [
data.message,
data.description,
data.error,
workflowData.message,
workflowData.description,
workflowData.error,
workflowData.errmsg,
];
for (const candidate of candidates) {
const normalized = formatStreamError(candidate).trim();
if (!normalized || normalized === 'Unknown error') continue;
if (/maximum context length|input_tokens/i.test(normalized)) {
return '当前会话上下文过长,模型无法继续回答。请新建对话后重新查询该资产编号。';
}
return normalized;
}
return '工作流执行失败,请稍后重试';
};
const streamErrorLabels = (): StreamErrorLabels => ({
networkDisconnectedEmpty: t('chat.streamError.networkDisconnectedEmpty'),
partialInterrupted: t('chat.streamError.partialInterrupted'),
@@ -350,7 +401,12 @@ export function useChat() {
) => {
const displayQuery = String(context?.display_query || query || '').trim();
clearLikelyCompletedStreamTimer();
cancelActiveStream();
const shouldDetachPreviousStream = Boolean(activeStreamController.value) && hasVisibleCompletedAssistantReply(messages.value);
if (shouldDetachPreviousStream) {
detachActiveStreamFromView();
} else {
cancelActiveStream();
}
const controller = new AbortController();
activeStreamController.value = controller;
const runViewId = viewId.value;
@@ -478,8 +534,13 @@ export function useChat() {
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
}
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
const workflowFailureMessage = extractWorkflowFailureMessage(data);
hasTerminalEvent = true;
ignoreFurtherStreamEvents = true;
// [STEP 2] 一旦拿到终态事件,当前轮回答在用户视角已经结束;
// 这里立刻把旧流从活动视图脱离,允许用户继续提问,同时让底层连接在后台自然读到 EOF,
// 避免下一次 sendMessage 先 abort 旧请求,导致网络面板残留 ERR_ABORTED。
detachActiveStreamFromView();
const relay = (data.hxops_relay || {}) as Record<string, unknown>;
if (relay.total_relay_ms != null) {
// eslint-disable-next-line no-console
@@ -487,9 +548,14 @@ export function useChat() {
`[chat-perf] hxops relay first_chunk=${String(relay.first_chunk_ms ?? '')}ms total=${String(relay.total_relay_ms ?? '')}ms`,
);
}
run.status = 'done';
run.status = workflowFailureMessage ? 'error' : 'done';
clearLikelyCompletedStreamTimer();
if (messages.value === runMessages) isThinking.value = false;
if (workflowFailureMessage) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
applyStreamErrorToMessage(botMsg, workflowFailureMessage, streamErrorLabels());
}
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
@@ -523,6 +589,9 @@ export function useChat() {
} else if (eventName === 'error') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
// [STEP 2] SSE error 对用户来说也是当前轮终态,脱离活动视图后可继续发下一问,
// 同时保留底层连接在后台自然收尾,避免后续交互误触 abort。
detachActiveStreamFromView();
applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels());
run.status = 'error';
clearLikelyCompletedStreamTimer();
@@ -8,6 +8,29 @@ import type { ChatMessage } from '../types/chat.types';
import type { ChatUploadFileSpec } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
const looksLikeCompletedAssistantReply = (content: string) => {
if (!content) return false;
return (
content.includes('<details>')
|| content.includes('**查询结果如下:**')
|| content.includes('**错误详情**')
|| content.includes('[FILE_START]')
|| content.includes('【💡 数据概述】')
|| content.includes('【📊 数据预览】')
|| content.includes('【📈 数据分析汇总报告】')
|| content.includes('系统为您从数据库中检索到共计')
);
};
const canContinueSendWhileThinking = (messages: ChatMessage[]) => {
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
if (message?.role !== 'assistant') continue;
return looksLikeCompletedAssistantReply(String(message.content || ''));
}
return false;
};
export interface ChatPageSendContext {
input: Ref<string>;
messages: Ref<ChatMessage[]>;
@@ -52,8 +75,9 @@ export interface ChatPageSendContext {
export function createChatPageSendApi(ctx: ChatPageSendContext) {
const canSendMessage = computed(() => {
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
if (ctx.input.value.trim()) return true;
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
if (ctx.isUploadingAttachments.value) return false;
if (ctx.input.value.trim()) return !ctx.isThinking.value || allowSendWhileThinking;
if (ctx.allowsSendWithAttachmentsOnly.value) return true;
return false;
});
@@ -61,10 +85,11 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || ctx.input.value;
const trimmed = content.trim();
const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value);
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
return;
}
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) {
if (!trimmed || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) {
return;
}
if (ctx.tryHandleLeaveSend(content)) {