feat(chat): 完善固资预览与下载权限
This commit is contained in:
1 parent
6ce0942fef
commit
bf18a7ef1d
19 files changed
+1163
-86
No files matched your search
@@ -6,6 +6,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import type {
|
||||
AssetHistorySearchResult,
|
||||
AssetImageResolveResult,
|
||||
ChatCrossAgentHistoryItem,
|
||||
ChatMessage,
|
||||
ChatQueryPreviewPage,
|
||||
@@ -104,4 +105,16 @@ export const searchAssetHistoryFiles = (
|
||||
return requestJson<AssetHistorySearchResult>(`/api/chat/asset-history/search?${qs.toString()}`, auth());
|
||||
};
|
||||
|
||||
export const resolveAssetImagePreview = (
|
||||
agentId: number,
|
||||
query: { asset_id?: string; asset_name?: string },
|
||||
) => {
|
||||
const qs = new URLSearchParams({
|
||||
agent_id: String(agentId),
|
||||
});
|
||||
if (query.asset_id) qs.set('asset_id', query.asset_id);
|
||||
if (query.asset_name) qs.set('asset_name', query.asset_name);
|
||||
return requestJson<AssetImageResolveResult>(`/api/chat/asset-image/resolve?${qs.toString()}`, auth());
|
||||
};
|
||||
|
||||
export type { ChatSessionItem, ChatCrossAgentHistoryItem };
|
||||
@@ -30,7 +30,7 @@ const titleText = computed(() => props.assetId || props.assetName || '资产履
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="dialog-overlay z-[120] items-center"
|
||||
class="dialog-overlay z-[150] items-center"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,900px)] max-w-[900px] flex-col">
|
||||
|
||||
@@ -19,6 +19,7 @@ const emit = defineEmits<{
|
||||
close: [];
|
||||
'change-page': [delta: number];
|
||||
'open-asset-history': [payload: { assetId: string; assetName: string }];
|
||||
'open-asset-image': [payload: { assetId: string; assetName: string }];
|
||||
}>();
|
||||
|
||||
const totalPages = computed(() =>
|
||||
@@ -26,19 +27,34 @@ const totalPages = computed(() =>
|
||||
);
|
||||
const assetIdColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产编号'));
|
||||
const assetNameColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产名称'));
|
||||
const imageColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '图片'));
|
||||
|
||||
function isHighlightColumn(column: string): boolean {
|
||||
return column === '资产编号' || column === '图片';
|
||||
}
|
||||
|
||||
function normalizeCellText(cell: unknown): string {
|
||||
return String(cell ?? '').trim();
|
||||
}
|
||||
|
||||
function canOpenAssetHistory(row: unknown[], cellIndex: number): boolean {
|
||||
return cellIndex === assetIdColumnIndex.value && !!normalizeCellText(row[cellIndex]);
|
||||
if (cellIndex === assetIdColumnIndex.value) {
|
||||
return !!normalizeCellText(row[cellIndex]);
|
||||
}
|
||||
if (cellIndex === imageColumnIndex.value) {
|
||||
return !!normalizeCellText(row[assetIdColumnIndex.value]);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function emitAssetHistory(row: unknown[]): void {
|
||||
function emitAssetAction(row: unknown[], cellIndex: number): void {
|
||||
const assetId = normalizeCellText(row[assetIdColumnIndex.value]);
|
||||
const assetName = assetNameColumnIndex.value >= 0 ? normalizeCellText(row[assetNameColumnIndex.value]) : '';
|
||||
if (!assetId) return;
|
||||
if (cellIndex === imageColumnIndex.value) {
|
||||
emit('open-asset-image', { assetId, assetName });
|
||||
return;
|
||||
}
|
||||
emit('open-asset-history', { assetId, assetName });
|
||||
}
|
||||
</script>
|
||||
@@ -97,7 +113,10 @@ function emitAssetHistory(row: unknown[]): void {
|
||||
<th
|
||||
v-for="column in state.columns"
|
||||
:key="`query-preview-col-${column}`"
|
||||
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
|
||||
:class="[
|
||||
'border border-slate-200 px-3 py-2 text-left font-semibold',
|
||||
isHighlightColumn(column) ? 'text-blue-800' : 'text-primary',
|
||||
]"
|
||||
>
|
||||
{{ column }}
|
||||
</th>
|
||||
@@ -117,8 +136,8 @@ function emitAssetHistory(row: unknown[]): void {
|
||||
<button
|
||||
v-if="canOpenAssetHistory(row, cellIndex)"
|
||||
type="button"
|
||||
class="whitespace-pre-wrap break-all text-left font-medium text-brand-600 underline-offset-2 transition hover:underline"
|
||||
@click="emitAssetHistory(row)"
|
||||
class="whitespace-pre-wrap break-all text-left font-semibold text-blue-700 underline-offset-2 transition hover:text-blue-800 hover:underline"
|
||||
@click="emitAssetAction(row, cellIndex)"
|
||||
>
|
||||
{{ cell ?? '-' }}
|
||||
</button>
|
||||
|
||||
@@ -11,6 +11,7 @@ import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialo
|
||||
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
|
||||
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
|
||||
import { Loader2 } from 'lucide-vue-next';
|
||||
import { nextTick } from 'vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
@@ -23,14 +24,29 @@ function onFeedbackSubmitted() {
|
||||
page.msg.success(page.t('chat.feedbackSubmitSuccess'));
|
||||
page.showGeneralFeedbackDialog = false;
|
||||
}
|
||||
|
||||
async function handleQueryPreviewAssetHistory(assetId: string, assetName: string) {
|
||||
page.queryPreview.close();
|
||||
await nextTick();
|
||||
await page.assetHistory.openHistory(assetId, assetName);
|
||||
}
|
||||
|
||||
async function handleQueryPreviewAssetImage(assetId: string, assetName: string) {
|
||||
page.queryPreview.close();
|
||||
await nextTick();
|
||||
await page.assetImage.openImage(assetId, assetName);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<FilePreviewModal
|
||||
v-model="page.filePreviewVisible"
|
||||
:file="page.previewFile"
|
||||
:files="page.previewFiles"
|
||||
:current-index="page.currentPreviewIndex"
|
||||
:agent-id="page.currentAgentId"
|
||||
:auth-headers="getAuthHeaders()"
|
||||
@update:current-index="page.setPreviewFileIndex"
|
||||
/>
|
||||
<GeneralFeedbackDialog
|
||||
v-model="page.showGeneralFeedbackDialog"
|
||||
@@ -46,7 +62,8 @@ function onFeedbackSubmitted() {
|
||||
:state="page.queryPreviewState"
|
||||
@close="page.queryPreview.close"
|
||||
@change-page="page.queryPreview.changePage"
|
||||
@open-asset-history="({ assetId, assetName }) => page.assetHistory.openHistory(assetId, assetName)"
|
||||
@open-asset-history="({ assetId, assetName }) => handleQueryPreviewAssetHistory(assetId, assetName)"
|
||||
@open-asset-image="({ assetId, assetName }) => handleQueryPreviewAssetImage(assetId, assetName)"
|
||||
/>
|
||||
<div
|
||||
v-if="page.assetHistory.loading"
|
||||
@@ -57,6 +74,15 @@ function onFeedbackSubmitted() {
|
||||
<span>正在搜索该资产的履历资料,请耐心等待...</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="page.assetImage.loading"
|
||||
class="pointer-events-none fixed inset-x-0 top-20 z-[145] flex justify-center px-4"
|
||||
>
|
||||
<div class="flex items-center gap-2 rounded-full border border-brand-200 bg-white/95 px-4 py-2 text-sm text-brand-700 shadow-lg backdrop-blur">
|
||||
<Loader2 class="h-4 w-4 animate-spin text-brand-500" />
|
||||
<span>正在搜索该资产的图片资料,请耐心等待...</span>
|
||||
</div>
|
||||
</div>
|
||||
<ChatLeaveAgentDialog
|
||||
v-model:open="page.showLeaveAgentDialog"
|
||||
v-model:keyword="page.leaveAgentKeyword"
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
||||
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
||||
@@ -23,6 +24,7 @@ export interface ChatMessageBubbleHandlers {
|
||||
renderMarkdown: (text: string) => string;
|
||||
onMarkdownClick: (event: MouseEvent) => void;
|
||||
openAssetHistory: (assetId: string, assetName?: string) => void;
|
||||
openAssetImage: (assetId: string, assetName?: string) => void;
|
||||
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
|
||||
downloadInlineFile: (file: InlineDownloadFile) => void;
|
||||
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
|
||||
@@ -76,6 +78,10 @@ const emit = defineEmits<{
|
||||
'open-feedback': [];
|
||||
}>();
|
||||
|
||||
const authStore = useAuthStore();
|
||||
const INLINE_DOWNLOAD_ALLOWED_EMPLOYEE_ID = '17070141';
|
||||
const RESTRICTED_INLINE_DOWNLOAD_FILE_NAME = '资产明细全量导出表.csv';
|
||||
|
||||
const isLeaveMessage = computed(() =>
|
||||
message.type === 'leave-form'
|
||||
|| message.type === 'leave-confirmation'
|
||||
@@ -185,6 +191,8 @@ const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
|
||||
custodian_name: '保管人',
|
||||
custodian_dept: '保管部门',
|
||||
department_name: '保管部门',
|
||||
image: '图片',
|
||||
picture: '图片',
|
||||
storage_location: '存放位置名称',
|
||||
location_name: '存放位置名称',
|
||||
asset_status: '资产状态',
|
||||
@@ -209,16 +217,17 @@ const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
|
||||
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'] },
|
||||
{ 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: 'image', label: '图片', aliases: ['image', 'picture', '图片'] },
|
||||
{ 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;
|
||||
|
||||
@@ -362,6 +371,18 @@ function buildFixedAssetInlineTable(rawHeaders: string[], dataRows: string[][]):
|
||||
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);
|
||||
if (column.key === 'image') {
|
||||
const assetIdColumnIndex = findInlineTableHeaderIndex(rawHeaders, ['asset_id', 'asset_no', '资产编号']);
|
||||
const rawAssetId = assetIdColumnIndex >= 0 ? row[assetIdColumnIndex] ?? '' : '';
|
||||
const normalizedAssetId = String(rawAssetId ?? '').trim();
|
||||
const imageColumnIndex = findInlineTableHeaderIndex(rawHeaders, ['image', 'picture', '图片']);
|
||||
const rawImageValue = imageColumnIndex >= 0 ? row[imageColumnIndex] ?? '' : '';
|
||||
const normalizedImageValue = String(rawImageValue ?? '').trim();
|
||||
if (normalizedImageValue) {
|
||||
return normalizeInlineTableCell(normalizedImageValue);
|
||||
}
|
||||
return normalizedAssetId ? '查看' : '无';
|
||||
}
|
||||
const columnIndex = findInlineTableHeaderIndex(rawHeaders, [...column.aliases]);
|
||||
const rawValue = columnIndex >= 0 ? row[columnIndex] ?? '' : '';
|
||||
const normalizedValue = column.key === 'acquisition_date'
|
||||
@@ -488,6 +509,33 @@ const activeInlinePageRows = computed(() => {
|
||||
});
|
||||
const activeInlineRangeStart = computed(() => (activeInlineFilteredRows.value.length === 0 ? 0 : (inlineDialogPage.value - 1) * INLINE_DIALOG_PAGE_SIZE + 1));
|
||||
const activeInlineRangeEnd = computed(() => Math.min(inlineDialogPage.value * INLINE_DIALOG_PAGE_SIZE, activeInlineFilteredRows.value.length));
|
||||
const currentUserEmployeeId = computed(() => String(authStore.user?.employee_id || '').trim());
|
||||
|
||||
/**
|
||||
* 判断当前文件是否命中“仅指定工号可下载”的特殊管控。
|
||||
* AI 触发时机:当聊天内嵌 CSV 预览头部要决定是否展示【下载数据】按钮,或真正执行下载前需要二次校验时调用。
|
||||
* 核心逻辑:仅对 `资产明细全量导出表.csv` 启用强限制,其他附件继续沿用现有下载能力,避免误伤普通文件预览。
|
||||
* 参数约束:传入文件名允许为空;空值或非目标文件一律视为不命中管控。
|
||||
*/
|
||||
function requiresRestrictedInlineDownload(file: InlineDownloadFile | null | undefined): boolean {
|
||||
const fileName = String(file?.name || '').trim();
|
||||
return fileName === RESTRICTED_INLINE_DOWNLOAD_FILE_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验当前用户是否有权下载当前内嵌文件。
|
||||
* AI 触发时机:当页面需要控制【下载数据】按钮显隐,或下载函数执行前做权限兜底时调用。
|
||||
* 核心逻辑:命中特殊管控文件时,只放行工号 `17070141`;其余文件保持原权限不变。
|
||||
* 参数约束:仅负责前端展示层和交互层兜底,不替代后端鉴权;若后续接入通用权限系统,应优先复用统一能力。
|
||||
*/
|
||||
function canDownloadInlineFile(file: InlineDownloadFile | null | undefined): boolean {
|
||||
if (!requiresRestrictedInlineDownload(file)) {
|
||||
return true;
|
||||
}
|
||||
return currentUserEmployeeId.value === INLINE_DOWNLOAD_ALLOWED_EMPLOYEE_ID;
|
||||
}
|
||||
|
||||
const canDownloadActiveInlineFile = computed(() => canDownloadInlineFile(activeInlineDialogEntry.value?.file));
|
||||
|
||||
watch(activeInlineTotalPages, (totalPages) => {
|
||||
if (inlineDialogPage.value > totalPages) {
|
||||
@@ -543,14 +591,32 @@ function changeInlineDialogPage(nextPage: number): void {
|
||||
|
||||
function canOpenInlineAssetHistory(cellIndex: number, cellValue: string): boolean {
|
||||
const normalizedValue = String(cellValue || '').trim();
|
||||
return cellIndex === activeInlineFilterIndexes.value.assetId && !!normalizedValue && normalizedValue !== '-';
|
||||
const imageIndex = activeInlineDialogEntry.value?.table.rawHeaders.findIndex((header) => header === 'image' || header === '图片') ?? -1;
|
||||
if (cellIndex === activeInlineFilterIndexes.value.assetId) {
|
||||
return !!normalizedValue && normalizedValue !== '-';
|
||||
}
|
||||
if (cellIndex === imageIndex) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function openInlineAssetHistory(row: string[]): void {
|
||||
function isInlineHighlightHeader(header: string): boolean {
|
||||
return header === '资产编号' || header === '图片';
|
||||
}
|
||||
|
||||
async function openInlineAssetHistory(row: string[], cellIndex: number): Promise<void> {
|
||||
const indexes = activeInlineFilterIndexes.value;
|
||||
const assetId = indexes.assetId >= 0 ? String(row[indexes.assetId] || '').trim() : '';
|
||||
const assetName = indexes.assetName >= 0 ? String(row[indexes.assetName] || '').trim() : '';
|
||||
if (!assetId || assetId === '-') return;
|
||||
const imageIndex = activeInlineDialogEntry.value?.table.rawHeaders.findIndex((header) => header === 'image' || header === '图片') ?? -1;
|
||||
closeInlinePreviewDialog();
|
||||
await nextTick();
|
||||
if (cellIndex === imageIndex) {
|
||||
handlers.openAssetImage(assetId, assetName === '-' ? '' : assetName);
|
||||
return;
|
||||
}
|
||||
handlers.openAssetHistory(assetId, assetName === '-' ? '' : assetName);
|
||||
}
|
||||
|
||||
@@ -560,6 +626,9 @@ function openInlineAssetHistory(row: string[]): void {
|
||||
* @param file - 从当前消息内容解析出的单个可下载文件。
|
||||
*/
|
||||
function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
if (!canDownloadInlineFile(file)) {
|
||||
return;
|
||||
}
|
||||
const table = buildInlinePreviewTable(file);
|
||||
if (!table.isCsv || table.headers.length === 0) {
|
||||
handlers.downloadInlineFile(file);
|
||||
@@ -854,6 +923,7 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
v-if="canDownloadActiveInlineFile"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||
@click="handleInlineDownload(activeInlineDialogEntry.file)"
|
||||
@@ -909,7 +979,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
<th
|
||||
v-for="(header, headerIndex) in activeInlineDialogEntry.table.headers"
|
||||
:key="`${activeInlineDialogEntry.file.name}-dialog-header-${headerIndex}`"
|
||||
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
|
||||
:class="[
|
||||
'border border-slate-200 px-3 py-2 text-left font-semibold',
|
||||
isInlineHighlightHeader(header) ? 'text-blue-800' : 'text-primary',
|
||||
]"
|
||||
>
|
||||
{{ header || '-' }}
|
||||
</th>
|
||||
@@ -929,8 +1002,8 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
<button
|
||||
v-if="canOpenInlineAssetHistory(cellIndex, cell)"
|
||||
type="button"
|
||||
class="whitespace-pre-wrap break-all text-left font-medium text-brand-600 underline-offset-2 transition hover:underline"
|
||||
@click="openInlineAssetHistory(row)"
|
||||
class="whitespace-pre-wrap break-all text-left font-semibold text-blue-700 underline-offset-2 transition hover:text-blue-800 hover:underline"
|
||||
@click="openInlineAssetHistory(row, cellIndex)"
|
||||
>
|
||||
{{ cell || '-' }}
|
||||
</button>
|
||||
@@ -1030,6 +1103,21 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-fixed-asset-highlight-header) {
|
||||
color: rgb(30 64 175);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-asset-history-link) {
|
||||
color: rgb(29 78 216);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-asset-history-link:hover) {
|
||||
color: rgb(30 64 175);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown th),
|
||||
:deep(.dark .chat-markdown td) {
|
||||
border-color: rgb(51 65 85);
|
||||
@@ -1039,6 +1127,15 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
background: rgb(30 41 59);
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown .chat-fixed-asset-highlight-header),
|
||||
:deep(.dark .chat-markdown .chat-asset-history-link) {
|
||||
color: rgb(147 197 253);
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown .chat-asset-history-link:hover) {
|
||||
color: rgb(191 219 254);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown details) {
|
||||
margin-top: 1rem;
|
||||
border: 1px solid rgb(226 232 240);
|
||||
|
||||
@@ -16,6 +16,21 @@ interface UseChatAssetHistoryOptions {
|
||||
warn: (message: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把后端返回的技术性错误翻译成用户可理解的提示。
|
||||
* AI 触发时机:当资产履历查询失败,但原始错误包含英文配置名、共享盘术语等技术细节时调用。
|
||||
* 核心逻辑:优先识别已知的履历共享盘配置异常,返回面向业务用户的中文说明;其他错误保持原文,避免吞掉真实上下文。
|
||||
* 参数约束:仅处理展示文案,不改变错误对象本身;返回值必须适合作为 toast/警告弹窗直接展示。
|
||||
*/
|
||||
function normalizeAssetHistoryErrorMessage(message: string): string {
|
||||
const normalizedMessage = String(message || '').trim();
|
||||
const lowerCaseMessage = normalizedMessage.toLowerCase();
|
||||
if (lowerCaseMessage.includes('asset history share is not configured')) {
|
||||
return '当前系统暂未配置资产履历文件目录,暂时无法查看履历,请联系管理员处理。';
|
||||
}
|
||||
return normalizedMessage || '检索资产履历失败';
|
||||
}
|
||||
|
||||
export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
|
||||
const open = ref(false);
|
||||
const loading = ref(false);
|
||||
@@ -35,7 +50,7 @@ export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
|
||||
* 检索资产履历并直接打开最佳预览结果。
|
||||
* AI 触发时机:当用户点击聊天表格中的“资产编号”,希望直接查看该资产履历时调用。
|
||||
* 核心逻辑:点击后先切入“检索中”状态,再按“资产编号 + 资产名称”查询共享盘候选文件,命中后默认取排序最优的第一条直接预览;
|
||||
* 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表。
|
||||
* 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表;若后端返回技术性英文报错,会先转换成业务可读提示。
|
||||
* 参数约束:至少要提供资产编号或资产名称之一;候选文件排序由后端负责,本方法默认信任第一条结果。
|
||||
*/
|
||||
const openHistory = async (nextAssetId: string, nextAssetName = '') => {
|
||||
@@ -69,7 +84,8 @@ export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
|
||||
}
|
||||
await openHistoryFilePreview(bestMatch);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '检索资产履历失败';
|
||||
const rawMessage = err instanceof Error ? err.message : '检索资产履历失败';
|
||||
const message = normalizeAssetHistoryErrorMessage(rawMessage);
|
||||
error.value = message;
|
||||
options.warn(`履历查询失败:${message}`);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAssetImage.ts
|
||||
* 用途:管理固定资产图片检索、友好提示与预览跳转。
|
||||
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
|
||||
* 逻辑:用户点击“图片 -> 查看”后,本 composable 统一向后端索要最佳图片,再复用现有文件预览弹窗在站内展示。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import type { ComputedRef } from 'vue';
|
||||
import { resolveAssetImagePreview } from '../api/chat.api';
|
||||
import type { SourceFileLink } from '../types/chat.types';
|
||||
|
||||
interface UseChatAssetImageOptions {
|
||||
agentId: ComputedRef<number>;
|
||||
openPreviewGallery: (files: SourceFileLink[], initialIndex?: number) => Promise<void>;
|
||||
warn: (message: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把后端返回的图片检索错误翻译成业务用户能看懂的提示。
|
||||
* AI 触发时机:当用户点击“图片 -> 查看”失败,但原始报错包含接口路径、外部系统术语等技术细节时调用。
|
||||
* 核心逻辑:优先识别已知的配置/检索异常并转成中文说明;未知错误保留原始文本,方便排查。
|
||||
* 参数与输出约束:只负责展示文案,不吞掉真实错误对象;返回值必须适合作为 toast 直接展示。
|
||||
*/
|
||||
function normalizeAssetImageErrorMessage(message: string): string {
|
||||
const normalizedMessage = String(message || '').trim();
|
||||
const lowerCaseMessage = normalizedMessage.toLowerCase();
|
||||
if (lowerCaseMessage.includes('固定资产图片文档库未配置')) {
|
||||
return '当前系统暂未配置固定资产图片文档库,暂时无法查看图片,请联系管理员处理。';
|
||||
}
|
||||
if (lowerCaseMessage.includes('未找到资产')) {
|
||||
return normalizedMessage;
|
||||
}
|
||||
return normalizedMessage || '检索固定资产图片失败';
|
||||
}
|
||||
|
||||
export function useChatAssetImage(options: UseChatAssetImageOptions) {
|
||||
const loading = ref(false);
|
||||
|
||||
/**
|
||||
* 检索固定资产图片并直接打开预览。
|
||||
* AI 触发时机:当用户点击聊天表格或 CSV 预览里的“图片 -> 查看”时调用。
|
||||
* 核心逻辑:先向后端请求全部命中的图片文件,再把图片组交给通用 FilePreviewModal 预览。
|
||||
* 参数约束:至少要提供资产编号或资产名称之一;后端负责登录外部文档库和挑选最佳图片。
|
||||
*/
|
||||
const openImage = async (nextAssetId: string, nextAssetName = '') => {
|
||||
const normalizedAssetId = String(nextAssetId || '').trim();
|
||||
const normalizedAssetName = String(nextAssetName || '').trim();
|
||||
if (loading.value) return;
|
||||
if (!normalizedAssetId && !normalizedAssetName) {
|
||||
options.warn('当前资产缺少可用于检索图片的编号或名称');
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await resolveAssetImagePreview(options.agentId.value, {
|
||||
asset_id: normalizedAssetId,
|
||||
asset_name: normalizedAssetName,
|
||||
});
|
||||
const items = Array.isArray(result?.items) && result.items.length
|
||||
? result.items
|
||||
: (result?.item ? [result.item] : []);
|
||||
if (!items.length) {
|
||||
const displayName = normalizedAssetId || normalizedAssetName;
|
||||
options.warn(`未找到资产 ${displayName} 的图片文件,请联系管理员补充。`);
|
||||
return;
|
||||
}
|
||||
await options.openPreviewGallery(
|
||||
items.map((item) => ({
|
||||
name: item.name,
|
||||
url: item.url,
|
||||
actualExt: item.actual_ext,
|
||||
})),
|
||||
0,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
const rawMessage = err instanceof Error ? err.message : '检索固定资产图片失败';
|
||||
const message = normalizeAssetImageErrorMessage(rawMessage);
|
||||
options.warn(`图片查询失败:${message}`);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
loading,
|
||||
openImage,
|
||||
};
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import { useChatSessions } from './useChatSessions';
|
||||
import { useChatShipping } from './useChatShipping';
|
||||
import { useChatSourceFiles } from './useChatSourceFiles';
|
||||
import { useChatAssetHistory } from './useChatAssetHistory';
|
||||
import { useChatAssetImage } from './useChatAssetImage';
|
||||
import { useChatStore } from '../stores/chat.store';
|
||||
import { useTrainingWorkspace } from './useTrainingWorkspace';
|
||||
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
|
||||
@@ -157,6 +158,8 @@ export function useChatPage() {
|
||||
const {
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
previewFiles,
|
||||
currentPreviewIndex,
|
||||
getSourceTitle,
|
||||
getSourceMeta,
|
||||
getSourceBrief,
|
||||
@@ -165,6 +168,8 @@ export function useChatPage() {
|
||||
getDisplayRetrieverResources,
|
||||
shouldExpandSourceDetails,
|
||||
openPreview,
|
||||
openPreviewGallery,
|
||||
setPreviewFileIndex,
|
||||
parsePlmPreviewLink,
|
||||
} = sourceFiles;
|
||||
const assetHistory = useChatAssetHistory({
|
||||
@@ -172,6 +177,11 @@ export function useChatPage() {
|
||||
openPreview,
|
||||
warn: (text) => msg.warning(text),
|
||||
});
|
||||
const assetImage = useChatAssetImage({
|
||||
agentId: currentAgentId,
|
||||
openPreviewGallery,
|
||||
warn: (text) => msg.warning(text),
|
||||
});
|
||||
|
||||
watch(currentAgentId, (id) => {
|
||||
chatStore.setCurrentAgentId(id > 0 ? id : null);
|
||||
@@ -315,6 +325,8 @@ export function useChatPage() {
|
||||
resetPeripheralState,
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
previewFiles,
|
||||
currentPreviewIndex,
|
||||
});
|
||||
|
||||
({ loadConversation, startNewChat } = conversationApi);
|
||||
@@ -363,6 +375,7 @@ export function useChatPage() {
|
||||
parsePlmPreviewLink,
|
||||
openPreview,
|
||||
openAssetHistory: assetHistory.openHistory,
|
||||
openAssetImage: assetImage.openImage,
|
||||
getMessageLinks,
|
||||
getDisplayRetrieverResources,
|
||||
getSourceLinks,
|
||||
@@ -504,6 +517,7 @@ export function useChatPage() {
|
||||
queryPreviewError: queryPreview.error,
|
||||
queryPreviewState: queryPreview.state,
|
||||
assetHistory,
|
||||
assetImage,
|
||||
...agent,
|
||||
agentGuides: chatGuides.guides,
|
||||
showGuideModal: chatGuides.showModal,
|
||||
@@ -514,6 +528,9 @@ export function useChatPage() {
|
||||
...attachmentApi,
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
previewFiles,
|
||||
currentPreviewIndex,
|
||||
setPreviewFileIndex,
|
||||
isSidebarOpen,
|
||||
sidebarCollapsed,
|
||||
toggleBrowserPanel: browser.toggle,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/useChatSourceFiles.ts
|
||||
* 检索来源 / 源文件链接解析与预览。
|
||||
*/
|
||||
@@ -204,6 +204,8 @@ export interface UseChatSourceFilesOptions {
|
||||
export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceFilesOptions) {
|
||||
const filePreviewVisible = ref(false);
|
||||
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
|
||||
const previewFiles = ref<Array<{ name: string; url: string; actualExt?: string }>>([]);
|
||||
const currentPreviewIndex = ref(0);
|
||||
|
||||
const getSourceTitle = (item: Record<string, unknown>) =>
|
||||
String(item?.document_name || item?.title || item?.source || 'Untitled Source');
|
||||
@@ -398,6 +400,8 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
|
||||
window.location.href = resolvedFile.url;
|
||||
return;
|
||||
}
|
||||
previewFiles.value = [resolvedFile];
|
||||
currentPreviewIndex.value = 0;
|
||||
previewFile.value = resolvedFile;
|
||||
filePreviewVisible.value = true;
|
||||
} catch (error: unknown) {
|
||||
@@ -406,6 +410,55 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开多文件预览组,并支持在同一弹窗内切换。
|
||||
* AI 触发时机:当后端一次返回同资产的多张图片,需要在当前系统内左右切换查看时调用。
|
||||
* 核心逻辑:先解析每个文件的可预览 URL,再把文件列表和初始索引写入共享弹窗状态。
|
||||
* 参数与输出约束:files 必须至少有 1 个可预览项;initialIndex 会被钳制到合法范围。
|
||||
*/
|
||||
const openPreviewGallery = async (files: SourceFileLink[], initialIndex = 0) => {
|
||||
const normalizedFiles = Array.isArray(files) ? files : [];
|
||||
if (!normalizedFiles.length) {
|
||||
msg.warning(t('chat.previewUnavailable'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const resolvedFiles = await Promise.all(normalizedFiles.map((file) => resolveSourceLink(file)));
|
||||
if (!resolvedFiles.length) {
|
||||
msg.warning(t('chat.previewUnavailable'));
|
||||
return;
|
||||
}
|
||||
const safeIndex = Math.min(Math.max(initialIndex, 0), resolvedFiles.length - 1);
|
||||
const initialFile = resolvedFiles[safeIndex] || resolvedFiles[0];
|
||||
if (!initialFile) {
|
||||
msg.warning(t('chat.previewUnavailable'));
|
||||
return;
|
||||
}
|
||||
if (shouldBypassEmbeddedPreview(initialFile)) {
|
||||
window.location.href = initialFile.url;
|
||||
return;
|
||||
}
|
||||
previewFiles.value = resolvedFiles;
|
||||
currentPreviewIndex.value = safeIndex;
|
||||
previewFile.value = initialFile;
|
||||
filePreviewVisible.value = true;
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : t('chat.previewUnavailable');
|
||||
msg.warning(message);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换当前预览中的文件索引。
|
||||
* 用途:供 FilePreviewModal 在多图模式下切换上一张、下一张或缩略图点击时回写当前文件。
|
||||
*/
|
||||
const setPreviewFileIndex = (nextIndex: number) => {
|
||||
if (!previewFiles.value.length) return;
|
||||
const safeIndex = Math.min(Math.max(nextIndex, 0), previewFiles.value.length - 1);
|
||||
currentPreviewIndex.value = safeIndex;
|
||||
previewFile.value = previewFiles.value[safeIndex] || null;
|
||||
};
|
||||
|
||||
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
|
||||
const rawHref = (href || '').trim();
|
||||
if (!rawHref.startsWith('#plm-preview?')) return null;
|
||||
@@ -419,6 +472,8 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
|
||||
return {
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
previewFiles,
|
||||
currentPreviewIndex,
|
||||
getSourceTitle,
|
||||
getSourceMeta,
|
||||
getSourceBrief,
|
||||
@@ -427,6 +482,8 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
|
||||
getDisplayRetrieverResources,
|
||||
shouldExpandSourceDetails,
|
||||
openPreview,
|
||||
openPreviewGallery,
|
||||
setPreviewFileIndex,
|
||||
parsePlmPreviewLink,
|
||||
};
|
||||
}
|
||||
@@ -31,6 +31,8 @@ export interface ChatPageConversationContext {
|
||||
resetPeripheralState: () => void;
|
||||
filePreviewVisible: Ref<boolean>;
|
||||
previewFile: Ref<unknown>;
|
||||
previewFiles: Ref<unknown[]>;
|
||||
currentPreviewIndex: Ref<number>;
|
||||
}
|
||||
|
||||
export function createChatPageConversationApi(ctx: ChatPageConversationContext) {
|
||||
@@ -76,6 +78,8 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
ctx.resetPeripheralState();
|
||||
ctx.filePreviewVisible.value = false;
|
||||
ctx.previewFile.value = null;
|
||||
ctx.previewFiles.value = [];
|
||||
ctx.currentPreviewIndex.value = 0;
|
||||
void ctx.router.replace({ path: ctx.route.path, query: {} });
|
||||
};
|
||||
|
||||
@@ -89,6 +93,8 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
|
||||
ctx.resetPeripheralState();
|
||||
ctx.filePreviewVisible.value = false;
|
||||
ctx.previewFile.value = null;
|
||||
ctx.previewFiles.value = [];
|
||||
ctx.currentPreviewIndex.value = 0;
|
||||
};
|
||||
|
||||
return { loadConversation, startNewChat, resetChatStateForAgentChange };
|
||||
|
||||
@@ -65,6 +65,7 @@ export interface ChatPageMarkdownContext {
|
||||
parsePlmPreviewLink: (href: string) => SourceFileLink | null;
|
||||
openPreview: (file: SourceFileLink) => Promise<void>;
|
||||
openAssetHistory: (assetId: string, assetName?: string) => void;
|
||||
openAssetImage: (assetId: string, assetName?: string) => void;
|
||||
getMessageLinks: (message: Record<string, unknown>) => SourceFileLink[];
|
||||
getDisplayRetrieverResources: (msgItem: Record<string, unknown>) => Record<string, unknown>[];
|
||||
getSourceLinks: (resources?: unknown[]) => SourceFileLink[];
|
||||
@@ -185,14 +186,109 @@ function normalizeAssetHistoryText(value: string): string {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const FIXED_ASSET_TABLE_TARGET_HEADERS = [
|
||||
'序号',
|
||||
'资产编号',
|
||||
'资产名称',
|
||||
'保管人',
|
||||
'保管部门',
|
||||
'图片',
|
||||
'账套',
|
||||
'供应商',
|
||||
'资产状态',
|
||||
'数量',
|
||||
'取得时间',
|
||||
];
|
||||
|
||||
const FIXED_ASSET_TABLE_HEADER_ALIASES: Record<string, string[]> = {
|
||||
序号: ['序号', 'id'],
|
||||
资产编号: ['资产编号', 'asset_id', 'asset_no'],
|
||||
资产名称: ['资产名称', 'asset_name'],
|
||||
保管人: ['保管人', '保管人姓名', 'custodian_name', 'custodian_person'],
|
||||
保管部门: ['保管部门', '保管部门名称', 'department_name', 'custodian_dept'],
|
||||
图片: ['图片', 'image', 'picture'],
|
||||
账套: ['账套', 'account_period', 'operating_center_code'],
|
||||
供应商: ['供应商', '供应厂商', 'supplier', 'vendor_name'],
|
||||
资产状态: ['资产状态', 'asset_status'],
|
||||
数量: ['数量', 'quantity'],
|
||||
取得时间: ['取得时间', '取得日期', 'acquisition_date', 'acquired_date'],
|
||||
};
|
||||
|
||||
function normalizeFixedAssetHeader(value: string): string {
|
||||
const normalized = normalizeAssetHistoryText(value).toLowerCase();
|
||||
if (!normalized) return '';
|
||||
const targetHeader = FIXED_ASSET_TABLE_TARGET_HEADERS.find((header) => (
|
||||
(FIXED_ASSET_TABLE_HEADER_ALIASES[header] || []).some((alias) => alias.toLowerCase() === normalized)
|
||||
));
|
||||
return targetHeader || '';
|
||||
}
|
||||
|
||||
function isFixedAssetPreviewTable(headerLabels: string[]): boolean {
|
||||
const normalizedHeaders = headerLabels
|
||||
.map((label) => normalizeFixedAssetHeader(label))
|
||||
.filter(Boolean);
|
||||
return ['资产编号', '资产名称', '保管人', '保管部门', '账套', '资产状态', '数量', '取得时间']
|
||||
.every((header) => normalizedHeaders.includes(header));
|
||||
}
|
||||
|
||||
/**
|
||||
* 把聊天结果表格里的“资产编号”列增强为可点击入口。
|
||||
* 核心逻辑:只处理包含“资产编号”表头的表格,并从同行“资产名称”列一并带出检索关键词,避免误伤其他普通 Markdown 表格。
|
||||
* 将 Dify 返回的旧版固定资产表格收敛成统一展示列顺序。
|
||||
* 核心逻辑:按中文/英文别名识别表头后重建 thead/tbody,并补出“图片=查看”列,让旧会话与新会话都按同一业务结构展示。
|
||||
*/
|
||||
function normalizeFixedAssetPreviewTables(container: HTMLElement): void {
|
||||
const tables = Array.from(container.querySelectorAll('table'));
|
||||
tables.forEach((table) => {
|
||||
const headerCells = Array.from(table.querySelectorAll('thead th'));
|
||||
if (headerCells.length === 0) return;
|
||||
const headerLabels = headerCells.map((cell) => normalizeAssetHistoryText(cell.textContent || ''));
|
||||
if (!isFixedAssetPreviewTable(headerLabels)) return;
|
||||
|
||||
const headerIndexMap = new Map<string, number>();
|
||||
headerLabels.forEach((label, index) => {
|
||||
const normalized = normalizeFixedAssetHeader(label);
|
||||
if (normalized && !headerIndexMap.has(normalized)) {
|
||||
headerIndexMap.set(normalized, index);
|
||||
}
|
||||
});
|
||||
|
||||
const bodyRows = Array.from(table.querySelectorAll('tbody tr'));
|
||||
const normalizedRows = bodyRows.map((row, rowIndex) => {
|
||||
const cells = Array.from(row.querySelectorAll('td'));
|
||||
const pickCellText = (header: string): string => {
|
||||
if (header === '序号') return String(rowIndex + 1);
|
||||
if (header === '图片') {
|
||||
const assetIdIndex = headerIndexMap.get('资产编号');
|
||||
const assetId = assetIdIndex !== undefined ? normalizeAssetHistoryText(cells[assetIdIndex]?.textContent || '') : '';
|
||||
return assetId ? '查看' : '无';
|
||||
}
|
||||
const cellIndex = headerIndexMap.get(header);
|
||||
return cellIndex !== undefined ? normalizeAssetHistoryText(cells[cellIndex]?.textContent || '') || '无' : '无';
|
||||
};
|
||||
return FIXED_ASSET_TABLE_TARGET_HEADERS.map((header) => pickCellText(header));
|
||||
});
|
||||
|
||||
const thead = table.querySelector('thead');
|
||||
const tbody = table.querySelector('tbody');
|
||||
if (!thead || !tbody) return;
|
||||
|
||||
thead.innerHTML = `<tr>${FIXED_ASSET_TABLE_TARGET_HEADERS.map((header) => (
|
||||
`<th class="${header === '资产编号' || header === '图片' ? 'chat-fixed-asset-highlight-header' : ''}">${header}</th>`
|
||||
)).join('')}</tr>`;
|
||||
tbody.innerHTML = normalizedRows.map((row) => (
|
||||
`<tr>${row.map((cell) => `<td>${cell || '无'}</td>`).join('')}</tr>`
|
||||
)).join('');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 把聊天结果表格里的“资产编号”和“图片”列增强为可点击入口。
|
||||
* 核心逻辑:只处理包含“资产编号”表头的表格,并从同行“资产名称”列一并带出检索关键词;资产编号走履历检索,图片走图片预览检索。
|
||||
*/
|
||||
function enhanceAssetHistoryTableLinks(html: string): string {
|
||||
if (!html || typeof document === 'undefined' || !html.includes('<table')) return html;
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = html;
|
||||
normalizeFixedAssetPreviewTables(container);
|
||||
const tables = Array.from(container.querySelectorAll('table'));
|
||||
tables.forEach((table) => {
|
||||
const headerCells = Array.from(table.querySelectorAll('thead th'));
|
||||
@@ -201,6 +297,7 @@ function enhanceAssetHistoryTableLinks(html: string): string {
|
||||
const assetIdIndex = headerLabels.findIndex((label) => label === '资产编号');
|
||||
if (assetIdIndex < 0) return;
|
||||
const assetNameIndex = headerLabels.findIndex((label) => label === '资产名称');
|
||||
const imageIndex = headerLabels.findIndex((label) => label === '图片');
|
||||
const rows = Array.from(table.querySelectorAll('tbody tr'));
|
||||
rows.forEach((row) => {
|
||||
const cells = Array.from(row.querySelectorAll('td'));
|
||||
@@ -215,6 +312,18 @@ function enhanceAssetHistoryTableLinks(html: string): string {
|
||||
link.textContent = assetId;
|
||||
assetIdCell.innerHTML = '';
|
||||
assetIdCell.appendChild(link);
|
||||
|
||||
if (imageIndex >= 0) {
|
||||
const imageCell = cells[imageIndex];
|
||||
if (!imageCell) return;
|
||||
const imageText = normalizeAssetHistoryText(imageCell.textContent || '') || '查看';
|
||||
const imageLink = document.createElement('a');
|
||||
imageLink.href = `#asset-image?asset_id=${encodeURIComponent(assetId)}&asset_name=${encodeURIComponent(assetName)}`;
|
||||
imageLink.className = 'chat-asset-history-link';
|
||||
imageLink.textContent = imageText;
|
||||
imageCell.innerHTML = '';
|
||||
imageCell.appendChild(imageLink);
|
||||
}
|
||||
});
|
||||
});
|
||||
return container.innerHTML;
|
||||
@@ -295,6 +404,12 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
ctx.openAssetHistory((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim());
|
||||
return;
|
||||
}
|
||||
if (rawHref.startsWith('#asset-image?')) {
|
||||
event.preventDefault();
|
||||
const params = new URLSearchParams(rawHref.slice('#asset-image?'.length));
|
||||
ctx.openAssetImage((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim());
|
||||
return;
|
||||
}
|
||||
const preview = ctx.parsePlmPreviewLink(rawHref);
|
||||
if (preview) {
|
||||
event.preventDefault();
|
||||
@@ -333,6 +448,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
renderMarkdown,
|
||||
onMarkdownClick: handleChatMarkdownClick,
|
||||
openAssetHistory: ctx.openAssetHistory,
|
||||
openAssetImage: ctx.openAssetImage,
|
||||
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
|
||||
downloadInlineFile,
|
||||
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
|
||||
|
||||
@@ -117,6 +117,25 @@ export interface AssetHistorySearchResult {
|
||||
items: AssetHistoryFileItem[];
|
||||
}
|
||||
|
||||
export interface AssetImageFileItem {
|
||||
item_id: string;
|
||||
version_id: string;
|
||||
attachment_id: string;
|
||||
name: string;
|
||||
relative_path: string;
|
||||
url: string;
|
||||
actual_ext?: string;
|
||||
size_bytes?: number;
|
||||
}
|
||||
|
||||
export interface AssetImageResolveResult {
|
||||
asset_id?: string;
|
||||
asset_name?: string;
|
||||
item: AssetImageFileItem;
|
||||
items: AssetImageFileItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ChatUploadResult {
|
||||
id: string;
|
||||
name?: string;
|
||||
|
||||
@@ -18,7 +18,7 @@ import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { marked } from 'marked';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { Minus, Plus, RotateCcw } from 'lucide-vue-next';
|
||||
import { ChevronLeft, ChevronRight, Minus, Plus, RotateCcw } from 'lucide-vue-next';
|
||||
import VueOfficeDocx from '@vue-office/docx';
|
||||
import VueOfficeExcel from '@vue-office/excel';
|
||||
import VueOfficePdf from '@vue-office/pdf';
|
||||
@@ -46,12 +46,15 @@ type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'sheetHtml' | 'of
|
||||
const props = defineProps<{
|
||||
modelValue: boolean;
|
||||
file: PreviewFile | null;
|
||||
files?: PreviewFile[] | null;
|
||||
currentIndex?: number;
|
||||
agentId?: number | null;
|
||||
authHeaders?: Record<string, string>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', value: boolean): void;
|
||||
(e: 'update:currentIndex', value: number): void;
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
|
||||
@@ -70,13 +73,34 @@ const EXCEL_ZOOM_STEP = 0.1;
|
||||
const EXCEL_ZOOM_MIN = 0.6;
|
||||
const EXCEL_ZOOM_MAX = 1.8;
|
||||
|
||||
const imagePreviewExts = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp']);
|
||||
|
||||
const activeFiles = computed<PreviewFile[]>(() => {
|
||||
const files = Array.isArray(props.files) ? props.files.filter(Boolean) : [];
|
||||
if (files.length) return files;
|
||||
return props.file ? [props.file] : [];
|
||||
});
|
||||
|
||||
const activeIndex = computed(() => {
|
||||
if (!activeFiles.value.length) return 0;
|
||||
const rawIndex = Number(props.currentIndex ?? 0);
|
||||
if (!Number.isFinite(rawIndex)) return 0;
|
||||
return Math.min(Math.max(Math.trunc(rawIndex), 0), activeFiles.value.length - 1);
|
||||
});
|
||||
|
||||
const activeFile = computed<PreviewFile | null>(() => activeFiles.value[activeIndex.value] || props.file || null);
|
||||
|
||||
/**
|
||||
* 从 URL 或文件名中提取扩展名。
|
||||
* - 会先去掉 query 参数(兼容签名链接)。
|
||||
* - 兼容直接传入 `jpg` 这类原始扩展名。
|
||||
* - 返回小写扩展名(不含点号)。
|
||||
*/
|
||||
const getExt = (raw: string) => {
|
||||
const clean = (raw.split('?')[0] ?? '').toLowerCase();
|
||||
if (clean && !clean.includes('/') && !clean.includes('.')) {
|
||||
return clean;
|
||||
}
|
||||
const parts = clean.split('/');
|
||||
const lastPart = parts[parts.length - 1] ?? '';
|
||||
const i = lastPart.lastIndexOf('.');
|
||||
@@ -84,16 +108,16 @@ const getExt = (raw: string) => {
|
||||
};
|
||||
|
||||
const ext = computed(() => {
|
||||
const actual = getExt(props.file?.actualExt || '');
|
||||
const actual = getExt(activeFile.value?.actualExt || '');
|
||||
if (actual) return actual;
|
||||
// Display name extension has higher priority than URL.
|
||||
const byName = getExt(props.file?.name || '');
|
||||
const byName = getExt(activeFile.value?.name || '');
|
||||
if (byName) return byName;
|
||||
return getExt(props.file?.url || '');
|
||||
return getExt(activeFile.value?.url || '');
|
||||
});
|
||||
|
||||
const preferredMode = computed<PreviewMode>(() => {
|
||||
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
|
||||
if (imagePreviewExts.has(ext.value)) return 'image';
|
||||
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
|
||||
if (['xlsx', 'xls', 'docx'].includes(ext.value)) return 'office';
|
||||
if (['doc', 'ppt', 'pptx', 'pdf'].includes(ext.value)) return 'iframe';
|
||||
@@ -114,7 +138,7 @@ const needsOfficeFallback = computed(() => {
|
||||
* - 其余返回原始 URL,由浏览器自行处理。
|
||||
*/
|
||||
const iframeSrc = computed(() => {
|
||||
if (!props.file?.url) return '';
|
||||
if (!activeFile.value?.url) return '';
|
||||
if (officeObjectUrl.value) return officeObjectUrl.value;
|
||||
if (!props.agentId) return '';
|
||||
if (['pdf', 'doc', 'ppt', 'pptx'].includes(ext.value)) {
|
||||
@@ -122,12 +146,16 @@ const iframeSrc = computed(() => {
|
||||
// Never fallback to a protected iframe URL, otherwise it returns Unauthorized.
|
||||
return officeObjectUrl.value;
|
||||
}
|
||||
return props.file.url;
|
||||
return activeFile.value.url;
|
||||
});
|
||||
|
||||
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
|
||||
const imageSrc = computed(() => officeObjectUrl.value || activeFile.value?.url || '');
|
||||
const officePreviewExts = new Set(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']);
|
||||
const isExcelPreviewFile = computed(() => ['xls', 'xlsx'].includes(ext.value));
|
||||
const isImageGallery = computed(() => (
|
||||
activeFiles.value.length > 1
|
||||
&& activeFiles.value.every((file) => imagePreviewExts.has(getExt(file.actualExt || file.name || file.url || '')))
|
||||
));
|
||||
const excelZoomPercent = computed(() => `${Math.round(excelZoom.value * 100)}%`);
|
||||
const excelPreviewScaleStyle = computed(() => ({
|
||||
transform: `scale(${excelZoom.value})`,
|
||||
@@ -137,6 +165,15 @@ const excelPreviewScaleStyle = computed(() => ({
|
||||
|
||||
const close = () => emit('update:modelValue', false);
|
||||
|
||||
const setActiveIndex = (nextIndex: number) => {
|
||||
if (!activeFiles.value.length) return;
|
||||
const safeIndex = Math.min(Math.max(nextIndex, 0), activeFiles.value.length - 1);
|
||||
emit('update:currentIndex', safeIndex);
|
||||
};
|
||||
|
||||
const showPrevImage = () => setActiveIndex(activeIndex.value - 1);
|
||||
const showNextImage = () => setActiveIndex(activeIndex.value + 1);
|
||||
|
||||
const previewTooLarge = computed(() => /file too large for online preview/i.test(error.value));
|
||||
|
||||
const clearOfficeObjectUrl = () => {
|
||||
@@ -250,13 +287,13 @@ const tryApplyExcelPreview = (buffer: ArrayBuffer) => {
|
||||
};
|
||||
|
||||
const loadSheetPreview = async () => {
|
||||
if (!props.file?.url) return;
|
||||
if (!activeFile.value?.url) return;
|
||||
if (!props.agentId) throw new Error('agent_id is required for excel preview');
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
url: activeFile.value.url,
|
||||
name: activeFile.value.name || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
@@ -274,13 +311,13 @@ const loadSheetPreview = async () => {
|
||||
* 约束:仅作为 Excel 预览兜底使用;解析失败时继续向上抛错,由统一错误 UI 呈现。
|
||||
*/
|
||||
const loadSheetPreviewFromRaw = async () => {
|
||||
if (!props.file?.url) return;
|
||||
if (!activeFile.value?.url) return;
|
||||
if (!props.agentId) throw new Error('agent_id is required for excel preview');
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
url: activeFile.value.url,
|
||||
name: activeFile.value.name || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
@@ -303,13 +340,13 @@ const loadSheetPreviewFromRaw = async () => {
|
||||
};
|
||||
|
||||
const loadOfficeContent = async () => {
|
||||
if (!props.file?.url) return;
|
||||
if (!activeFile.value?.url) return;
|
||||
if (!props.agentId) throw new Error('agent_id is required for office preview');
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
url: activeFile.value.url,
|
||||
name: activeFile.value.name || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
@@ -415,13 +452,13 @@ const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
|
||||
};
|
||||
|
||||
const loadBinaryContent = async () => {
|
||||
if (!props.file?.url) return;
|
||||
if (!activeFile.value?.url) return;
|
||||
if (!props.agentId) throw new Error('agent_id is required for binary preview');
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
url: activeFile.value.url,
|
||||
name: activeFile.value.name || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
@@ -451,8 +488,8 @@ const loadContent = async () => {
|
||||
excelPreview.value = null;
|
||||
resetExcelZoom();
|
||||
clearOfficeObjectUrl();
|
||||
if (!props.modelValue || !props.file) return;
|
||||
if (!props.file?.url) return;
|
||||
if (!props.modelValue || !activeFile.value) return;
|
||||
if (!activeFile.value?.url) return;
|
||||
resolvedMode.value = preferredMode.value;
|
||||
|
||||
if (['pdf', 'doc', 'docx', 'ppt', 'pptx'].includes(ext.value) && preferredMode.value === 'iframe') {
|
||||
@@ -516,7 +553,7 @@ const loadContent = async () => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (preferredMode.value === 'image' || (preferredMode.value === 'iframe' && !/^https?:\/\//i.test(props.file.url || ''))) {
|
||||
if (preferredMode.value === 'image' || (preferredMode.value === 'iframe' && !/^https?:\/\//i.test(activeFile.value.url || ''))) {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
await loadBinaryContent();
|
||||
@@ -539,8 +576,8 @@ const loadContent = async () => {
|
||||
}
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(props.agentId),
|
||||
url: props.file.url,
|
||||
name: props.file.name || '',
|
||||
url: activeFile.value.url,
|
||||
name: activeFile.value.name || '',
|
||||
ext: ext.value || '',
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
|
||||
@@ -567,7 +604,7 @@ const loadContent = async () => {
|
||||
* - 文件名变化。
|
||||
*/
|
||||
watch(
|
||||
() => [props.modelValue, props.file?.url, props.file?.name],
|
||||
() => [props.modelValue, activeFile.value?.url, activeFile.value?.name, activeIndex.value, activeFiles.value.length],
|
||||
() => {
|
||||
loadContent();
|
||||
},
|
||||
@@ -585,12 +622,15 @@ watch(
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="modelValue && file" class="dialog-overlay z-[140] items-center">
|
||||
<div v-if="modelValue && activeFile" class="dialog-overlay z-[160] items-center">
|
||||
<div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden">
|
||||
<div class="dialog-header dialog-header--compact items-start">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
|
||||
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
|
||||
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ activeFile.name }}</div>
|
||||
<div v-if="isImageGallery" class="mt-1 text-xs text-slate-500 dark:text-slate-400">
|
||||
第 {{ activeIndex + 1 }} / {{ activeFiles.length }} 张
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<div v-if="isExcelPreviewFile" class="flex items-center gap-2 rounded-full border border-default bg-surface px-2 py-1">
|
||||
@@ -713,8 +753,49 @@ watch(
|
||||
style="height: 100%; width: 100%;"
|
||||
/>
|
||||
</div>
|
||||
<div v-else-if="resolvedMode === 'image'" class="dialog-preview-frame h-full flex items-center justify-center p-2">
|
||||
<img :src="imageSrc" :alt="file.name" class="max-w-full max-h-full object-contain" />
|
||||
<div v-else-if="resolvedMode === 'image'" class="dialog-preview-frame h-full flex flex-col p-2">
|
||||
<div class="relative flex min-h-0 flex-1 items-center justify-center rounded-xl bg-slate-50 dark:bg-slate-900/40">
|
||||
<button
|
||||
v-if="isImageGallery"
|
||||
type="button"
|
||||
class="absolute left-3 top-1/2 z-10 inline-flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-slate-200 bg-white/90 text-slate-700 shadow transition hover:bg-white disabled:cursor-not-allowed disabled:opacity-40 dark:border-slate-700 dark:bg-slate-900/90 dark:text-slate-100"
|
||||
:disabled="activeIndex <= 0"
|
||||
aria-label="上一张"
|
||||
@click="showPrevImage"
|
||||
>
|
||||
<ChevronLeft class="h-5 w-5" />
|
||||
</button>
|
||||
<img :src="imageSrc" :alt="activeFile.name" class="max-w-full max-h-full object-contain" />
|
||||
<button
|
||||
v-if="isImageGallery"
|
||||
type="button"
|
||||
class="absolute right-3 top-1/2 z-10 inline-flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-slate-200 bg-white/90 text-slate-700 shadow transition hover:bg-white disabled:cursor-not-allowed disabled:opacity-40 dark:border-slate-700 dark:bg-slate-900/90 dark:text-slate-100"
|
||||
:disabled="activeIndex >= activeFiles.length - 1"
|
||||
aria-label="下一张"
|
||||
@click="showNextImage"
|
||||
>
|
||||
<ChevronRight class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="isImageGallery" class="mt-3 flex gap-3 overflow-x-auto pb-1">
|
||||
<button
|
||||
v-for="(preview, index) in activeFiles"
|
||||
:key="`${preview.name}-${index}`"
|
||||
type="button"
|
||||
:class="[
|
||||
'group shrink-0 overflow-hidden rounded-xl border bg-white text-left shadow-sm transition dark:bg-slate-900',
|
||||
index === activeIndex ? 'border-blue-500 ring-2 ring-blue-200 dark:ring-blue-900/60' : 'border-slate-200 hover:border-blue-300 dark:border-slate-700',
|
||||
]"
|
||||
@click="setActiveIndex(index)"
|
||||
>
|
||||
<div class="flex h-20 w-20 items-center justify-center bg-slate-100 text-sm font-semibold text-slate-500 dark:bg-slate-800 dark:text-slate-300">
|
||||
{{ index + 1 }}
|
||||
</div>
|
||||
<div class="w-20 truncate px-2 py-1 text-xs text-slate-600 dark:text-slate-300">
|
||||
{{ preview.name }}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="['pdf', 'doc', 'ppt', 'pptx'].includes(ext) && officeObjectUrl"
|
||||
|
||||
Reference in new issue
Block a user