feat(chat-fixed-assets): 支持资产履历直达预览并优化 Excel 预览体验

This commit is contained in:
runny committed 2026-07-03 18:59:27 +08:00
1 parent 1164ae2e3c
commit 56b6ea06a8
14 files changed
+1051 -48

No files matched your search

+118 -2
View File
@@ -21,6 +21,7 @@ from flask import Blueprint, request, Response, stream_with_context, jsonify, g,
from sqlalchemy import func, desc, or_, exists, and_
from openpyxl import load_workbook
from app.services.dify import DifyService
from app.core.config.settings import Config
from app.services.integration_api import IntegrationApiService
from app.core.decorators import require_agent_permission
from app.models import Agent, ChatLog, ChatSession, Feedback
@@ -217,8 +218,18 @@ def _normalize_windows_share_path(path_value: str) -> str:
def _is_allowed_share_path(target_url: str) -> bool:
normalized_target = _normalize_windows_share_path(target_url)
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
return bool(normalized_root and normalized_target.startswith('\\\\') and normalized_target.lower().startswith(normalized_root.lower()))
if not normalized_target.startswith('\\\\'):
return False
history_share_root = ''
if has_request_context():
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
if not history_share_root:
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
roots = [
_normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT),
_normalize_windows_share_path(history_share_root),
]
return any(root and normalized_target.lower().startswith(root.lower()) for root in roots)
def _is_allowed_preview_url(target_url: str) -> bool:
"""
@@ -1115,6 +1126,111 @@ def get_chat_query_preview(chat_log_id: int):
'query': query,
})
@chat_bp.route('/asset-history/search', methods=['GET'])
@require_agent_permission
def search_asset_history_files():
"""
检索固定资产履历文件。
用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。
约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。
"""
asset_id = (request.args.get('asset_id') or '').strip()
asset_name = (request.args.get('asset_name') or '').strip()
limit = request.args.get('limit', type=int) or 20
limit = max(1, min(limit, 50))
# #region debug-point C:asset-history-api-entry
import json as _debug_json
import urllib.request as _debug_urllib_request
try:
_debug_payload = _debug_json.dumps({
'sessionId': 'asset-history-click',
'runId': 'pre-fix',
'hypothesisId': 'C',
'location': 'backend/chat.py:search_asset_history_files',
'msg': '[DEBUG] asset history api entry',
'data': {
'asset_id': asset_id,
'asset_name': asset_name,
'limit': limit,
},
}).encode('utf-8')
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
'http://127.0.0.1:7777/event',
data=_debug_payload,
headers={'Content-Type': 'application/json'},
method='POST',
), timeout=2).read()
except Exception:
pass
# #endregion
if not asset_id and not asset_name:
raise ValidationError('asset_id or asset_name is required')
from app.services.fixed_asset_history import FixedAssetHistoryService
if not FixedAssetHistoryService.is_enabled():
# #region debug-point C:asset-history-api-disabled
try:
_debug_payload = _debug_json.dumps({
'sessionId': 'asset-history-click',
'runId': 'pre-fix',
'hypothesisId': 'C',
'location': 'backend/chat.py:search_asset_history_files',
'msg': '[DEBUG] asset history api disabled',
'data': {
'share_root': str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or ''),
},
}).encode('utf-8')
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
'http://127.0.0.1:7777/event',
data=_debug_payload,
headers={'Content-Type': 'application/json'},
method='POST',
), timeout=2).read()
except Exception:
pass
# #endregion
raise ServiceUnavailableError('asset history share is not configured')
items = FixedAssetHistoryService.search_history_files(
asset_id=asset_id,
asset_name=asset_name,
limit=limit,
)
# #region debug-point C:asset-history-api-success
try:
_debug_payload = _debug_json.dumps({
'sessionId': 'asset-history-click',
'runId': 'pre-fix',
'hypothesisId': 'C',
'location': 'backend/chat.py:search_asset_history_files',
'msg': '[DEBUG] asset history api success',
'data': {
'asset_id': asset_id,
'asset_name': asset_name,
'item_count': len(items),
},
}).encode('utf-8')
_debug_urllib_request.urlopen(_debug_urllib_request.Request(
'http://127.0.0.1:7777/event',
data=_debug_payload,
headers={'Content-Type': 'application/json'},
method='POST',
), timeout=2).read()
except Exception:
pass
# #endregion
return jsonify({
'asset_id': asset_id,
'asset_name': asset_name,
'total': len(items),
'items': items,
})
@chat_bp.route('/completions', methods=['POST'])
@require_agent_permission
def chat_completions():
+4
View File
@@ -282,6 +282,10 @@ class Config:
)
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip()
FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip()
FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '')
FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20')
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
str(_ROOT_DIR / 'docs'),
+325
View File
@@ -0,0 +1,325 @@
"""
backend/app/services/fixed_asset_history.py
用途:为固资管理提供“资产履历”共享盘检索能力,按资产编号/资产名称匹配履历文件。
依赖:app.core.config.settings.Config、chat.py 里的预览代理会复用这里返回的共享盘文件路径。
逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索共享盘 -> 前端拿到候选履历文件后继续走既有预览弹窗。
"""
from __future__ import annotations
import os
import re
import subprocess
import threading
import time
from dataclasses import dataclass
from flask import current_app, has_app_context
from app.core.config.settings import Config
_CONNECT_LOCK = threading.Lock()
_LAST_CONNECT_AT = 0.0
_CONNECT_COOLDOWN_SECONDS = 30.0
@dataclass(slots=True)
class AssetHistoryCandidate:
"""资产履历候选文件。"""
path: str
relative_path: str
name: str
actual_ext: str
size_bytes: int
modified_at: str
score: int
match_reason: str
def to_dict(self) -> dict[str, object]:
return {
"name": self.name,
"path": self.path,
"relative_path": self.relative_path,
"actual_ext": self.actual_ext,
"size_bytes": self.size_bytes,
"modified_at": self.modified_at,
"match_reason": self.match_reason,
"url": self.path,
}
class FixedAssetHistoryService:
"""
固资履历检索服务。
AI 触发时机:
- 当聊天结果里已经拿到了具体资产编号,用户点击“资产编号”想看履历时调用;
- 输入必须至少包含资产编号或资产名称中的一个;
- 输出只返回共享盘上可预览的候选文件,不直接拼接文件内容。
"""
HISTORY_FILE_EXTENSIONS = {".xls", ".xlsx", ".pdf", ".doc", ".docx", ".txt"}
@classmethod
def _get_runtime_setting(cls, key: str, default: str = "") -> str:
if has_app_context():
try:
value = current_app.config.get(key)
if value is not None:
return str(value)
except Exception:
pass
return str(getattr(Config, key, default) or default)
@classmethod
def is_enabled(cls) -> bool:
return bool(cls.get_share_root())
@classmethod
def get_share_root(cls) -> str:
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_ROOT').strip()
@classmethod
def search_history_files(
cls,
*,
asset_id: str,
asset_name: str = "",
limit: int | None = None,
) -> list[dict[str, object]]:
"""
按资产编号/资产名称检索履历文件。
[STEP 1] 先尝试建立共享盘访问权限,避免 Windows 服务账号没有提前挂载网络盘。
[STEP 2] 优先用资产编号做全局文件名命中,确保定位到唯一设备履历。
[STEP 3] 再用资产名称命中同名文件夹/文件,补足部分历史文件只按设备名称归档的情况。
"""
asset_id_value = cls._normalize_keyword(asset_id)
asset_name_value = cls._normalize_keyword(asset_name)
if not asset_id_value and not asset_name_value:
return []
root = cls.get_share_root()
if not root:
return []
if not os.path.exists(root):
cls._ensure_share_connected(root)
if not os.path.isdir(root):
return []
max_results = max(
1,
min(int(limit or cls._get_runtime_setting('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or 20), 50),
)
candidates: dict[str, AssetHistoryCandidate] = {}
if asset_id_value:
for current_root, _dirs, files in os.walk(root):
for filename in files:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
asset_id=asset_id_value,
asset_name=asset_name_value,
match_reason="asset_id",
)
if candidate:
cls._merge_candidate(candidates, candidate)
folder_candidates = cls._find_matching_folders(root, asset_name_value)
for folder_path in folder_candidates:
for current_root, _dirs, files in os.walk(folder_path):
for filename in files:
candidate = cls._build_candidate(
root=root,
file_path=os.path.join(current_root, filename),
asset_id=asset_id_value,
asset_name=asset_name_value,
match_reason="asset_name_folder",
)
if candidate:
cls._merge_candidate(candidates, candidate)
if asset_name_value:
for entry in os.scandir(root):
if not entry.is_file():
continue
candidate = cls._build_candidate(
root=root,
file_path=entry.path,
asset_id=asset_id_value,
asset_name=asset_name_value,
match_reason="asset_name_file",
)
if candidate:
cls._merge_candidate(candidates, candidate)
ordered = sorted(
candidates.values(),
key=lambda item: (-item.score, item.relative_path.lower(), item.name.lower()),
)
return [item.to_dict() for item in ordered[:max_results]]
@classmethod
def _merge_candidate(
cls,
existing: dict[str, AssetHistoryCandidate],
candidate: AssetHistoryCandidate,
) -> None:
previous = existing.get(candidate.path)
if previous is None or candidate.score > previous.score:
existing[candidate.path] = candidate
@classmethod
def _find_matching_folders(cls, root: str, asset_name: str) -> list[str]:
if not asset_name:
return []
matches: list[str] = []
for entry in os.scandir(root):
if not entry.is_dir():
continue
normalized_folder = cls._normalize_keyword(entry.name)
if asset_name and asset_name in normalized_folder:
matches.append(entry.path)
return matches
@classmethod
def _build_candidate(
cls,
*,
root: str,
file_path: str,
asset_id: str,
asset_name: str,
match_reason: str,
) -> AssetHistoryCandidate | None:
if not os.path.isfile(file_path):
return None
ext = os.path.splitext(file_path)[1].strip().lower()
if ext and ext not in cls.HISTORY_FILE_EXTENSIONS:
return None
filename = os.path.basename(file_path)
searchable_parts = [
cls._normalize_keyword(filename),
cls._normalize_keyword(os.path.relpath(file_path, root)),
]
searchable_text = " ".join(part for part in searchable_parts if part)
if not searchable_text:
return None
if asset_id and asset_id not in searchable_text:
return None
if asset_name and asset_name not in searchable_text and match_reason != "asset_id":
return None
score = cls._score_candidate(
searchable_text=searchable_text,
filename=cls._normalize_keyword(filename),
asset_id=asset_id,
asset_name=asset_name,
match_reason=match_reason,
)
if score <= 0:
return None
stat = os.stat(file_path)
return AssetHistoryCandidate(
path=file_path,
relative_path=os.path.relpath(file_path, root).replace("/", "\\"),
name=filename,
actual_ext=ext.lstrip("."),
size_bytes=int(stat.st_size),
modified_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stat.st_mtime)),
score=score,
match_reason=match_reason,
)
@classmethod
def _score_candidate(
cls,
*,
searchable_text: str,
filename: str,
asset_id: str,
asset_name: str,
match_reason: str,
) -> int:
score = 0
if asset_id:
if asset_id in filename:
score += 120
elif asset_id in searchable_text:
score += 80
if asset_name:
if asset_name in filename:
score += 60
elif asset_name in searchable_text:
score += 40
if "履历" in filename:
score += 20
if match_reason == "asset_name_folder":
score += 10
return score
@classmethod
def _normalize_keyword(cls, value: str | None) -> str:
text = str(value or "").strip().lower()
if not text:
return ""
return re.sub(r"[\s\\/_\-()()【】\[\],。,;;::]+", "", text)
@classmethod
def _ensure_share_connected(cls, root: str) -> None:
"""
尝试用配置的账号密码建立共享盘会话。
账号密码只从环境变量读取,避免把敏感信息写进仓库。
"""
username = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_USERNAME').strip()
password = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_PASSWORD')
if not username or not password:
return
share_root = cls._extract_server_share_root(root)
if not share_root:
return
global _LAST_CONNECT_AT
now = time.time()
if now - _LAST_CONNECT_AT < _CONNECT_COOLDOWN_SECONDS:
return
with _CONNECT_LOCK:
if time.time() - _LAST_CONNECT_AT < _CONNECT_COOLDOWN_SECONDS:
return
try:
subprocess.run(
[
"net",
"use",
share_root,
password,
f"/user:{username}",
"/persistent:no",
],
check=False,
capture_output=True,
text=True,
timeout=8,
)
except Exception:
return
_LAST_CONNECT_AT = time.time()
@staticmethod
def _extract_server_share_root(path_value: str) -> str:
normalized = str(path_value or "").strip().replace("/", "\\")
if not normalized.startswith("\\\\"):
return ""
parts = [part for part in normalized[2:].split("\\") if part]
if len(parts) < 2:
return ""
return f"\\\\{parts[0]}\\{parts[1]}"
+1
View File
@@ -61,6 +61,7 @@
| 固资备注模糊检索 | 已实现 | 同步时生成 `备注` 与标准化备注,查询时作为结构化条件兜底 |
| 固资本地快照查询 | 已实现 | `固资管理` Agent 优先查询 SQLite 最新快照,减少实时 ERP 压力 |
| 固资导出文件 | 已实现 | 同步成功后生成 `FixedAssets_latest.xlsx`,供人工核查与留档 |
| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看 |
### F-01 本人假期查询
+15 -1
View File
@@ -1,10 +1,11 @@
/**
/**
* features/chat/api/chat.api.ts
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
import type {
AssetHistorySearchResult,
ChatCrossAgentHistoryItem,
ChatMessage,
ChatQueryPreviewPage,
@@ -90,4 +91,17 @@ export const getChatQueryPreviewPage = (
return requestJson<ChatQueryPreviewPage>(`/api/chat/query-preview/${chatLogId}?${qs.toString()}`, auth());
};
export const searchAssetHistoryFiles = (
agentId: number,
query: { asset_id?: string; asset_name?: string; limit?: number },
) => {
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);
if (query.limit) qs.set('limit', String(query.limit));
return requestJson<AssetHistorySearchResult>(`/api/chat/asset-history/search?${qs.toString()}`, auth());
};
export type { ChatSessionItem, ChatCrossAgentHistoryItem };
@@ -0,0 +1,91 @@
<script setup lang="ts">
/**
* features/chat/components/ChatAssetHistoryDialog.vue
* 用途:展示固定资产履历候选文件列表,并复用既有文件预览弹窗打开具体履历。
* 依赖:聊天页 useChatPage 提供的查询状态与打开预览回调。
* 逻辑:用户点击资产编号后打开;先显示检索状态,再列出共享盘匹配文件,点击单条文件进入预览。
*/
import { computed } from 'vue';
import { ExternalLink, FileText, Loader2, X } from 'lucide-vue-next';
import type { AssetHistoryFileItem } from '../types/chat.types';
const open = defineModel<boolean>('open', { required: true });
const props = defineProps<{
loading: boolean;
error: string;
assetId: string;
assetName: string;
items: AssetHistoryFileItem[];
}>();
const emit = defineEmits<{
close: [];
openPreview: [item: AssetHistoryFileItem];
}>();
const titleText = computed(() => props.assetId || props.assetName || '资产履历');
</script>
<template>
<div
v-if="open"
class="dialog-overlay z-[120] items-center"
@click.self="emit('close')"
>
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,900px)] max-w-[900px] flex-col">
<div class="dialog-header">
<div>
<h3 class="section-title">资产履历</h3>
<p class="section-desc mt-1">当前资产:{{ titleText }}</p>
</div>
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="emit('close')">
<X class="h-5 w-5" />
</button>
</div>
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
<div v-if="loading" class="flex h-56 items-center justify-center text-sm text-muted">
<Loader2 class="mr-2 h-5 w-5 animate-spin text-brand-500" />
正在检索共享盘履历文件...
</div>
<div v-else-if="error" class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
{{ error }}
</div>
<div
v-else-if="items.length === 0"
class="flex h-56 items-center justify-center rounded-2xl border border-dashed border-default bg-surface-soft text-sm text-muted"
>
未找到匹配的履历文件
</div>
<div v-else class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
<div
v-for="item in items"
:key="item.path"
class="flex items-start justify-between gap-3 border-b border-default px-4 py-4 last:border-b-0"
>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2 text-sm font-semibold text-primary">
<FileText class="h-4 w-4 shrink-0 text-brand-500" />
<span class="truncate">{{ item.name }}</span>
</div>
<div class="mt-1 break-all text-xs text-secondary">{{ item.relative_path }}</div>
<div class="mt-2 flex flex-wrap gap-3 text-xs text-muted">
<span v-if="item.modified_at">修改时间:{{ item.modified_at }}</span>
<span v-if="item.size_bytes">大小:{{ Math.max(1, Math.round(item.size_bytes / 1024)) }} KB</span>
<span v-if="item.match_reason">匹配方式:{{ item.match_reason }}</span>
</div>
</div>
<button
type="button"
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-default px-3 py-2 text-sm font-medium text-brand-600 transition hover:bg-brand-50"
@click="emit('openPreview', item)"
>
<ExternalLink class="h-4 w-4" />
查看履历
</button>
</div>
</div>
</div>
</div>
</div>
</template>
@@ -18,11 +18,29 @@ const props = defineProps<{
const emit = defineEmits<{
close: [];
'change-page': [delta: number];
'open-asset-history': [payload: { assetId: string; assetName: string }];
}>();
const totalPages = computed(() =>
Math.max(1, Math.ceil((props.state.total || 0) / (props.state.pageSize || 100))),
);
const assetIdColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产编号'));
const assetNameColumnIndex = computed(() => props.state.columns.findIndex((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]);
}
function emitAssetHistory(row: unknown[]): void {
const assetId = normalizeCellText(row[assetIdColumnIndex.value]);
const assetName = assetNameColumnIndex.value >= 0 ? normalizeCellText(row[assetNameColumnIndex.value]) : '';
if (!assetId) return;
emit('open-asset-history', { assetId, assetName });
}
</script>
<template>
@@ -96,7 +114,15 @@ const totalPages = computed(() =>
:key="`query-preview-cell-${rowIndex}-${cellIndex}`"
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
>
<div class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
<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)"
>
{{ cell ?? '-' }}
</button>
<div v-else class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
</td>
</tr>
</tbody>
@@ -1,6 +1,6 @@
/**
/**
* features/chat/components/ChatViewOverlays.vue
* 对话页全局弹窗:文件预览、反馈、查询预览、请假 OA、删除确认、学习之窗。
* 对话页全局弹窗与浮层:文件预览、反馈、查询预览、履历检索提示、请假 OA、删除确认、学习之窗。
*/
<script setup lang="ts">
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
@@ -10,6 +10,7 @@ import ChatQueryPreviewDialog from '@/features/chat/components/ChatQueryPreviewD
import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialog.vue';
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
import { Loader2 } from 'lucide-vue-next';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { getAuthHeaders } from '@/shared/utils/auth';
@@ -45,7 +46,17 @@ function onFeedbackSubmitted() {
:state="page.queryPreviewState"
@close="page.queryPreview.close"
@change-page="page.queryPreview.changePage"
@open-asset-history="({ assetId, assetName }) => page.assetHistory.openHistory(assetId, assetName)"
/>
<div
v-if="page.assetHistory.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"
@@ -21,6 +21,7 @@ import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload }
export interface ChatMessageBubbleHandlers {
renderMarkdown: (text: string) => string;
onMarkdownClick: (event: MouseEvent) => void;
openAssetHistory: (assetId: string, assetName?: string) => void;
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
downloadInlineFile: (file: InlineDownloadFile) => void;
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
@@ -431,10 +432,11 @@ const inlineDialogPage = ref(1);
const activeInlineFilterIndexes = computed(() => {
const table = activeInlineDialogEntry.value?.table;
if (!table) {
return { assetId: -1, custodianPerson: -1, custodianDept: -1 };
return { assetId: -1, assetName: -1, custodianPerson: -1, custodianDept: -1 };
}
return {
assetId: findInlineTableHeaderIndex(table.rawHeaders, ['asset_id', 'asset_no']),
assetName: findInlineTableHeaderIndex(table.rawHeaders, ['asset_name']),
custodianPerson: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_person', 'custodian_name']),
custodianDept: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_dept', 'department_name']),
};
@@ -521,6 +523,19 @@ function changeInlineDialogPage(nextPage: number): void {
inlineDialogPage.value = Math.min(Math.max(1, nextPage), activeInlineTotalPages.value);
}
function canOpenInlineAssetHistory(cellIndex: number, cellValue: string): boolean {
const normalizedValue = String(cellValue || '').trim();
return cellIndex === activeInlineFilterIndexes.value.assetId && !!normalizedValue && normalizedValue !== '-';
}
function openInlineAssetHistory(row: string[]): 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;
handlers.openAssetHistory(assetId, assetName === '-' ? '' : assetName);
}
/**
* 响应聊天消息里的内嵌文件下载按钮点击。
* 核心逻辑:复用页面层 handlers 生成 Blob 下载,组件层只负责把当前文件对象回传出去。
@@ -617,6 +632,7 @@ function handleInlineDownload(file: InlineDownloadFile): void {
v-else-if="renderedMarkdown"
ref="markdownContainer"
class="markdown-body chat-markdown min-w-0 break-words text-sm leading-relaxed"
@click="handlers.onMarkdownClick"
v-html="renderedMarkdown"
/>
@@ -885,7 +901,15 @@ function handleInlineDownload(file: InlineDownloadFile): void {
:key="`${activeInlineDialogEntry.file.name}-dialog-cell-${rowIndex}-${cellIndex}`"
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
>
<div class="whitespace-pre-wrap break-all">{{ cell || '-' }}</div>
<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)"
>
{{ cell || '-' }}
</button>
<div v-else class="whitespace-pre-wrap break-all">{{ cell || '-' }}</div>
</td>
</tr>
</tbody>
@@ -0,0 +1,106 @@
/**
* features/chat/composables/useChatAssetHistory.ts
* 用途:管理固定资产履历检索、友好提示与文件预览跳转。
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
* 逻辑:页面层统一持有“打开履历”动作,消息气泡/查询预览弹窗复用该入口;
* 点击资产编号后先进入“检索中”状态,命中履历文件则直接打开最佳候选预览,未命中时仅提示用户。
*/
import { ref } from 'vue';
import { searchAssetHistoryFiles } from '../api/chat.api';
import type { AssetHistoryFileItem, SourceFileLink } from '../types/chat.types';
import type { ComputedRef } from 'vue';
interface UseChatAssetHistoryOptions {
agentId: ComputedRef<number>;
openPreview: (file: SourceFileLink) => Promise<void>;
warn: (message: string) => void;
}
export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
const open = ref(false);
const loading = ref(false);
const error = ref('');
const assetId = ref('');
const assetName = ref('');
const items = ref<AssetHistoryFileItem[]>([]);
const close = () => {
open.value = false;
loading.value = false;
error.value = '';
items.value = [];
};
/**
* 检索资产履历并直接打开最佳预览结果。
* AI 触发时机:当用户点击聊天表格中的“资产编号”,希望直接查看该资产履历时调用。
* 核心逻辑:点击后先切入“检索中”状态,再按“资产编号 + 资产名称”查询共享盘候选文件,命中后默认取排序最优的第一条直接预览;
* 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表。
* 参数约束:至少要提供资产编号或资产名称之一;候选文件排序由后端负责,本方法默认信任第一条结果。
*/
const openHistory = async (nextAssetId: string, nextAssetName = '') => {
const normalizedAssetId = String(nextAssetId || '').trim();
const normalizedAssetName = String(nextAssetName || '').trim();
if (loading.value) {
return;
}
if (!normalizedAssetId && !normalizedAssetName) {
options.warn('当前资产缺少可用于检索履历的编号或名称');
return;
}
assetId.value = normalizedAssetId;
assetName.value = normalizedAssetName;
open.value = false;
loading.value = true;
error.value = '';
items.value = [];
try {
const result = await searchAssetHistoryFiles(options.agentId.value, {
asset_id: normalizedAssetId,
asset_name: normalizedAssetName,
});
items.value = Array.isArray(result?.items) ? result.items : [];
const bestMatch = items.value[0];
if (!bestMatch) {
const displayName = normalizedAssetId || normalizedAssetName;
options.warn(`未找到资产 ${displayName} 的履历文件,如确认应有履历,请联系管理员补充。`);
return;
}
await openHistoryFilePreview(bestMatch);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '检索资产履历失败';
error.value = message;
options.warn(`履历查询失败:${message}`);
} finally {
loading.value = false;
}
};
/**
* 打开履历文件预览。
* AI 触发时机:当用户在“资产履历”列表里点击某一条“查看履历”时调用。
* 核心逻辑:先关闭履历候选列表弹窗,避免与文件预览弹窗叠层冲突,再交给聊天页通用预览器处理。
* 参数约束:必须传入带有 name/url 的有效履历文件项,url 必须是后端允许代理的共享盘路径。
*/
const openHistoryFilePreview = async (item: AssetHistoryFileItem) => {
close();
await options.openPreview({
name: item.name,
url: item.url,
actualExt: item.actual_ext,
});
};
return {
open,
loading,
error,
assetId,
assetName,
items,
close,
openHistory,
openHistoryFilePreview,
};
}
@@ -25,6 +25,7 @@ import { useChatScroll } from './useChatScroll';
import { useChatSessions } from './useChatSessions';
import { useChatShipping } from './useChatShipping';
import { useChatSourceFiles } from './useChatSourceFiles';
import { useChatAssetHistory } from './useChatAssetHistory';
import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace, matchesTrainingAgent } from './useTrainingWorkspace';
import {
@@ -158,6 +159,11 @@ export function useChatPage() {
openPreview,
parsePlmPreviewLink,
} = sourceFiles;
const assetHistory = useChatAssetHistory({
agentId: currentAgentId,
openPreview,
warn: (text) => msg.warning(text),
});
watch(currentAgentId, (id) => {
chatStore.setCurrentAgentId(id > 0 ? id : null);
@@ -344,6 +350,7 @@ export function useChatPage() {
handleLeaveMarkdownClick: leave.handleLeaveMarkdownClick,
parsePlmPreviewLink,
openPreview,
openAssetHistory: assetHistory.openHistory,
getMessageLinks,
getDisplayRetrieverResources,
getSourceLinks,
@@ -482,6 +489,7 @@ export function useChatPage() {
queryPreviewLoading: queryPreview.loading,
queryPreviewError: queryPreview.error,
queryPreviewState: queryPreview.state,
assetHistory,
...agent,
agentGuides: chatGuides.guides,
showGuideModal: chatGuides.showModal,
@@ -64,6 +64,7 @@ export interface ChatPageMarkdownContext {
handleLeaveMarkdownClick: (event: MouseEvent) => void;
parsePlmPreviewLink: (href: string) => SourceFileLink | null;
openPreview: (file: SourceFileLink) => Promise<void>;
openAssetHistory: (assetId: string, assetName?: string) => void;
getMessageLinks: (message: Record<string, unknown>) => SourceFileLink[];
getDisplayRetrieverResources: (msgItem: Record<string, unknown>) => Record<string, unknown>[];
getSourceLinks: (resources?: unknown[]) => SourceFileLink[];
@@ -178,6 +179,47 @@ function downloadInlineFile(file: InlineDownloadFile): void {
URL.revokeObjectURL(objectUrl);
}
function normalizeAssetHistoryText(value: string): string {
const normalized = String(value || '').trim();
if (!normalized || normalized === '-' || normalized === '无') return '';
return normalized;
}
/**
* 把聊天结果表格里的“资产编号”列增强为可点击入口。
* 核心逻辑:只处理包含“资产编号”表头的表格,并从同行“资产名称”列一并带出检索关键词,避免误伤其他普通 Markdown 表格。
*/
function enhanceAssetHistoryTableLinks(html: string): string {
if (!html || typeof document === 'undefined' || !html.includes('<table')) return html;
const container = document.createElement('div');
container.innerHTML = html;
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 || ''));
const assetIdIndex = headerLabels.findIndex((label) => label === '资产编号');
if (assetIdIndex < 0) return;
const assetNameIndex = headerLabels.findIndex((label) => label === '资产名称');
const rows = Array.from(table.querySelectorAll('tbody tr'));
rows.forEach((row) => {
const cells = Array.from(row.querySelectorAll('td'));
const assetIdCell = cells[assetIdIndex];
if (!assetIdCell) return;
const assetId = normalizeAssetHistoryText(assetIdCell.textContent || '');
if (!assetId) return;
const assetName = assetNameIndex >= 0 ? normalizeAssetHistoryText(cells[assetNameIndex]?.textContent || '') : '';
const link = document.createElement('a');
link.href = `#asset-history?asset_id=${encodeURIComponent(assetId)}&asset_name=${encodeURIComponent(assetName)}`;
link.className = 'chat-asset-history-link';
link.textContent = assetId;
assetIdCell.innerHTML = '';
assetIdCell.appendChild(link);
});
});
return container.innerHTML;
}
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
@@ -226,7 +268,34 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const handleChatMarkdownClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
const preview = ctx.parsePlmPreviewLink(anchor?.getAttribute('href') || '');
const rawHref = anchor?.getAttribute('href') || '';
// #region debug-point A:asset-history-anchor-click
if (rawHref.startsWith('#asset-history?')) {
fetch('http://127.0.0.1:7777/event', {
method: 'POST',
body: JSON.stringify({
sessionId: 'asset-history-click',
runId: 'pre-fix',
hypothesisId: 'A',
location: 'frontend/useChatPageMarkdown.ts',
msg: '[DEBUG] asset history anchor clicked',
data: {
href: rawHref,
tagName: target?.tagName || '',
anchorText: String(anchor?.textContent || '').trim(),
},
ts: Date.now(),
}),
}).catch(() => {});
}
// #endregion
if (rawHref.startsWith('#asset-history?')) {
event.preventDefault();
const params = new URLSearchParams(rawHref.slice('#asset-history?'.length));
ctx.openAssetHistory((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim());
return;
}
const preview = ctx.parsePlmPreviewLink(rawHref);
if (preview) {
event.preventDefault();
void ctx.openPreview(preview);
@@ -248,7 +317,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
try {
const rendered = marked.parse(displayText);
const html = typeof rendered === 'string' ? rendered : displayText;
return html
return enhanceAssetHistoryTableLinks(html)
.replace(/<(td|th)\b([^>]*)>(?:\s|&nbsp;|<br\s*\/?>)*<\/\1>/gi, (_match, tagName: string, attrs: string) => (
`<${tagName}${attrs}>无</${tagName}>`
))
@@ -263,6 +332,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
renderMarkdown,
onMarkdownClick: handleChatMarkdownClick,
openAssetHistory: ctx.openAssetHistory,
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
downloadInlineFile,
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
@@ -99,6 +99,24 @@ export interface ChatSourceFileResult {
source_ext?: string;
}
export interface AssetHistoryFileItem {
name: string;
path: string;
relative_path: string;
url: string;
actual_ext?: string;
size_bytes?: number;
modified_at?: string;
match_reason?: string;
}
export interface AssetHistorySearchResult {
asset_id?: string;
asset_name?: string;
total: number;
items: AssetHistoryFileItem[];
}
export interface ChatUploadResult {
id: string;
name?: string;
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script setup lang="ts">
/**
* shared/components/FilePreviewModal.vue
* 文件预览弹窗(图片/PDF 等)。
@@ -10,13 +10,15 @@
* 引用文件:vue, marked
* 逻辑关系:
* - 接收 ChatView 传入的 file(name/url)与弹窗显隐状态
* - 根据扩展名选择预览模式(markdown/image/iframe)
* - 根据扩展名选择预览模式(markdown/image/iframe/office)
* - Excel 预览优先走 Office 风格渲染,尽量还原原始表格观感;失败时再降级为简化表格
* - 对 Office 文档在可公网 HTTPS 访问时走 Office 在线预览,否则降级为打开/下载
*/
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 VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
@@ -39,7 +41,7 @@ interface ExcelPreviewData {
}
type OfficeKind = 'docx' | 'excel' | 'pdf' | null;
type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'office';
type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'sheetHtml' | 'office';
const props = defineProps<{
modelValue: boolean;
@@ -56,11 +58,17 @@ const { t } = useI18n();
const isLoading = ref(false);
const error = ref('');
const markdownHtml = ref('');
const excelHtml = ref('');
const excelPreview = ref<ExcelPreviewData | null>(null);
const officeSrc = ref<string | ArrayBuffer | Blob>('');
const officeKind = ref<OfficeKind>(null);
const officeObjectUrl = ref<string>('');
const officeRenderKey = ref(0);
const excelZoom = ref(1);
const EXCEL_ZOOM_STEP = 0.1;
const EXCEL_ZOOM_MIN = 0.6;
const EXCEL_ZOOM_MAX = 1.8;
/**
* 从 URL 或文件名中提取扩展名。
@@ -87,8 +95,7 @@ const ext = computed(() => {
const preferredMode = computed<PreviewMode>(() => {
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
if (['xlsx', 'xls'].includes(ext.value)) return 'sheet';
if (['docx'].includes(ext.value)) return 'office';
if (['xlsx', 'xls', 'docx'].includes(ext.value)) return 'office';
if (['doc', 'ppt', 'pptx', 'pdf'].includes(ext.value)) return 'iframe';
return 'iframe';
});
@@ -120,6 +127,13 @@ const iframeSrc = computed(() => {
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
const officePreviewExts = new Set(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']);
const isExcelPreviewFile = computed(() => ['xls', 'xlsx'].includes(ext.value));
const excelZoomPercent = computed(() => `${Math.round(excelZoom.value * 100)}%`);
const excelPreviewScaleStyle = computed(() => ({
transform: `scale(${excelZoom.value})`,
transformOrigin: 'top left',
width: `${100 / excelZoom.value}%`,
}));
const close = () => emit('update:modelValue', false);
@@ -134,6 +148,25 @@ const clearOfficeObjectUrl = () => {
officeKind.value = null;
};
/**
* 调整 Excel 预览缩放比例。
* AI 触发时机:当用户点击弹窗头部的放大/缩小按钮,希望更清楚查看履历表格时调用。
* 核心逻辑:按照固定步进调整缩放,并限制在可读范围内,避免放得过大或过小。
* 参数与输出约束:delta 仅表示增量,不直接写死最终倍率;最终结果会被钳制到 60%~180%。
*/
const adjustExcelZoom = (delta: number) => {
const nextZoom = excelZoom.value + delta;
excelZoom.value = Math.min(EXCEL_ZOOM_MAX, Math.max(EXCEL_ZOOM_MIN, Number(nextZoom.toFixed(2))));
};
/**
* 重置 Excel 预览缩放比例。
* 用途:让用户一键回到默认 100% 视图,避免多次缩放后难以恢复。
*/
const resetExcelZoom = () => {
excelZoom.value = 1;
};
const extractErrorMessage = (payload: any, fallback: string) => {
if (!payload) return fallback;
if (typeof payload === 'string' && payload.trim()) return payload.trim();
@@ -186,6 +219,27 @@ const applyExcelPreview = (buffer: ArrayBuffer) => {
};
};
/**
* 将 Excel 原始工作表转为 HTML 预览。
* 用途:尽量保留原 Excel 的布局、合并单元格和表格观感,使履历预览更接近用户看到的原文件。
* 约束:仅使用第一个工作表;若库无法解析原始布局,则抛错并交给表格矩阵模式兜底。
*/
const applyExcelHtmlPreview = (buffer: ArrayBuffer) => {
const workbook = XLSX.read(buffer, { type: 'array', cellStyles: true });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
excelHtml.value = XLSX.utils.sheet_to_html(worksheet, {
id: 'hxops-excel-preview-table',
editable: false,
});
};
const tryApplyExcelPreview = (buffer: ArrayBuffer) => {
try {
applyExcelPreview(buffer);
@@ -214,6 +268,40 @@ const loadSheetPreview = async () => {
excelPreview.value = await res.json();
};
/**
* 直接拉取原始 Excel 二进制并在前端解析。
* 用途:当后端 `/preview-excel` 无法处理共享盘里的旧版 Excel 时,前端仍尽量展示首个工作表内容。
* 约束:仅作为 Excel 预览兜底使用;解析失败时继续向上抛错,由统一错误 UI 呈现。
*/
const loadSheetPreviewFromRaw = async () => {
if (!props.file?.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 || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
const buffer = await res.arrayBuffer();
try {
applyExcelHtmlPreview(buffer);
resolvedMode.value = 'sheetHtml';
return;
} catch {
if (!tryApplyExcelPreview(buffer)) {
throw new Error('failed to parse excel file');
}
resolvedMode.value = 'sheet';
}
};
const loadOfficeContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for office preview');
@@ -240,6 +328,23 @@ const loadOfficeContent = async () => {
else officeKind.value = null;
};
/**
* Excel Office 风格渲染失败后的兜底处理。
* AI 触发时机:当 `VueOfficeExcel` 无法正确渲染共享盘里的旧版/特殊 Excel 时调用。
* 核心逻辑:优先走后端 `/preview-excel` 简化预览,失败后再回退到前端原始二进制解析,确保用户至少能看到表格内容。
* 参数与输出约束:该方法只处理当前已加载文件,不接收外部参数;成功后会把 `resolvedMode` 切换为 `sheet`。
*/
const fallbackToSheetPreview = async () => {
try {
await loadSheetPreviewFromRaw();
error.value = '';
} catch {
await loadSheetPreview();
resolvedMode.value = 'sheet';
error.value = '';
}
};
const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
if (!props.file?.url) return 'iframe';
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
@@ -342,7 +447,9 @@ const loadBinaryContent = async () => {
const loadContent = async () => {
error.value = '';
markdownHtml.value = '';
excelHtml.value = '';
excelPreview.value = null;
resetExcelZoom();
clearOfficeObjectUrl();
if (!props.modelValue || !props.file) return;
if (!props.file?.url) return;
@@ -374,8 +481,17 @@ const loadContent = async () => {
}
resolvedMode.value = 'office';
} catch (e: any) {
error.value = e?.message || 'Failed to preview office file';
resolvedMode.value = 'iframe';
if (['xlsx', 'xls'].includes(ext.value)) {
try {
await fallbackToSheetPreview();
} catch {
error.value = e?.message || 'Failed to preview excel';
resolvedMode.value = 'iframe';
}
} else {
error.value = e?.message || 'Failed to preview office file';
resolvedMode.value = 'iframe';
}
} finally {
isLoading.value = false;
}
@@ -387,8 +503,13 @@ const loadContent = async () => {
await loadSheetPreview();
resolvedMode.value = 'sheet';
} catch (e: any) {
error.value = e?.message || 'Failed to preview excel';
resolvedMode.value = 'iframe';
try {
await loadSheetPreviewFromRaw();
resolvedMode.value = 'sheet';
} catch {
error.value = e?.message || 'Failed to preview excel';
resolvedMode.value = 'iframe';
}
} finally {
isLoading.value = false;
}
@@ -464,14 +585,47 @@ watch(
</script>
<template>
<div v-if="modelValue && file" class="dialog-overlay dialog-overlay--z80 items-center">
<div v-if="modelValue && file" class="dialog-overlay z-[140] 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>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
<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">
<button
type="button"
class="btn-icon-ds h-8 w-8"
aria-label="缩小"
:disabled="excelZoom <= EXCEL_ZOOM_MIN"
@click="adjustExcelZoom(-EXCEL_ZOOM_STEP)"
>
<Minus class="h-4 w-4" />
</button>
<button
type="button"
class="rounded-md px-2 py-1 text-xs font-medium text-secondary transition hover:bg-surface-soft"
aria-label="重置缩放"
@click="resetExcelZoom"
>
<span class="inline-flex items-center gap-1">
<RotateCcw class="h-3.5 w-3.5" />
{{ excelZoomPercent }}
</span>
</button>
<button
type="button"
class="btn-icon-ds h-8 w-8"
aria-label="放大"
:disabled="excelZoom >= EXCEL_ZOOM_MAX"
@click="adjustExcelZoom(EXCEL_ZOOM_STEP)"
>
<Plus class="h-4 w-4" />
</button>
</div>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
</div>
</div>
<div class="dialog-preview-body">
@@ -493,34 +647,44 @@ watch(
v-else-if="resolvedMode === 'sheet' && excelPreview"
class="dialog-preview-frame h-full p-4 overflow-auto"
>
<div class="mb-3 text-xs text-muted">
Sheet: {{ excelPreview.sheet_name }} | Rows: {{ excelPreview.rows.length }}
<span v-if="excelPreview.truncated"> (truncated)</span>
<div :style="excelPreviewScaleStyle" class="pb-6">
<div class="mb-3 text-xs text-muted">
Sheet: {{ excelPreview.sheet_name }} | Rows: {{ excelPreview.rows.length }}
<span v-if="excelPreview.truncated"> (truncated)</span>
</div>
<table class="min-w-full text-xs border-collapse">
<thead>
<tr>
<th
v-for="(col, i) in excelPreview.columns"
:key="`h-${i}`"
class="sticky top-0 bg-surface-soft border border-default px-2 py-1 text-left font-semibold text-secondary"
>
{{ col }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in excelPreview.rows" :key="`r-${ri}`">
<td
v-for="(cell, ci) in row"
:key="`c-${ri}-${ci}`"
class="border border-default px-2 py-1 align-top whitespace-pre-wrap break-words text-secondary"
>
{{ cell }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div
v-else-if="resolvedMode === 'sheetHtml' && excelHtml"
class="dialog-preview-frame h-full overflow-auto bg-white p-4"
>
<div :style="excelPreviewScaleStyle" class="pb-6">
<div class="excel-html-preview min-w-max" v-html="excelHtml"></div>
</div>
<table class="min-w-full text-xs border-collapse">
<thead>
<tr>
<th
v-for="(col, i) in excelPreview.columns"
:key="`h-${i}`"
class="sticky top-0 bg-surface-soft border border-default px-2 py-1 text-left font-semibold text-secondary"
>
{{ col }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in excelPreview.rows" :key="`r-${ri}`">
<td
v-for="(cell, ci) in row"
:key="`c-${ri}-${ci}`"
class="border border-default px-2 py-1 align-top whitespace-pre-wrap break-words text-secondary"
>
{{ cell }}
</td>
</tr>
</tbody>
</table>
</div>
<div
v-else-if="resolvedMode === 'office' && officeKind"
@@ -538,6 +702,8 @@ watch(
v-else-if="officeKind === 'excel'"
:key="`excel-${officeRenderKey}`"
:src="officeSrc"
@rendered="error = ''"
@error="fallbackToSheetPreview().catch(() => { error = 'Excel render failed'; resolvedMode = 'sheet'; })"
style="height: 100%; width: 100%;"
/>
<VueOfficePdf
@@ -581,3 +747,26 @@ watch(
</div>
</div>
</template>
<style scoped>
.excel-html-preview :deep(table) {
border-collapse: collapse;
background: #fff;
color: #111827;
font-size: 14px;
}
.excel-html-preview :deep(td),
.excel-html-preview :deep(th) {
min-width: 52px;
border: 1px solid #111827;
padding: 4px 6px;
vertical-align: middle;
white-space: pre-wrap;
}
.excel-html-preview :deep(tr:nth-child(-n + 2) td),
.excel-html-preview :deep(tr:nth-child(-n + 2) th) {
text-align: center;
}
</style>