feat(chat): 完善固资预览与下载权限

This commit is contained in:
runny committed 2026-07-07 02:27:08 +08:00
1 parent 6ce0942fef
commit bf18a7ef1d
19 files changed
+1163 -86

No files matched your search

+39
View File
@@ -320,6 +320,16 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
if _extract_placeholder_text(content):
guessed_type = 'text/plain; charset=utf-8'
return (content, guessed_type, None)
try:
from app.services.fixed_asset_image import FixedAssetImageService
content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes(
file_url,
max_size=max_size,
)
if content is not None or asset_image_err is not None:
return (content, content_type, asset_image_err)
except Exception as exc:
current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc)
headers = {}
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
@@ -1251,6 +1261,35 @@ def search_asset_history_files():
})
@chat_bp.route('/asset-image/resolve', methods=['GET'])
@require_agent_permission
def resolve_asset_image_preview():
"""
解析固定资产图片预览链接。
用途:聊天结果表格点击“图片 -> 查看”时,后端自动登录外部文档库并返回最佳图片的可预览元数据。
约束:至少提供资产编号或资产名称之一;只返回当前最佳命中的单张图片,不向前端暴露文档库登录态。
"""
asset_id = (request.args.get('asset_id') or '').strip()
asset_name = (request.args.get('asset_name') or '').strip()
if not asset_id and not asset_name:
raise ValidationError('asset_id or asset_name is required')
from app.services.fixed_asset_image import FixedAssetImageService
result = FixedAssetImageService.resolve_images(
asset_id=asset_id,
asset_name=asset_name,
)
return jsonify({
'asset_id': asset_id,
'asset_name': asset_name,
'item': result.get('item'),
'items': result.get('items', []),
'total': result.get('total', 0),
})
@chat_bp.route('/completions', methods=['POST'])
@require_agent_permission
def chat_completions():
+5
View File
@@ -296,6 +296,11 @@ class Config:
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_ASSET_IMAGE_BASE_URL = os.getenv('FIXED_ASSET_IMAGE_BASE_URL', '').strip()
FIXED_ASSET_IMAGE_USERNAME = os.getenv('FIXED_ASSET_IMAGE_USERNAME', '').strip()
FIXED_ASSET_IMAGE_PASSWORD = os.getenv('FIXED_ASSET_IMAGE_PASSWORD', '')
FIXED_ASSET_IMAGE_LIBRARY_ID = os.getenv('FIXED_ASSET_IMAGE_LIBRARY_ID', '').strip()
FIXED_ASSET_IMAGE_FOLDER_ID = os.getenv('FIXED_ASSET_IMAGE_FOLDER_ID', '').strip()
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
str(_ROOT_DIR / 'docs'),
+422
View File
@@ -0,0 +1,422 @@
"""
backend/app/services/fixed_asset_image.py
用途:为固资管理提供“资产图片”检索与预览能力,按资产编号登录外部文档库并定位对应图片附件。
依赖:requests、app.core.config.settings.Config、chat.py 的预览代理会复用这里的已登录会话去抓取图片二进制。
逻辑:聊天表格点击“图片 -> 查看” -> chat API 调用本服务登录文档库并搜索固定资产图片 -> 前端继续走既有 FilePreviewModal 在站内预览。
"""
from __future__ import annotations
import threading
import time
from dataclasses import dataclass
from typing import Any
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
import requests
from flask import current_app, has_app_context
from app.core.config.settings import Config
from app.core.errors import NotFoundError, ServiceUnavailableError
_SESSION_LOCK = threading.Lock()
_SESSION_TTL_SECONDS = 20 * 60.0
_SESSION_CACHE: dict[str, Any] = {
"session": None,
"created_at": 0.0,
}
@dataclass(slots=True)
class AssetImageMatch:
"""固定资产图片最佳命中结果。"""
item_id: str
version_id: str
attachment_id: str
name: str
actual_ext: str
relative_path: str
size_bytes: int
url: str
def to_dict(self) -> dict[str, object]:
return {
"item_id": self.item_id,
"version_id": self.version_id,
"attachment_id": self.attachment_id,
"name": self.name,
"actual_ext": self.actual_ext,
"relative_path": self.relative_path,
"size_bytes": self.size_bytes,
"url": self.url,
}
class FixedAssetImageService:
"""
固资图片检索服务。
AI 触发时机:
- 当聊天结果表格里用户点击“图片 -> 查看”,希望直接预览该资产照片时调用;
- 输入必须至少带资产编号,资产名称仅作为兜底排序辅助;
- 输出返回同资产的全部命中图片(按最佳匹配优先排序),不把文档库账号暴露给前端。
"""
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
@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 _get_base_url(cls) -> str:
raw_value = cls._get_runtime_setting("FIXED_ASSET_IMAGE_BASE_URL").strip()
if not raw_value:
return ""
parsed = urlparse(raw_value)
if parsed.scheme and parsed.netloc:
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
return raw_value.rstrip("/")
@classmethod
def _build_url(cls, path: str) -> str:
return f"{cls._get_base_url()}{path}"
@classmethod
def is_enabled(cls) -> bool:
return all([
cls._get_base_url(),
cls._get_runtime_setting("FIXED_ASSET_IMAGE_USERNAME").strip(),
cls._get_runtime_setting("FIXED_ASSET_IMAGE_PASSWORD"),
cls._get_runtime_setting("FIXED_ASSET_IMAGE_LIBRARY_ID").strip(),
cls._get_runtime_setting("FIXED_ASSET_IMAGE_FOLDER_ID").strip(),
])
@classmethod
def is_managed_asset_image_url(cls, file_url: str) -> bool:
base_url = cls._get_base_url()
if not base_url or not file_url:
return False
base = urlparse(base_url)
target = urlparse(file_url)
return (
target.scheme in ("http", "https")
and target.netloc.lower() == base.netloc.lower()
and (target.path or "").startswith("/Api/_api/DMS/Public/Attachment/Embed")
)
@classmethod
def resolve_images(cls, *, asset_id: str, asset_name: str = "") -> dict[str, object]:
"""
按资产编号解析文档库中的全部命中图片。
[STEP 1] 使用固定资产图片专用账号登录文档库,并缓存会话,避免每次点击都重复登录。
[STEP 2] 进入“文档库 > 总务 > 固定资产”目录按资产编号检索图片文件,仅保留常见图片扩展名。
[STEP 3] 选出全部有效命中并按相关度排序,回填图片 Embed URL,让前端支持单图或多图浏览。
"""
normalized_asset_id = str(asset_id or "").strip()
normalized_asset_name = str(asset_name or "").strip()
if not normalized_asset_id and not normalized_asset_name:
raise NotFoundError("当前资产缺少图片检索所需的编号或名称")
if not cls.is_enabled():
raise ServiceUnavailableError("固定资产图片文档库未配置,请联系管理员处理")
payload = {
"LibraryID": cls._get_runtime_setting("FIXED_ASSET_IMAGE_LIBRARY_ID").strip(),
"ParentFolderID": cls._get_runtime_setting("FIXED_ASSET_IMAGE_FOLDER_ID").strip(),
"Keywords": "",
"Page": {
"Size": 50,
"Index": 1,
},
"Total": 0,
"Recursion": True,
"OrderBy": [],
"FieldQuery": [],
"LeafName": normalized_asset_id or normalized_asset_name,
}
response = cls._request_json("POST", "/Api/_api/APS/Public/Item/Page", json=payload)
data_section = response.get("Data", {}) or {}
rows = (
data_section.get("Rows")
or data_section.get("Items")
or (data_section.get("Page") or {}).get("Items")
or []
)
matches = cls._pick_matches(rows, normalized_asset_id, normalized_asset_name)
if not matches:
display_name = normalized_asset_id or normalized_asset_name
raise NotFoundError(f"未找到资产 {display_name} 对应的图片文件")
primary_match = matches[0]
cls._record_browse(primary_match.item_id, primary_match.version_id)
return {
"item": primary_match.to_dict(),
"items": [match.to_dict() for match in matches],
"total": len(matches),
}
@classmethod
def resolve_image(cls, *, asset_id: str, asset_name: str = "") -> dict[str, object]:
"""兼容旧调用:仍返回最佳命中单图元数据。"""
result = cls.resolve_images(asset_id=asset_id, asset_name=asset_name)
return result["item"]
@classmethod
def fetch_preview_bytes(
cls,
file_url: str,
*,
max_size: int | None = 15 * 1024 * 1024,
) -> tuple[bytes | None, str | None, tuple[str, int] | None]:
"""
使用文档库登录态抓取图片二进制,供 `/preview-file-raw` 复用。
参数约束:仅处理本服务生成的 Embed URL;其余 URL 一律返回 None,让 chat.py 继续走默认拉取逻辑。
"""
if not cls.is_managed_asset_image_url(file_url):
return (None, None, None)
response = cls._request("GET", file_url, stream=True)
if response.status_code == 404:
return (None, None, ("asset image file not found", 404))
if response.status_code >= 400:
return (None, None, (f"asset image upstream returned {response.status_code}", 502))
content_length = response.headers.get("content-length")
if max_size is not None and content_length:
try:
if int(content_length) > max_size:
return (None, None, ("file too large for online preview", 413))
except ValueError:
pass
content = response.content
if max_size is not None and len(content) > max_size:
return (None, None, ("file too large for online preview", 413))
return (content, (response.headers.get("content-type") or "").strip().lower(), None)
@classmethod
def _pick_matches(
cls,
items: list[dict[str, Any]],
asset_id: str,
asset_name: str,
) -> list[AssetImageMatch]:
scored_matches: list[tuple[int, AssetImageMatch]] = []
for item in items:
match = cls._build_match(item, asset_id, asset_name)
if not match:
continue
score = cls._score_item(match.name, asset_id, asset_name, match.relative_path)
scored_matches.append((score, match))
if not scored_matches:
return []
scored_matches.sort(key=lambda pair: (-pair[0], pair[1].name.lower(), pair[1].attachment_id))
deduplicated: list[AssetImageMatch] = []
seen_attachment_ids: set[str] = set()
for _score, match in scored_matches:
if match.attachment_id in seen_attachment_ids:
continue
seen_attachment_ids.add(match.attachment_id)
deduplicated.append(match)
return deduplicated
@classmethod
def _build_match(
cls,
item: dict[str, Any],
asset_id: str,
asset_name: str,
) -> AssetImageMatch | None:
main_attachment = item.get("MainFileAttachment") or {}
extension = str(main_attachment.get("Extension") or "").strip().lower()
if extension not in cls.IMAGE_EXTENSIONS:
return None
attachment_id = str(main_attachment.get("ID") or "").strip()
item_id = str(item.get("ID") or "").strip()
version_id = str(item.get("VersionID") or "").strip()
if not attachment_id or not item_id or not version_id:
return None
raw_name = str(item.get("LeafName") or "").strip().rstrip(".")
normalized_name = cls._normalize_match_text(raw_name)
normalized_asset_id = cls._normalize_match_text(asset_id)
if normalized_asset_id and normalized_asset_id not in normalized_name:
return None
file_name = f"{raw_name or attachment_id}{extension}"
return AssetImageMatch(
item_id=item_id,
version_id=version_id,
attachment_id=attachment_id,
name=file_name,
actual_ext=extension.lstrip("."),
relative_path=str(item.get("Path") or "").strip(),
size_bytes=int(main_attachment.get("FileSize") or 0),
url=cls._build_embed_url(attachment_id),
)
@classmethod
def _score_item(cls, file_name: str, asset_id: str, asset_name: str, relative_path: str) -> int:
normalized_file_name = cls._normalize_match_text(file_name)
normalized_asset_id = cls._normalize_match_text(asset_id)
normalized_asset_name = cls._normalize_match_text(asset_name)
normalized_path = cls._normalize_match_text(relative_path)
score = 0
if normalized_asset_id:
if normalized_file_name == normalized_asset_id:
score += 200
elif normalized_file_name.startswith(normalized_asset_id):
score += 150
elif normalized_asset_id in normalized_file_name:
score += 120
elif normalized_asset_id in normalized_path:
score += 80
if normalized_asset_name:
if normalized_asset_name in normalized_file_name:
score += 60
elif normalized_asset_name in normalized_path:
score += 30
if file_name.lower().endswith(".jpg"):
score += 20
return score
@classmethod
def _build_embed_url(cls, attachment_id: str) -> str:
parsed = urlparse(cls._build_url("/Api/_api/DMS/Public/Attachment/Embed"))
query = parse_qs(parsed.query, keep_blank_values=True)
query["attachmentID"] = [attachment_id]
return urlunparse(parsed._replace(query=urlencode(query, doseq=True)))
@classmethod
def _normalize_match_text(cls, value: str) -> str:
return str(value or "").strip().lower().replace(" ", "").replace(".", "")
@classmethod
def _record_browse(cls, item_id: str, version_id: str) -> None:
"""
记录外部文档库浏览行为。
用途:与外部系统正常用户操作保持一致;失败不阻断图片预览主链路。
"""
if not item_id or not version_id:
return
try:
cls._request_json(
"POST",
"/Api/_api/DMS/Public/Item/AddItemBrowse",
json={
"ItemID": item_id,
"VersionID": version_id,
"AttachmentType": 1,
},
)
except Exception as exc:
if has_app_context():
current_app.logger.warning("[fixed-asset-image] failed to record browse item_id=%s err=%s", item_id, exc)
@classmethod
def _request_json(
cls,
method: str,
url_or_path: str,
*,
json: dict[str, Any] | None = None,
timeout: int = 20,
) -> dict[str, Any]:
try:
response = cls._request(method, url_or_path, json=json, timeout=timeout)
response.raise_for_status()
payload = response.json()
except requests.RequestException as exc:
raise ServiceUnavailableError(f"固定资产图片文档库请求失败:{exc}") from exc
if int(payload.get("Code") or 0) != 0:
raise ServiceUnavailableError(payload.get("Msg") or "固定资产图片文档库返回异常")
return payload
@classmethod
def _request(
cls,
method: str,
url_or_path: str,
*,
json: dict[str, Any] | None = None,
timeout: int = 20,
stream: bool = False,
) -> requests.Response:
target_url = url_or_path if url_or_path.startswith("http") else cls._build_url(url_or_path)
session = cls._get_logged_session()
response = session.request(
method.upper(),
target_url,
json=json,
timeout=timeout,
stream=stream,
allow_redirects=True,
)
if cls._looks_like_login_response(response):
session = cls._get_logged_session(force_refresh=True)
response = session.request(
method.upper(),
target_url,
json=json,
timeout=timeout,
stream=stream,
allow_redirects=True,
)
return response
@classmethod
def _looks_like_login_response(cls, response: requests.Response) -> bool:
final_url = (response.url or "").lower()
content_type = (response.headers.get("content-type") or "").lower()
return (
response.status_code in (401, 403)
or "/login" in final_url
or ("text/html" in content_type and "login" in final_url)
)
@classmethod
def _get_logged_session(cls, *, force_refresh: bool = False) -> requests.Session:
with _SESSION_LOCK:
current_session = _SESSION_CACHE.get("session")
created_at = float(_SESSION_CACHE.get("created_at") or 0.0)
if (
not force_refresh
and isinstance(current_session, requests.Session)
and time.time() - created_at < _SESSION_TTL_SECONDS
):
return current_session
session = requests.Session()
try:
login_response = session.post(
cls._build_url("/Login/_api/Login"),
json={
"LoginName": cls._get_runtime_setting("FIXED_ASSET_IMAGE_USERNAME").strip(),
"Pwd": cls._get_runtime_setting("FIXED_ASSET_IMAGE_PASSWORD"),
},
headers={
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json, text/plain, */*",
},
timeout=20,
)
login_response.raise_for_status()
payload = login_response.json()
except requests.RequestException as exc:
raise ServiceUnavailableError(f"固定资产图片文档库登录失败:{exc}") from exc
if int(payload.get("Code") or 0) != 0:
raise ServiceUnavailableError(payload.get("Msg") or "固定资产图片文档库登录失败")
_SESSION_CACHE["session"] = session
_SESSION_CACHE["created_at"] = time.time()
return session
+50 -3
View File
@@ -34,6 +34,19 @@ class FixedAssetsSnapshotService:
SNAPSHOT_SQL_MARKER = "SNAPSHOT://FIXED_ASSETS"
SNAPSHOT_KIND = "fixed_assets_snapshot_preview"
PREVIEW_COLUMNS = (
"序号",
"资产编号",
"资产名称",
"保管人",
"保管部门",
"图片",
"账套",
"供应商",
"资产状态",
"数量",
"取得时间",
)
VISIBLE_COLUMNS = (
"资产编号",
@@ -126,6 +139,33 @@ class FixedAssetsSnapshotService:
return ""
return str(value).strip()
@classmethod
def _build_preview_row(
cls,
row_map: dict[str, Any],
*,
row_number: int,
) -> tuple[Any, ...]:
"""
用途:把固资快照原始查询结果收敛成聊天/预览统一使用的展示行。
核心逻辑:按前端固定列顺序输出,并补充“序号”和“图片=查看”两个展示列。
参数约束:row_map 必须包含资产编号等基础字段;当资产编号为空时,“图片”列保持为空,避免误导用户点击。
"""
asset_no = cls._stringify(row_map.get("资产编号"))
return (
row_number,
asset_no,
cls._stringify(row_map.get("资产名称")),
cls._stringify(row_map.get("保管人姓名")),
cls._stringify(row_map.get("保管部门名称")),
"查看" if asset_no else "",
cls._stringify(row_map.get("账套")),
cls._stringify(row_map.get("供应厂商")),
cls._stringify(row_map.get("资产状态")),
cls._stringify(row_map.get("数量")),
cls._stringify(row_map.get("取得日期")),
)
@classmethod
def _normalize_search_text(cls, text: str) -> str:
cleaned = str(text or "").upper()
@@ -871,9 +911,16 @@ SELECT COUNT(*) FROM {result_source_name} WHERE {where_sql}
cursor.execute(count_sql, params)
total_count = int(cursor.fetchone()[0] or 0)
cursor.execute(list_sql, [*params, max(1, int(limit)), max(0, int(offset))])
columns = [str(item[0] or "").strip() for item in cursor.description]
rows = [tuple(row) for row in cursor.fetchall()]
return columns, rows, total_count
raw_columns = [str(item[0] or "").strip() for item in cursor.description]
raw_rows = [tuple(row) for row in cursor.fetchall()]
rows = []
for index, row in enumerate(raw_rows, start=max(0, int(offset)) + 1):
row_map = {
raw_columns[column_index]: row[column_index]
for column_index in range(min(len(raw_columns), len(row)))
}
rows.append(cls._build_preview_row(row_map, row_number=index))
return list(cls.PREVIEW_COLUMNS), rows, total_count
finally:
conn.close()
+25 -18
View File
@@ -22,6 +22,7 @@ class Text2SQLService:
"ERP_FAF_FILE_V",
)
_ASSET_COLUMN_LABELS = {
"ID": "序号",
"ASSET_NO": "资产编号",
"ASSET_NAME": "资产名称",
"SPECIFICATION": "规格型号",
@@ -29,23 +30,26 @@ class Text2SQLService:
"UNIT_PRICE": "本币单价",
"QUANTITY": "数量",
"UNIT": "计量单位",
"ACQUISITION_DATE": "取得日期",
"ACQUISITION_DATE": "取得时间",
"ACCOUNTING_DATE": "入账日期",
"ASSET_STATUS": "资产状态",
"ASSET_TYPE": "资产类型",
"ASSET_SUBTYPE": "资产次类型",
"ASSET_SUB_TYPE": "资产次类型",
"CUSTODIAN": "保管人姓名",
"CUSTODIAN": "保管人",
"CUSTODIAN_ID": "保管人工号",
"CUSTODIAN_NAME": "保管人姓名",
"DEPARTMENT": "保管部门名称",
"DEPARTMENT_NAME": "保管部门名称",
"CUSTODIAN_NAME": "保管人",
"DEPARTMENT": "保管部门",
"DEPARTMENT_NAME": "保管部门",
"LOCATION": "存放位置名称",
"LOCATION_NAME": "存放位置名称",
"SITE": "营运中心代码",
"SITE_DESC": "营运中心名称",
"OPERATING_CENTER_CODE": "账套",
"PMC03": "供应厂商",
"PMC03": "供应商",
"VENDOR_NAME": "供应商",
"IMAGE": "图片",
"PICTURE": "图片",
"FAJ01": "序号",
"FAJ02": "资产编号",
"FAJ021": "类型",
@@ -63,11 +67,11 @@ class Text2SQLService:
"FAJ14": "本币成本",
"FAJ17": "数量",
"FAJ18": "计量单位",
"FAJ19": "保管人姓名",
"FAJ20": "保管部门名称",
"FAJ19": "保管人",
"FAJ20": "保管部门",
"FAJ21": "存放位置名称",
"FAJ22": "账套",
"FAJ25": "取得日期",
"FAJ25": "取得时间",
"FAJ26": "入账日期",
"FAJ31": "预留残值",
"FAJ43": "资产状态",
@@ -79,21 +83,23 @@ class Text2SQLService:
"GEM02": "部门名称",
}
_ASSET_DISPLAY_COLUMN_ORDER = (
"序号",
"资产编号",
"资产名称",
"规格型号",
"保管人",
"保管部门",
"图片",
"账套",
"保管人姓名",
"保管部门名称",
"存放位置名称",
"供应商",
"资产状态",
"数量",
"取得时间",
"规格型号",
"存放位置名称",
"预留残值",
"供应厂商",
"资产性质",
"本币单价",
"数量",
"计量单位",
"取得日期",
"入账日期",
)
_ASSET_VALUE_MAPPINGS = {
@@ -125,9 +131,10 @@ class Text2SQLService:
},
}
_ASSET_FALLBACK_NAME_COLUMNS = {
"保管人": ("保管人姓名", "员工姓名"),
"保管人": ("保管人", "保管人姓名", "员工姓名"),
"保管人工号": ("保管人姓名", "员工姓名"),
"保管部门": ("保管部门名称", "部门名称"),
"保管部门": ("保管部门", "保管部门名称", "部门名称"),
"供应商": ("供应商", "供应厂商"),
"存放位置": ("存放位置名称",),
"资产类型": ("资产类型名称", "类型名称"),
}
+8 -7
View File
@@ -87,12 +87,13 @@ def test_query_assets_supports_name_and_spec_combo(app, tmp_path):
columns, rows, total = FixedAssetsSnapshotService.query_assets("查询线切割机 规格型号 DK7732")
# 断言:组合查询应命中同一台设备,且返回预期中文列头。
assert columns[:3] == ["资产编号", "资产名称", "规格型号"]
# 断言:组合查询应命中同一台设备,且返回新的固定资产预览列顺序。
assert columns[:6] == ["序号", "资产编号", "资产名称", "保管人", "保管部门", "图片"]
assert total == 1
assert rows[0][0] == "A0827011"
assert rows[0][1] == "线切割机"
assert rows[0][2] == "DK7732"
assert rows[0][0] == 1
assert rows[0][1] == "A0827011"
assert rows[0][2] == "线切割机"
assert rows[0][5] == "查看"
def test_query_assets_supports_self_scope(app, tmp_path):
@@ -106,8 +107,8 @@ def test_query_assets_supports_self_scope(app, tmp_path):
)
# 断言:本人查询必须按当前用户身份过滤,不能返回其他人的资产。
assert columns[0] == "资产编号"
assert columns[0] == "序号"
assert total == 1
assert len(rows) == 1
assert rows[0][0] == "A0827011"
assert rows[0][1] == "A0827011"
assert rows[0][3] == "张三"
@@ -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"