Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/agent_runtime_context/dify_inputs.py
#	backend/app/services/maintenance_chat_service.py
This commit is contained in:
hugo committed 2026-07-07 13:25:16 +08:00
commit fc694a8f43
55 files changed
+2107 -192

No files matched your search

+1 -1
View File
@@ -112,4 +112,4 @@ SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# FREIGHT_RPA_SAMPLE_INVENTORY=
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=xxxx
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+1 -1
View File
@@ -63,4 +63,4 @@ HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=xxxx
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+12
View File
@@ -129,6 +129,18 @@ SRM_SQLSERVER_TIMEOUT=10
ERP_DB_DSN=192.168.8.24:1521/topprod
TEXT2SQL_SCHEMA_PATH=
# 固资履历共享盘
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# 固资图片文档库
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
FIXED_ASSET_IMAGE_USERNAME=26040006
FIXED_ASSET_IMAGE_PASSWORD=26040006
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
+1 -1
View File
@@ -117,4 +117,4 @@ SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=xxxx
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+41
View File
@@ -316,6 +316,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()
@@ -1247,6 +1257,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():
@@ -1308,6 +1347,7 @@ def chat_completions():
username=getattr(user, 'username', None),
employee_id=getattr(user, 'employee_id', None),
real_name=getattr(user, 'real_name', None),
role=getattr(user, 'role', None),
)
from app.services.dify import DifyService
@@ -1429,6 +1469,7 @@ def chat_completions():
session_id=session.session_id,
request_id=request_id,
trigger_source="frontend_chat",
user_role=user_proxy.role,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
+5 -5
View File
@@ -46,15 +46,15 @@ def _require_user():
def _require_ledger_admin():
"""
校验设备台账管理权限。
校验设备维保管理权限。
Returns:
当前用户对象。
Raises:
ForbiddenError: 当前角色不允许写入台账。
ForbiddenError: 当前角色不允许写入台账或维修记录。
"""
user = _require_user()
if getattr(user, 'role', None) not in {'admin', 'asset_admin', 'maintenance_manager'}:
raise ForbiddenError('Maintenance ledger admin privilege required')
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
raise ForbiddenError('Maintenance manager privilege required')
return user
@@ -141,7 +141,7 @@ def get_maintenance_record(record_id: int):
@maintenance_bp.route('/records/export', methods=['GET'])
def export_maintenance_records():
"""按当前筛选条件导出设备维修记录 Excel。"""
_require_user()
_require_ledger_admin()
data = build_records_export(
keyword=request.args.get('keyword'),
device_code=request.args.get('device_code') or request.args.get('deviceCode'),
+8
View File
@@ -127,6 +127,9 @@ class Config:
# 文件检核 Chatflow Tool API
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
# 设备维保助手 Chatflow Tool API
MAINTENANCE_TOOL_API_KEY = os.getenv('MAINTENANCE_TOOL_API_KEY')
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
@@ -293,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'),
@@ -42,6 +42,7 @@ def build_agent_registry_schema() -> dict[str, Any]:
**item,
'required_fields': list(entry.get('required_fields') or []),
'forced_capabilities': dict(entry.get('forced_capabilities') or {}),
'default_intent_routes': list(entry.get('default_intent_routes') or []),
})
return {
@@ -38,6 +38,7 @@ agent_types:
label: 通用问答 / 知识库
conversation_mode_default: chat
runtime_provider_default: dify
default_intent_routes: []
models: []
required_fields: []
forced_capabilities: {}
@@ -17,6 +17,77 @@ from app.services.agent_runtime_context.builder import (
)
from app.services.agent_runtime_context.registry import register_context_adapter
TRAINING_AGENT_NAME_PATTERN = ('培训', '考试', '入职')
def _agent_extra_config(agent) -> dict[str, Any]:
"""读取 Agent.extra_config;非字典时回退为空,避免脏配置导致培训识别异常。"""
extra_config = getattr(agent, 'extra_config', None)
return extra_config if isinstance(extra_config, dict) else {}
def _agent_handler_config(agent) -> dict[str, Any]:
"""读取 Agent.handler_config;非字典时回退为空。"""
handler_config = getattr(agent, 'handler_config', None)
return handler_config if isinstance(handler_config, dict) else {}
def is_training_chat_agent(agent) -> bool:
"""
判断当前 Agent 是否启用培训工作区语义。
核心逻辑:优先 handler_config.content_profile=training 与 extra_config 显式开关;
未配置时再回退 Agent 名称关键字,避免普通 Agent 被误注入培训专用字段。
Args:
agent: 当前对话 Agent 记录或代理对象。
Returns:
命中培训 Agent 返回 True,否则返回 False。
"""
if _agent_handler_config(agent).get('content_profile') == 'training':
return True
extra_config = _agent_extra_config(agent)
if extra_config.get('training_workspace_enabled') in (False, 'false'):
return False
explicit_flags = (
extra_config.get('training_workspace_enabled'),
extra_config.get('training_mode'),
extra_config.get('training_agent'),
)
if any(value in (True, 'true') for value in explicit_flags):
return True
name = str(getattr(agent, 'name', None) or '').strip()
return any(keyword in name for keyword in TRAINING_AGENT_NAME_PATTERN)
def _append_training_role_input(
base_inputs: dict[str, Any],
*,
agent,
user_role: str | None = None,
) -> dict[str, Any]:
"""
为培训 Agent 追加 Dify 顶层 role 输入。
核心逻辑:仅当命中培训 Agent 且当前用户角色非空时,基于现有 inputs 复制后追加 `role`。
Args:
base_inputs: 已构建好的 Dify inputs。
agent: 当前对话 Agent。
user_role: 后端鉴权后的真实账号角色,来源于 users.role。
Returns:
若符合条件则包含 `role`,否则原样返回。
"""
normalized_role = str(user_role or '').strip()
if not base_inputs or not normalized_role or not is_training_chat_agent(agent):
return base_inputs
return {
**base_inputs,
'role': normalized_role,
}
def resolve_agent_code(agent) -> str:
"""
@@ -123,13 +194,15 @@ def build_generic_context_adapter(
request_id: str | None = None,
trigger_source: str | None = 'frontend_chat',
locale: str | None = None,
user_role: str | None = None,
**kwargs: Any,
) -> dict[str, str]:
) -> dict[str, Any]:
"""通用 Context Adapter 入口,供 CONTEXT_ADAPTER_REGISTRY 分发。"""
return build_generic_dify_inputs(
inputs = build_generic_dify_inputs(
session_id=session_id,
agent=agent,
request_id=request_id,
trigger_source=trigger_source,
locale=locale,
)
return _append_training_role_input(inputs, agent=agent, user_role=user_role)
@@ -18,7 +18,7 @@ from app.services.chat.intent_route_registry import (
def _match(ctx: ChatIntentRouteContext) -> bool:
from app.services.maintenance_chat_service import MaintenanceChatService
return MaintenanceChatService.supports(ctx.query, ctx.agent)
return MaintenanceChatService.can_attempt(ctx.query, ctx.agent, session_id=ctx.session_id)
def _stream(ctx: ChatIntentRouteContext):
+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()
+350 -15
View File
@@ -1,9 +1,9 @@
"""
backend/app/services/maintenance_chat_service.py
用途:设备维保助手的会话查询直答服务,用于把设备编号/名称查询转换成设备台账卡片。
依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、SQLAlchemy、SSE JSON 输出。
逻辑:chat.py 在设备维保助手命中查询意图时调用本服务;本服务查询台账和维修记录,写入聊天历史并返回结构化消息。
用途:设备维保助手的会话查询直答服务,用于把设备编号/名称或上下文指代转换成设备台账卡片。
依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、agent_registry.resolver、SQLAlchemy、SSE JSON 输出。
逻辑:chat intent_routes/maintenance_chat 与 try_stream_chat 调用本服务;Agent 门控读 handler_config.intent_routes。
"""
from __future__ import annotations
@@ -21,6 +21,26 @@ from app.models import ChatLog, MaintenanceDevice, MaintenanceRecord
from app.services.maintenance_ledger_service import serialize_device
from app.services.maintenance_record_service import REPAIR_STATUS_LABELS, serialize_record
MAINTENANCE_INTENT_ROUTE = 'maintenance_chat'
MAINTENANCE_MESSAGE_TYPE = 'maintenance-device-result'
REFERENCE_DEVICE_PATTERN = re.compile(r'(这个设备|這個設備|这台|這台|该设备|該設備|它|刚才那个|剛才那個|上一个设备|上一個設備|当前设备|當前設備)')
def _agent_has_maintenance_chat_route(agent: Any) -> bool:
"""
判断当前 Agent 是否声明 maintenance_chat Intent 快路径。
核心逻辑:只读 handler_config.intent_routes,不再根据 Agent 名称硬编码推断。
Args:
agent: Agent ORM 或代理对象。
Returns:
已配置 maintenance_chat route 时返回 True。
"""
from app.services.agent_registry.resolver import agent_has_intent_route
return agent_has_intent_route(agent, MAINTENANCE_INTENT_ROUTE)
def _clean_text(value: Any) -> str:
return str(value or '').strip()
@@ -38,18 +58,18 @@ def extract_device_query_keyword(query: str) -> str | None:
text = _clean_text(query)
if not text:
return None
if not re.search(r'(设备|台账|台帳|维保|維保|维修|維修|保养|保養|查询|查詢|查看|检索)', text):
if not re.search(r'(设备|台账|台帳|维保|維保|维修|維修|保养|保養|查询|查詢|查看|检索|查)', text):
return None
code_match = re.search(r'\b[A-Za-z]{1,6}\d{4,}[A-Za-z0-9_-]*\b', text)
code_match = re.search(r'(?<![A-Za-z0-9_-])([A-Za-z]{1,6}\d{4,}[A-Za-z0-9_-]*)', text)
if code_match:
return code_match.group(0).strip()
digit_match = re.search(r'\b\d{6,}\b', text)
return code_match.group(1).strip()
digit_match = re.search(r'(?<![A-Za-z0-9_-])(\d{6,})(?![A-Za-z0-9_-])', text)
if digit_match:
return digit_match.group(0).strip()
return digit_match.group(1).strip()
cleaned = re.sub(
r'(查询|查詢|查看|检索|一下|这条|這條|这个|這個|设备|設備|台账|台帳|信息|資料|维保|維保|维修|維修|记录|記錄|历史|歷史|的|了|请|請|帮我|幫我)',
r'(查询|查詢|查看|检索|查|一下|这条|這條|这个|這個|设备|設備|台账|台帳|信息|資料|维保|維保|维修|維修|记录|記錄|历史|歷史|的|了|请|請|帮我|幫我)',
' ',
text,
)
@@ -57,6 +77,93 @@ def extract_device_query_keyword(query: str) -> str | None:
return cleaned[:80] or None
def _looks_like_context_reference(query: str) -> bool:
"""
判断用户本轮问题是否在指代上一轮设备。
AI 触发时机:当用户追问“这个设备/这台/它的维修记录”时,用它把本轮问题接到最近命中的设备上下文。
Args:
query: 用户原始问题。
Returns:
True 表示问题包含设备指代词,适合尝试读取会话中的最近设备。
"""
return bool(REFERENCE_DEVICE_PATTERN.search(_clean_text(query)))
def _extract_device_code_from_payload(payload: Any) -> str | None:
"""
从维保卡片 payload 中提取设备编号。
Args:
payload: ChatLog.payload,通常来自 maintenance-device-result。
Returns:
设备编号;没有可用设备信息时返回 None。
"""
if not isinstance(payload, dict):
return None
device = payload.get('device')
if not isinstance(device, dict):
return None
code = _clean_text(device.get('deviceCode') or device.get('device_code'))
return code or None
def _find_recent_context_device_code(session_id: str | None, agent: Any) -> str | None:
"""
从同一会话最近的维保结果中恢复当前设备编号。
Args:
session_id: 本地 ChatSession.session_id。
agent: 当前 Agent,用于限制只读取同一助手的上下文。
Returns:
最近一次命中的设备编号;没有上下文时返回 None。
"""
session_key = _clean_text(session_id)
if not session_key:
return None
rows = (
db.session.query(ChatLog)
.filter(
ChatLog.session_id == session_key,
ChatLog.agent_id == getattr(agent, 'id', None),
ChatLog.message_type == MAINTENANCE_MESSAGE_TYPE,
)
.order_by(ChatLog.created_at.desc(), ChatLog.id.desc())
.limit(10)
.all()
)
for row in rows:
code = _extract_device_code_from_payload(row.payload)
if code:
current_app.logger.info(
'[maintenance-chat] context device resolved session_id=%s chat_log_id=%s device_code=%s',
session_key,
row.id,
code,
)
return code
current_app.logger.info('[maintenance-chat] context device missed session_id=%s', session_key)
return None
def resolve_device_query_keyword(query: str, agent: Any, *, session_id: str | None = None) -> tuple[str | None, str]:
"""
解析本轮维保查询关键词,优先使用显式编号,其次处理“这个设备”等上下文指代。
AI 触发时机:chat.py 分流前调用,用于判断本地维保服务是否能明确回答。
Args:
query: 用户原始问题。
agent: 当前 Agent。
session_id: 本地会话 ID,用于读取最近设备上下文。
Returns:
(keyword, source):source 为 explicit/context/none。
"""
if not _agent_has_maintenance_chat_route(agent):
return None, 'none'
if _looks_like_context_reference(query):
context_code = _find_recent_context_device_code(session_id, agent)
if context_code:
return context_code, 'context'
keyword = extract_device_query_keyword(query)
return (keyword, 'explicit') if keyword else (None, 'none')
def _find_device(keyword: str) -> MaintenanceDevice | None:
"""按设备编号优先,其次按设备名称模糊匹配查找单台设备。"""
value = _clean_text(keyword)
@@ -64,14 +171,109 @@ def _find_device(keyword: str) -> MaintenanceDevice | None:
return None
exact = db.session.query(MaintenanceDevice).filter(MaintenanceDevice.device_code == value).first()
if exact:
current_app.logger.info('[maintenance-chat] device exact matched keyword=%s device_id=%s device_code=%s', value, exact.id, exact.device_code)
return exact
like = f'%{value}%'
return (
device = (
db.session.query(MaintenanceDevice)
.filter(or_(MaintenanceDevice.device_code.ilike(like), MaintenanceDevice.device_name.ilike(like)))
.order_by(MaintenanceDevice.updated_at.desc(), MaintenanceDevice.id.desc())
.first()
)
current_app.logger.info(
'[maintenance-chat] device fuzzy result keyword=%s matched=%s device_id=%s device_code=%s',
value,
bool(device),
getattr(device, 'id', None),
getattr(device, 'device_code', None),
)
return device
def _find_records(keyword: str, *, record_limit: int = 5) -> list[MaintenanceRecord]:
"""
按设备编号或设备名称查询维修记录。
AI 触发时机:本地会话直答未匹配台账时,用维修记录兜底,避免导入履历后问不到记录。
Args:
keyword: 从用户问题中提取出的设备编号或名称。
record_limit: 最大返回条数。
Returns:
按报修日期倒序排列的维修记录列表。
"""
value = _clean_text(keyword)
if not value:
return []
record_limit = max(1, min(20, int(record_limit or 5)))
query = db.session.query(MaintenanceRecord)
exact_rows = (
query.filter(MaintenanceRecord.device_code == value)
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
.limit(record_limit)
.all()
)
if exact_rows:
current_app.logger.info('[maintenance-chat] records exact matched keyword=%s count=%s', value, len(exact_rows))
return exact_rows
like = f'%{value}%'
rows = (
query.filter(or_(MaintenanceRecord.device_code.ilike(like), MaintenanceRecord.device_name.ilike(like)))
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
.limit(record_limit)
.all()
)
current_app.logger.info('[maintenance-chat] records fuzzy result keyword=%s count=%s', value, len(rows))
return rows
def _build_record_device_snapshot(record: MaintenanceRecord) -> dict[str, Any]:
"""把维修记录中的设备快照转成前端台账卡片可展示的设备结构。"""
return {
'id': record.device_id or 0,
'deviceCode': record.device_code,
'deviceName': record.device_name,
'modelSpec': record.model_spec,
'department': None,
'installLocation': record.install_location,
'deviceStatus': None,
'manufacturer': None,
'entryDate': None,
'productionDate': None,
'startDate': None,
'responsibleUser': None,
'maintenanceCycle': None,
'originalValue': None,
'residualValue': None,
'accountSet': None,
'remark': '仅来自维修记录快照,未匹配到设备台账',
'createdAt': None,
'updatedAt': None,
}
def _build_records_payload(keyword: str, records: list[MaintenanceRecord]) -> dict[str, Any]:
"""构建仅命中维修记录时的会话 payload。"""
serialized_records = [serialize_record(item) for item in records]
status_counts: dict[str, int] = {}
for item in serialized_records:
key = str(item.get('repairStatus') or '')
status_counts[key] = status_counts.get(key, 0) + 1
return {
'source': 'maintenance_record_query',
'matched': True,
'keyword': keyword,
'device': _build_record_device_snapshot(records[0]) if records else None,
'records': serialized_records,
'summary': {
'recentRecordCount': len(serialized_records),
'statusCounts': status_counts,
'statusLabels': REPAIR_STATUS_LABELS,
'ledgerMatched': False,
},
'actions': [
{'id': 'viewMaintenanceHistory', 'label': '查维修历史'},
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
],
}
def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, record_limit: int = 5) -> dict[str, Any]:
@@ -116,8 +318,19 @@ def build_device_query_result(keyword: str, *, include_records: bool = True, rec
Returns:
设备查询结果 payload。
"""
current_app.logger.info(
'[maintenance-chat] build query keyword=%s include_records=%s record_limit=%s',
keyword,
include_records,
record_limit,
)
device = _find_device(keyword)
if not device:
records = _find_records(keyword, record_limit=record_limit) if include_records else []
if records:
current_app.logger.info('[maintenance-chat] fallback to records keyword=%s count=%s', keyword, len(records))
return _build_records_payload(keyword, records)
current_app.logger.info('[maintenance-chat] no device or records matched keyword=%s', keyword)
return {
'source': 'maintenance_device_query',
'matched': False,
@@ -139,7 +352,39 @@ def supports(query: str, agent: Any) -> bool:
True 表示命中设备查询意图。
"""
_ = agent
return bool(extract_device_query_keyword(query))
keyword = extract_device_query_keyword(query)
supported = bool(keyword)
current_app.logger.info(
'[maintenance-chat] support decision keyword=%s supported=%s query=%s',
keyword,
supported,
query,
)
return supported
def can_attempt(query: str, agent: Any, *, session_id: str | None = None) -> bool:
"""
判断本地维保服务是否具备明确查询关键词,可尝试直答。
Args:
query: 用户原始问题。
agent: 当前 Agent。
session_id: 本地会话 ID;用于支持“这个设备”等指代追问。
Returns:
True 表示已有显式关键词或上下文设备,可以先查本地库。
"""
keyword, source = resolve_device_query_keyword(query, agent, session_id=session_id)
supported = bool(keyword)
current_app.logger.info(
'[maintenance-chat] attempt decision agent_id=%s agent_name=%s keyword=%s source=%s supported=%s query=%s',
getattr(agent, 'id', None),
getattr(agent, 'name', None),
keyword,
source,
supported,
query,
)
return supported
def stream_chat(
@@ -148,6 +393,10 @@ def stream_chat(
agent: Any,
conversation_id: str | None = None,
session_id: str | None = None,
request_id: str | None = None,
keyword: str | None = None,
keyword_source: str = 'explicit',
result: dict[str, Any] | None = None,
) -> Iterator[str]:
"""
以 SSE 返回设备查询结果,并写入 ChatLog 供历史会话回放。
@@ -157,23 +406,53 @@ def stream_chat(
agent: 当前 Agent 代理对象。
conversation_id: 外部会话 ID,设备本地查询会沿用本地 session。
session_id: 本地会话 ID。
keyword: 已解析的设备编号或名称;为空时在函数内重新解析。
keyword_source: 关键词来源,explicit 表示本轮明示,context 表示来自上一轮设备。
result: 已查询好的本地结果;为空时在函数内查询。
Yields:
SSE data 帧。
"""
start_time = time.time()
final_conversation_id = conversation_id or session_id or f'maintenance_{int(time.time())}'
keyword = extract_device_query_keyword(query) or ''
result = build_device_query_result(keyword, include_records=True, record_limit=5)
if keyword is None:
keyword, keyword_source = resolve_device_query_keyword(query, agent, session_id=session_id)
keyword = keyword or ''
current_app.logger.info(
'[maintenance-chat] stream start request_id=%s user_id=%s agent_id=%s session_id=%s conversation_id=%s keyword=%s keyword_source=%s query=%s',
request_id,
getattr(user, 'id', None),
getattr(agent, 'id', None),
session_id,
final_conversation_id,
keyword,
keyword_source,
query,
)
result = result or build_device_query_result(keyword, include_records=True, record_limit=5)
if result.get('matched'):
content = '已查询设备台账信息,下面是匹配结果。'
if result.get('source') == 'maintenance_record_query':
content = '已查询设备维修记录,下面是匹配结果。'
if keyword_source == 'context':
content = f'已按上一轮设备({keyword})查询,下面是匹配结果。'
payload = result
message_type = 'maintenance-device-result'
message_type = MAINTENANCE_MESSAGE_TYPE
else:
content = f'未找到与“{keyword or query}”匹配的设备台账信息,请检查设备编号或设备名称。'
payload = result
message_type = 'text'
current_app.logger.info(
'[maintenance-chat] stream result request_id=%s source=%s matched=%s message_type=%s records=%s device_code=%s',
request_id,
result.get('source'),
result.get('matched'),
message_type,
len(result.get('records') or []),
(result.get('device') or {}).get('deviceCode') if isinstance(result.get('device'), dict) else None,
)
yield f"data: {json.dumps({'event': 'message', 'answer': content}, ensure_ascii=False)}\n\n"
chat_log_id = None
@@ -206,12 +485,68 @@ def stream_chat(
'message_payload': payload,
'chat_log_id': chat_log_id,
'conversation_id': final_conversation_id,
'metadata': {'source': 'maintenance_device_query'},
'metadata': {'source': 'maintenance_device_query', 'keyword_source': keyword_source},
}, ensure_ascii=False)}\n\n"
def try_stream_chat(
query: str,
user: Any,
agent: Any,
conversation_id: str | None = None,
session_id: str | None = None,
request_id: str | None = None,
) -> Iterator[str] | None:
"""
尝试用本地维保库回答;无法明确命中时返回 None 交给 Dify。
AI 触发时机:chat.py 分流时优先调用;只有设备台账或维修记录真实命中时才拦截 Dify。
Args:
query: 用户原始问题。
user: 当前用户代理对象。
agent: 当前 Agent 代理对象。
conversation_id: 外部 Dify 会话 ID。
session_id: 本地会话 ID。
request_id: 当前请求 ID,用于日志串联。
Returns:
SSE 生成器;返回 None 表示本地无法处理,应继续走 Dify。
"""
keyword, keyword_source = resolve_device_query_keyword(query, agent, session_id=session_id)
if not keyword:
current_app.logger.info(
'[maintenance-chat] bypass local no keyword request_id=%s agent_id=%s session_id=%s query=%s',
request_id,
getattr(agent, 'id', None),
session_id,
query,
)
return None
result = build_device_query_result(keyword, include_records=True, record_limit=5)
if not result.get('matched'):
current_app.logger.info(
'[maintenance-chat] bypass local unmatched request_id=%s keyword=%s keyword_source=%s query=%s',
request_id,
keyword,
keyword_source,
query,
)
return None
return stream_chat(
query,
user,
agent,
conversation_id,
session_id=session_id,
request_id=request_id,
keyword=keyword,
keyword_source=keyword_source,
result=result,
)
class MaintenanceChatService:
"""设备维保助手会话查询服务门面,供 chat.py 按统一 Service 风格调用。"""
supports = staticmethod(supports)
can_attempt = staticmethod(can_attempt)
stream_chat = staticmethod(stream_chat)
try_stream_chat = staticmethod(try_stream_chat)
+25 -18
View File
@@ -21,6 +21,7 @@ class Text2SQLService:
"ERP_FAF_FILE_V",
)
_ASSET_COLUMN_LABELS = {
"ID": "序号",
"ASSET_NO": "资产编号",
"ASSET_NAME": "资产名称",
"SPECIFICATION": "规格型号",
@@ -28,23 +29,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": "类型",
@@ -62,11 +66,11 @@ class Text2SQLService:
"FAJ14": "本币成本",
"FAJ17": "数量",
"FAJ18": "计量单位",
"FAJ19": "保管人姓名",
"FAJ20": "保管部门名称",
"FAJ19": "保管人",
"FAJ20": "保管部门",
"FAJ21": "存放位置名称",
"FAJ22": "账套",
"FAJ25": "取得日期",
"FAJ25": "取得时间",
"FAJ26": "入账日期",
"FAJ31": "预留残值",
"FAJ43": "资产状态",
@@ -78,21 +82,23 @@ class Text2SQLService:
"GEM02": "部门名称",
}
_ASSET_DISPLAY_COLUMN_ORDER = (
"序号",
"资产编号",
"资产名称",
"规格型号",
"保管人",
"保管部门",
"图片",
"账套",
"保管人姓名",
"保管部门名称",
"存放位置名称",
"供应商",
"资产状态",
"数量",
"取得时间",
"规格型号",
"存放位置名称",
"预留残值",
"供应厂商",
"资产性质",
"本币单价",
"数量",
"计量单位",
"取得日期",
"入账日期",
)
_ASSET_VALUE_MAPPINGS = {
@@ -124,9 +130,10 @@ class Text2SQLService:
},
}
_ASSET_FALLBACK_NAME_COLUMNS = {
"保管人": ("保管人姓名", "员工姓名"),
"保管人": ("保管人", "保管人姓名", "员工姓名"),
"保管人工号": ("保管人姓名", "员工姓名"),
"保管部门": ("保管部门名称", "部门名称"),
"保管部门": ("保管部门", "保管部门名称", "部门名称"),
"供应商": ("供应商", "供应厂商"),
"存放位置": ("存放位置名称",),
"资产类型": ("资产类型名称", "类型名称"),
}
@@ -166,6 +166,23 @@ def test_build_chat_dify_inputs_falls_back_to_generic_adapter(monkeypatch):
}
def test_build_chat_dify_inputs_appends_role_for_training_agent():
"""培训 Agent 对接 Dify 时应额外透传后台账号角色,普通 generic 输入保持不变。"""
agent = _agent(
name='员工培训 Agent',
extra_config={'training_workspace_enabled': True},
)
inputs = build_chat_dify_inputs(
agent,
session_id='conv-training-001',
user_role='hr',
)
assert inputs.get('role') == 'hr'
assert AGENT_RUNTIME_CONTEXT_INPUT in inputs
def test_build_chat_dify_inputs_ignores_invalid_shipping_hints(monkeypatch):
"""shipping hints 非字典时应安全回退为空,避免平台入口依赖脏业务结构。"""
agent = _agent(
+14 -14
View File
@@ -73,8 +73,8 @@ def test_try_fast_route_maintenance(monkeypatch):
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: True),
'app.services.maintenance_chat_service.MaintenanceChatService.can_attempt',
staticmethod(lambda query, agent, session_id=None: True),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.stream_chat',
@@ -100,8 +100,8 @@ def test_try_fast_route_hr_leave_when_route_declared(monkeypatch):
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
'app.services.maintenance_chat_service.MaintenanceChatService.can_attempt',
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
@@ -132,8 +132,8 @@ def test_try_fast_route_text2sql_for_erp_kb(monkeypatch):
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
'app.services.maintenance_chat_service.MaintenanceChatService.can_attempt',
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
@@ -168,8 +168,8 @@ def test_try_fast_route_returns_none_for_generic_query(monkeypatch):
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
'app.services.maintenance_chat_service.MaintenanceChatService.can_attempt',
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
@@ -196,8 +196,8 @@ def test_try_fast_route_plm_skips_when_attachments_present(monkeypatch):
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
'app.services.maintenance_chat_service.MaintenanceChatService.can_attempt',
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
@@ -223,8 +223,8 @@ def test_try_fast_route_skips_hr_when_route_not_declared(monkeypatch):
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
'app.services.maintenance_chat_service.MaintenanceChatService.can_attempt',
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
@@ -250,8 +250,8 @@ def test_try_fast_route_skips_text2sql_without_route(monkeypatch):
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
'app.services.maintenance_chat_service.MaintenanceChatService.can_attempt',
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
+94
View File
@@ -0,0 +1,94 @@
"""
backend/tests/test_fixed_asset_image.py
用途:验证固定资产图片服务的多图排序与图片抓取兜底逻辑。
依赖:pytest、Flask app fixture、FixedAssetImageService。
逻辑关系:覆盖“按资产编号选中最佳 jpg”与“预览代理读取外部图片二进制”两个核心场景。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.fixed_asset_image import FixedAssetImageService
def test_resolve_images_returns_sorted_matches(app, monkeypatch):
app.config.update({
"FIXED_ASSET_IMAGE_BASE_URL": "http://192.168.8.158:8071/Web/#/login",
"FIXED_ASSET_IMAGE_USERNAME": "26040006",
"FIXED_ASSET_IMAGE_PASSWORD": "26040006",
"FIXED_ASSET_IMAGE_LIBRARY_ID": "lib-1",
"FIXED_ASSET_IMAGE_FOLDER_ID": "folder-1",
})
rows = [
{
"ID": "item-1",
"LeafName": "A082700482.",
"Path": "总务/固定资产/A082700482.",
"VersionID": "ver-1",
"MainFileAttachment": {
"ID": "att-1",
"Extension": ".jpg",
"FileSize": 12,
},
},
{
"ID": "item-2",
"LeafName": "A082700482_备份",
"Path": "总务/固定资产/A082700482_备份",
"VersionID": "ver-2",
"MainFileAttachment": {
"ID": "att-2",
"Extension": ".png",
"FileSize": 20,
},
},
]
def fake_request_json(method: str, path: str, **_: object):
assert method == "POST"
assert path == "/Api/_api/APS/Public/Item/Page"
return {"Code": 0, "Data": {"Rows": rows}}
recorded: list[tuple[str, str]] = []
monkeypatch.setattr(FixedAssetImageService, "_request_json", classmethod(lambda cls, method, path, **kwargs: fake_request_json(method, path, **kwargs)))
monkeypatch.setattr(FixedAssetImageService, "_record_browse", classmethod(lambda cls, item_id, version_id: recorded.append((item_id, version_id))))
with app.app_context():
result = FixedAssetImageService.resolve_images(asset_id="A082700482", asset_name="攻牙治具")
assert result["total"] == 2
assert result["item"]["attachment_id"] == "att-1"
assert [item["attachment_id"] for item in result["items"]] == ["att-1", "att-2"]
assert result["items"][0]["name"] == "A082700482.jpg"
assert result["items"][0]["url"] == "http://192.168.8.158:8071/Api/_api/DMS/Public/Attachment/Embed?attachmentID=att-1"
assert recorded == [("item-1", "ver-1")]
def test_fetch_preview_bytes_reads_external_image(app, monkeypatch):
app.config.update({
"FIXED_ASSET_IMAGE_BASE_URL": "http://192.168.8.158:8071/Web/#/login",
"FIXED_ASSET_IMAGE_USERNAME": "26040006",
"FIXED_ASSET_IMAGE_PASSWORD": "26040006",
"FIXED_ASSET_IMAGE_LIBRARY_ID": "lib-1",
"FIXED_ASSET_IMAGE_FOLDER_ID": "folder-1",
})
response = SimpleNamespace(
status_code=200,
headers={"content-type": "image/jpeg", "content-length": "4"},
content=b"test",
url="http://192.168.8.158:8071/Api/_api/DMS/Public/Attachment/Embed?attachmentID=att-1",
)
monkeypatch.setattr(FixedAssetImageService, "_request", classmethod(lambda cls, method, url_or_path, **kwargs: response))
with app.app_context():
content, content_type, err = FixedAssetImageService.fetch_preview_bytes(
"http://192.168.8.158:8071/Api/_api/DMS/Public/Attachment/Embed?attachmentID=att-1",
max_size=16,
)
assert err is None
assert content == b"test"
assert content_type == "image/jpeg"
+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] == "张三"
@@ -0,0 +1,134 @@
"""
backend/tests/test_maintenance_chat_service.py
用途:验证设备维保助手本地直答与 Dify 放行策略。
依赖:pytest fixture app、ChatLog/Agent/User/MaintenanceDevice 模型、maintenance_chat_service。
逻辑:直接构造会话历史与台账数据,断言上下文指代能命中上一轮设备,未命中时不会截断 Dify。
"""
from app import db
from app.models import Agent, ChatLog, MaintenanceDevice, User
from app.services.maintenance_chat_service import (
MAINTENANCE_MESSAGE_TYPE,
resolve_device_query_keyword,
try_stream_chat,
)
def _create_user_and_agent():
"""
创建维保助手测试所需的用户和 Agent。
Args:
无。
Returns:
(User, Agent):已写入数据库的测试对象。
"""
user = User(username='maintenance-user', email='maintenance@example.com', role='admin')
agent = Agent(
name='设备维保助手',
description='maintenance',
dify_app_id='maintenance-app',
dify_api_key='maintenance-key',
type='api',
api_base_url='http://dify.example/v1',
handler_config={'intent_routes': ['maintenance_chat']},
)
db.session.add_all([user, agent])
db.session.commit()
return user, agent
def test_resolve_context_device_code_from_previous_maintenance_result(app):
"""
断言“这个设备”等追问会复用同会话最近一次维保卡片中的设备编号。
"""
user, agent = _create_user_and_agent()
db.session.add(
ChatLog(
user_id=user.id,
agent_id=agent.id,
query='A070700001 的维修记录',
answer='已查询设备台账信息,下面是匹配结果。',
conversation_id='session-maintenance-1',
session_id='session-maintenance-1',
message_type=MAINTENANCE_MESSAGE_TYPE,
payload={'device': {'deviceCode': 'A070700001'}, 'matched': True},
)
)
db.session.commit()
keyword, source = resolve_device_query_keyword('这个设备的维修记录', agent, session_id='session-maintenance-1')
# 关键断言:本轮没有设备编号时,必须从上一轮维保卡片恢复设备上下文。
assert keyword == 'A070700001'
assert source == 'context'
def test_try_stream_chat_bypasses_dify_only_when_local_query_matches(app):
"""
断言本地库真实命中时返回 SSE 生成器,查不到时返回 None 让 chat.py 继续走 Dify。
"""
user, agent = _create_user_and_agent()
db.session.add(
MaintenanceDevice(
device_code='A070700001',
device_name='测试设备',
device_status='in_use',
)
)
db.session.commit()
local_stream = try_stream_chat(
'A070700001 的维修记录',
user,
agent,
session_id='session-maintenance-2',
request_id='req-local',
)
dify_fallback = try_stream_chat(
'不存在设备999999的维修记录',
user,
agent,
session_id='session-maintenance-2',
request_id='req-fallback',
)
# 关键断言:本地真实命中才接管;本地查不到时返回 None,交由 chat.py 后续 Dify 分支处理。
assert local_stream is not None
assert dify_fallback is None
def test_resolve_context_device_works_for_custom_agent_name_with_intent_route(app):
"""
断言 Agent 名称可自定义,只要 handler_config 声明 maintenance_chat 即可解析上下文设备。
"""
user = User(username='maintenance-user-2', email='maintenance2@example.com', role='admin')
agent = Agent(
name='工厂维保Bot',
description='maintenance',
dify_app_id='maintenance-app-2',
dify_api_key='maintenance-key-2',
type='api',
api_base_url='http://dify.example/v1',
handler_config={'intent_routes': ['maintenance_chat']},
)
db.session.add_all([user, agent])
db.session.flush()
db.session.add(
ChatLog(
user_id=user.id,
agent_id=agent.id,
query='A070700002 的维修记录',
answer='已查询设备台账信息,下面是匹配结果。',
conversation_id='session-maintenance-3',
session_id='session-maintenance-3',
message_type=MAINTENANCE_MESSAGE_TYPE,
payload={'device': {'deviceCode': 'A070700002'}, 'matched': True},
)
)
db.session.commit()
keyword, source = resolve_device_query_keyword('这个设备的维修记录', agent, session_id='session-maintenance-3')
assert keyword == 'A070700002'
assert source == 'context'
+3 -1
View File
@@ -3,7 +3,7 @@
## 设备维保助手补充需求
- 查询方式:用户通过 `设备维保助手` 会话查询设备维护/维修记录,系统支持按设备编号、设备名称、故障描述、维修说明、维修人和状态筛选记录。
- 管理方式:新增维修记录、设备台账配置属于固定管理人员操作,不通过会话消息承载;在聊天输入区底部以按钮进入右侧固定面板,面板顶部可关闭。
- 管理方式:新增维修记录、设备台账配置属于“管理员 / 维保管理员”角色操作,不通过会话消息承载;在聊天输入区底部以按钮进入右侧固定面板,面板顶部可关闭。
- 台账配置:右侧固定面板包含“设备列表”和“设备配置”两个 Tab,设备字段包含设备编号、设备名称、型号规格、使用部门、安装地点、设备状态、制造厂家、进厂日期、生产日期、启用日期、责任人用户名、维护周期和备注。
- Excel 导入:设备台账支持下载模板并从 Excel 批量导入,按设备编号判断新增或更新。
- 责任人规则:`responsible_user` 存储用户名文本,当前阶段不与用户表建立外键关联。
@@ -68,6 +68,8 @@
| 角色 | 说明 |
| --- | --- |
| 管理员 | 平台管理员,默认拥有所有功能权限,包括设备台账配置和维修记录维护 |
| 维保管理员 | 设备维保业务管理员,可维护设备台账配置、导入设备台账、维护维修记录;普通用户仅能通过会话查询设备台账与维修记录 |
| 员工 | 发起假期查询、请假申请、查询请假状态 |
| AI Agent | 识别用户意图,查询数据,发起流程,回传结果 |
| OA WorkflowService | 接收请假单并进入 OA 审批流 |
+4 -4
View File
@@ -5,10 +5,10 @@
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| 会话式维修记录查询 | 后端已实现 | 新增 `/api/maintenance/records` 查询接口,支持按设备编号、设备名称、维修状态筛选,供 Agent 会话查询和前端结果复用 |
| 会话式设备台账卡片 | 已实现 | 明确设备编号/名称查询由 HXOPS 后端本地直答,返回设备台账信息卡片和最近维修记录 |
| 会话式设备台账卡片 | 已实现 | 明确设备编号/名称查询由 HXOPS 后端本地直答,返回设备台账信息卡片和最近维修记录;支持“这个设备/这台”等同会话追问复用上一轮设备,本地未命中时放行 Dify 处理复杂语义 |
| Dify 设备维保查询 Tool | 已实现 | 新增 `/api/maintenance/tools/*` 只读 Tool API 与 `/api/maintenance/tools/openapi.json`,供 Dify 处理复杂问法时查询设备台账和维修记录 |
| 维修记录管理 | 已实现 | `设备维保助手` 聊天输入栏底部提供“维修记录”按钮,右侧固定面板支持维修记录查询、新增、编辑、删除 |
| 设备台账配置 | 已实现 | `设备维保助手` 聊天输入栏底部提供“台账配置”按钮,右侧固定面板包含“设备列表 / 设备配置”两个 Tab |
| 维修记录管理 | 已实现 | `设备维保助手` 聊天输入栏底部仅对“管理员 / 维保管理员”显示“维修记录”按钮,右侧固定面板支持维修记录查询、新增、编辑、删除 |
| 设备台账配置 | 已实现 | `设备维保助手` 聊天输入栏底部仅对“管理员 / 维保管理员”显示“台账配置”按钮,右侧固定面板包含“设备列表 / 设备配置”两个 Tab |
| Excel 导入设备台账 | 已实现 | 支持下载设备台账模板并通过 Excel 批量导入,按设备编号新增或更新 |
| 设备财务字段配置 | 已实现 | 设备台账支持原值、残值和账套字段;账套固定选项为和信、科技、电子、和宏智 |
| 责任人字段 | 已实现 | 设备台账责任人字段使用 `responsible_user` / `responsibleUser` 用户名文本,不关联用户表 |
@@ -31,7 +31,7 @@
| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 |
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
| 培训业务闭环整改清单 | 已文档化 | 见 [docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
## 1. 功能总览
@@ -767,7 +767,7 @@
<button class="tool-pill manager" type="button" data-drawer="repair">+ 新增维修记录</button>
<button class="tool-pill manager" type="button" data-drawer="ledger">▦ 台账配置</button>
<button class="tool-pill" type="button">企业知识库⌄</button>
<span class="manager-note">管理操作:仅资产管理员 / 维修主管可用</span>
<span class="manager-note">管理操作:仅管理员 / 维保管理员可用</span>
</div>
</div>
<div class="disclaimer">AI 查询可能会犯错,请核实重要信息。写入类操作只能由固定管理人员在右侧面板中确认提交。</div>
@@ -856,7 +856,7 @@
</template>
<template id="repairDrawerTemplate">
<div class="permission-box">当前管理身份:维修主管 / 资产管理员。普通用户只能查询或提交报修描述,不能直接写入维修记录。</div>
<div class="permission-box">当前管理身份:管理员 / 维保管理员。普通用户只能查询或提交报修描述,不能直接写入维修记录。</div>
<div class="field-grid">
<label class="field">设备编号<input value="A022700978" /></label>
<label class="field">设备名称<input value="注塑件自动冲切水口机" /></label>
@@ -954,7 +954,7 @@
</template>
<template id="ledgerDrawerTemplate">
<div class="permission-box">当前管理身份:资产管理员。台账配置会影响设备基础信息,需记录变更审计。</div>
<div class="permission-box">当前管理身份:管理员 / 维保管理员。台账配置会影响设备基础信息,需记录变更审计。</div>
<div class="panel-tabs">
<button class="panel-tab active" type="button" data-ledger-tab="list">设备列表</button>
<button class="panel-tab" type="button" data-ledger-tab="form">设备配置</button>
@@ -1098,8 +1098,8 @@
function openDrawer(type) {
activeDrawerType = type;
const drawerMeta = {
repair: ["新增维修记录", "仅维修主管 / 资产管理员可新增维修记录。", "repairDrawerTemplate"],
ledger: ["台账配置", "仅资产管理员可维护设备台账。", "ledgerDrawerTemplate"],
repair: ["新增维修记录", "仅管理员 / 维保管理员可新增维修记录。", "repairDrawerTemplate"],
ledger: ["台账配置", "仅管理员 / 维保管理员可维护设备台账。", "ledgerDrawerTemplate"],
detail: ["维修记录明细", "查询类操作,右侧固定面板展示详情。", "detailDrawerTemplate"],
filter: ["继续筛选", "查询类操作,确认后刷新当前结果卡片。", "filterDrawerTemplate"]
};
@@ -1154,7 +1154,7 @@
const intent = detectIntent(normalized);
if (intent === "config") {
addMessage("assistant", "这是管理配置类操作。为了控制权限,请使用底部“台账配置”按钮,在右侧固定面板中由资产管理员确认。");
addMessage("assistant", "这是管理配置类操作。为了控制权限,请使用底部“台账配置”按钮,在右侧固定面板中由管理员 / 维保管理员确认。");
} else if (intent === "create") {
addMessage("assistant", "这是写入类操作。普通会话只负责说明和查询,请固定管理人员点击底部“新增维修记录”按钮,在右侧固定面板中提交。");
} else if (intent === "asset") {
+1 -1
View File
@@ -921,7 +921,7 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth;
“新人入职培训 Agent”不建议走纯 Dify 考试编排主链,推荐采用:
- **主链**:Chat 页面内嵌培训工作区 + 前端受控状态机 + 后端真实记录落库
- **辅助层**:Dify 承担培训 FAQ、知识点解释、HR 自然语言统计问答(ChatBI)
- **辅助层**:Dify 承担培训 FAQ、知识点解释、HR 自然语言统计问答(ChatBI);员工培训 Agent 对接 Dify 时额外透传后台账号 `role`,供画布区分学员/HR/管理员提示词或分支
该方案更符合培训考试场景对“流程刚性、成绩可信、状态可恢复、结果可审计”的要求。
@@ -116,6 +116,7 @@ export interface AdminAgentRegistrySchema {
models?: string[];
required_fields?: string[];
forced_capabilities?: Record<string, boolean>;
default_intent_routes?: string[];
handler_config_schema?: Record<string, unknown>;
}>;
handler_config_schemas: Record<string, unknown>;
@@ -7,8 +7,8 @@
*/
<script setup lang="ts">
import { computed, watch } from 'vue';
import { FileDown, Plus, Trash2, X } from 'lucide-vue-next';
import { computed, ref, watch } from 'vue';
import { ChevronDown, FileDown, Plus, Search, Trash2, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import type { AgentFormState, AgentGuideSummary } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
@@ -52,6 +52,8 @@ const emit = defineEmits<{
const { t } = useI18n();
const optionLabels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
const advancedOpen = ref(false);
const intentRouteSearch = ref('');
const showDifyFields = computed(() => props.form.runtime_provider === 'dify' || props.form.runtime_provider === 'hybrid');
const showIframeFields = computed(() => props.form.runtime_provider === 'iframe');
@@ -67,6 +69,30 @@ const currentCatalogEntry = computed(() => (
const taskProgressForced = computed(() => catalogForcesTaskProgress(currentCatalogEntry.value));
const selectedIntentRouteOptions = computed(() => (
props.form.intent_routes
.map((key) => props.intentRouteOptions.find((item) => item.key === key))
.filter(Boolean) as IntentRouteOption[]
));
const intentRouteSummary = computed(() => {
if (!selectedIntentRouteOptions.value.length) return t('admin.agent.registry.intentRoutesNone');
return t('admin.agent.registry.intentRoutesSummary', {
count: selectedIntentRouteOptions.value.length,
names: selectedIntentRouteOptions.value.map((item) => item.label).join('、'),
});
});
const filteredIntentRouteOptions = computed(() => {
const keyword = intentRouteSearch.value.trim().toLowerCase();
if (!keyword) return props.intentRouteOptions;
return props.intentRouteOptions.filter((route) => (
route.key.toLowerCase().includes(keyword)
|| route.label.toLowerCase().includes(keyword)
|| String(route.description || '').toLowerCase().includes(keyword)
));
});
/**
* 切换 intent_route 勾选状态。
*/
@@ -84,6 +110,13 @@ const toggleIntentRoute = (route: string, checked: boolean) => {
void props.syncContentProfileFromIntentRoutes(props.form);
};
/**
* 移除已选 intent_route tag。
*/
const removeIntentRoute = (route: string) => {
toggleIntentRoute(route, false);
};
/**
* 套用 content_profile 默认欢迎语与推荐问题。
*/
@@ -303,29 +336,73 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
</div>
<div class="space-y-4">
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.registry.intentRoutesLabel') }}</label>
<div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
<label
v-for="route in intentRouteOptions"
:key="route.key"
class="inline-flex items-start gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary"
>
<input
type="checkbox"
class="mt-0.5 accent-brand-600"
:checked="form.intent_routes.includes(route.key)"
@change="toggleIntentRoute(route.key, ($event.target as HTMLInputElement).checked)"
/>
<span>
<span class="font-medium text-primary">{{ route.label }}</span>
<span v-if="route.description" class="mt-1 block text-xs leading-5 text-muted">
{{ route.description }}
</span>
<div class="rounded-xl border border-default bg-white">
<button
type="button"
class="flex w-full items-center justify-between gap-3 px-4 py-3 text-left"
@click="advancedOpen = !advancedOpen"
>
<div>
<div class="text-sm font-semibold text-primary">{{ t('admin.agent.registry.advancedTitle') }}</div>
<div class="mt-1 text-xs text-muted">{{ intentRouteSummary }}</div>
</div>
<ChevronDown class="h-4 w-4 text-muted transition-transform" :class="{ 'rotate-180': advancedOpen }" />
</button>
<div v-if="advancedOpen" class="border-t border-default px-4 py-4">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.registry.intentRoutesLabel') }}</label>
<div class="mt-2 flex flex-wrap gap-2 rounded-xl border border-default px-3 py-2">
<span
v-for="route in selectedIntentRouteOptions"
:key="route.key"
class="inline-flex items-center gap-1 rounded-full bg-surface-soft px-2.5 py-1 text-xs text-secondary"
>
{{ route.label }}
<button type="button" @click="removeIntentRoute(route.key)">
<X class="h-3 w-3" />
</button>
</span>
</label>
<span v-if="!selectedIntentRouteOptions.length" class="text-sm text-muted">
{{ t('admin.agent.registry.intentRoutesPlaceholder') }}
</span>
</div>
<div class="mt-3 rounded-xl border border-default">
<div class="flex items-center gap-2 border-b border-default px-3 py-2">
<Search class="h-4 w-4 text-muted" />
<input
v-model="intentRouteSearch"
type="search"
class="w-full bg-transparent text-sm outline-none"
:placeholder="t('admin.agent.registry.intentRoutesSearch')"
/>
</div>
<div class="max-h-56 overflow-y-auto p-2">
<label
v-for="route in filteredIntentRouteOptions"
:key="route.key"
class="flex cursor-pointer items-start gap-2 rounded-lg px-2 py-2 text-sm hover:bg-surface-soft"
>
<input
type="checkbox"
class="mt-0.5 accent-brand-600"
:checked="form.intent_routes.includes(route.key)"
@change="toggleIntentRoute(route.key, ($event.target as HTMLInputElement).checked)"
/>
<span>
<span class="font-medium text-primary">{{ route.label }}</span>
<span v-if="route.description" class="mt-1 block text-xs leading-5 text-muted">
{{ route.description }}
</span>
</span>
</label>
</div>
</div>
<p class="mt-2 text-xs leading-5 text-muted">{{ t('admin.agent.registry.intentRoutesHint') }}</p>
</div>
<p class="text-xs leading-5 text-muted">{{ t('admin.agent.registry.intentRoutesHint') }}</p>
</div>
<div class="space-y-2">
@@ -33,6 +33,18 @@ const shippingCatalogEntry: AgentTypeCatalogEntry = {
handler_config_schema: {},
};
const fixedAssetsCatalogEntry: AgentTypeCatalogEntry = {
agent_code: 'fixed_assets',
label: '固资管理',
conversation_mode_default: 'chat',
runtime_provider_default: 'dify',
default_intent_routes: ['text2sql'],
handler_config_schema: {
intent_routes: { type: 'array', items: 'string' },
content_profile: { type: 'string' },
},
};
describe('useAgentsAdminRegistry catalog switch', () => {
it('pruneHandlerFormFieldsForCatalog clears intent routes and content profile for empty schema', () => {
const form = createEmptyAgentForm();
@@ -68,4 +80,24 @@ describe('useAgentsAdminRegistry catalog switch', () => {
expect(payload.handler_config).toBeNull();
});
it('applyCatalogDefaultsToForm applies default_intent_routes when catalog supports intent_routes', () => {
const form = createEmptyAgentForm();
applyCatalogDefaultsToForm(form, genericCatalogEntry);
form.intent_routes = ['hr_leave'];
applyCatalogDefaultsToForm(form, fixedAssetsCatalogEntry);
expect(form.intent_routes).toEqual(['text2sql']);
});
it('applyCatalogDefaultsToForm clears intent routes when catalog schema lacks intent_routes', () => {
const form = createEmptyAgentForm();
applyCatalogDefaultsToForm(form, fixedAssetsCatalogEntry);
expect(form.intent_routes).toEqual(['text2sql']);
applyCatalogDefaultsToForm(form, shippingCatalogEntry);
expect(form.intent_routes).toEqual([]);
});
});
@@ -32,6 +32,8 @@ export interface AgentTypeCatalogEntry {
runtime_provider_default: string;
default_intent_routes?: string[];
runtime_handler?: string | null;
models?: string[];
@@ -232,6 +234,11 @@ export function applyCatalogDefaultsToForm(
pruneHandlerFormFieldsForCatalog(form, entry);
const schemaFields = new Set(handlerConfigSchemaFieldNames(entry));
if (schemaFields.has('intent_routes')) {
form.intent_routes = normalizeIntentRoutes(entry.default_intent_routes || []);
}
}
@@ -40,6 +40,7 @@ const { t } = useI18n();
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="hr">{{ t('admin.role.hr') }}</option>
<option value="maintenance_manager">{{ t('admin.role.maintenanceManager') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
@@ -88,6 +88,7 @@ const { t } = useI18n();
<select v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option value="user">{{ t('admin.role.user') }}</option>
<option value="hr">{{ t('admin.role.hr') }}</option>
<option value="maintenance_manager">{{ t('admin.role.maintenanceManager') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
@@ -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">
@@ -41,6 +41,7 @@ const props = defineProps<{
canSendMessage: boolean;
isShippingNoticeAgent: boolean;
isMaintenanceAgent?: boolean;
canManageMaintenance?: boolean;
shippingSuggestedPrompt: string;
shippingFocusTaskNo?: string;
shippingFocusReason?: string;
@@ -202,7 +203,7 @@ watch(
ref="textareaRef"
v-model="inputValue"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : $t('chat.askAnything')"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : isMaintenanceAgent ? $t('maintenance.chat.inputPlaceholder') : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-2.5 py-1.5 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
style="min-height: 40px; max-height: 220px;"
:disabled="isVoiceTranscribing"
@@ -259,7 +260,7 @@ watch(
</div>
<div
v-if="isMaintenanceAgent"
v-if="isMaintenanceAgent && canManageMaintenance"
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
>
<button
@@ -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>
@@ -31,6 +31,7 @@ const embeddedIframeSrc = computed(() => {
const url = agent.iframe_url;
return url ? String(url) : undefined;
});
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
const isTrainingWorkspaceExpanded = ref(false);
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
@@ -224,6 +225,7 @@ watch(() => page.currentAgentId, () => {
:can-send-message="page.canSendMessage"
:is-shipping-notice-agent="page.isShippingNoticeAgent"
:is-maintenance-agent="isMaintenanceAgentPage"
:can-manage-maintenance="canManageMaintenance"
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
:shipping-focus-task-no="page.focusedShippingTaskNo"
:shipping-focus-reason="page.shippingFocusReason"
@@ -245,7 +247,7 @@ watch(() => page.currentAgentId, () => {
</div>
<aside
v-if="isMaintenanceAgentPage && maintenancePanel"
v-if="isMaintenanceAgentPage && canManageMaintenance && maintenancePanel"
class="relative flex flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.06)]"
:class="[
isMaintenancePanelFullscreen ? 'absolute inset-y-0 right-0 z-30' : '',
@@ -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);
@@ -15,6 +15,9 @@ interface MaintenanceDeviceResultPayload {
matched?: boolean;
device?: MaintenanceDevice;
records?: MaintenanceRecord[];
summary?: {
ledgerMatched?: boolean;
};
actions?: Array<{ id: string; label: string }>;
}
@@ -32,6 +35,8 @@ const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
const device = computed(() => payload.value?.device || null);
const records = computed(() => payload.value?.records || []);
const hasResult = computed(() => Boolean(device.value || records.value.length));
const ledgerMatched = computed(() => payload.value?.summary?.ledgerMatched !== false);
const statusLabel = computed(() => {
const status = device.value?.deviceStatus;
@@ -67,15 +72,20 @@ const rows = computed(() => {
</script>
<template>
<section v-if="device" class="mt-3 rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-800 shadow-sm">
<section v-if="hasResult" class="mt-3 rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-800 shadow-sm">
<div class="flex items-center justify-between gap-3 rounded-t-lg border border-slate-200 bg-slate-50 px-3 py-2">
<h3 class="font-semibold">{{ t('maintenance.chat.deviceLedgerInfo') }}</h3>
<span class="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-semibold text-emerald-700">
{{ t('maintenance.chat.matched') }}
<h3 class="font-semibold">
{{ device ? t('maintenance.chat.deviceLedgerInfo') : t('maintenance.chat.recordInfo') }}
</h3>
<span
class="rounded-full px-2.5 py-0.5 text-xs font-semibold"
:class="ledgerMatched ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'"
>
{{ ledgerMatched ? t('maintenance.chat.matched') : t('maintenance.chat.recordMatched') }}
</span>
</div>
<div class="overflow-hidden border-x border-b border-slate-200">
<div v-if="device" class="overflow-hidden border-x border-b border-slate-200">
<table class="w-full table-fixed text-sm">
<tbody>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex" class="border-t border-slate-200 first:border-t-0">
@@ -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';
@@ -159,6 +160,8 @@ export function useChatPage() {
const {
filePreviewVisible,
previewFile,
previewFiles,
currentPreviewIndex,
getSourceTitle,
getSourceMeta,
getSourceBrief,
@@ -167,6 +170,8 @@ export function useChatPage() {
getDisplayRetrieverResources,
shouldExpandSourceDetails,
openPreview,
openPreviewGallery,
setPreviewFileIndex,
parsePlmPreviewLink,
} = sourceFiles;
const assetHistory = useChatAssetHistory({
@@ -174,6 +179,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);
@@ -318,6 +328,8 @@ export function useChatPage() {
resetPeripheralState,
filePreviewVisible,
previewFile,
previewFiles,
currentPreviewIndex,
});
({ loadConversation, startNewChat } = conversationApi);
@@ -366,6 +378,7 @@ export function useChatPage() {
parsePlmPreviewLink,
openPreview,
openAssetHistory: assetHistory.openHistory,
openAssetImage: assetImage.openImage,
getMessageLinks,
getDisplayRetrieverResources,
getSourceLinks,
@@ -507,6 +520,7 @@ export function useChatPage() {
queryPreviewError: queryPreview.error,
queryPreviewState: queryPreview.state,
assetHistory,
assetImage,
...agent,
agentGuides: chatGuides.guides,
showGuideModal: chatGuides.showModal,
@@ -517,6 +531,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,
@@ -119,6 +119,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;
@@ -439,34 +439,30 @@ onMounted(loadRecords);
</div>
<div class="min-h-0 overflow-auto rounded-xl border border-default bg-surface">
<table class="min-w-full text-left text-sm">
<table class="w-full table-fixed text-left text-sm">
<thead class="bg-muted/50 text-secondary">
<tr>
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.modelSpec') }}</th>
<th class="w-[24%] px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
<th class="w-[22%] px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.faultDescription') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.repairer') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.operation') }}</th>
<th class="w-[14%] px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
<th class="w-[18%] px-3 py-2 text-right">{{ t('maintenance.record.table.operation') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="7" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
<td colspan="5" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
</tr>
<tr v-else-if="!records.length">
<td colspan="7" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.empty') }}</td>
<td colspan="5" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.empty') }}</td>
</tr>
<tr v-for="record in records" v-else :key="record.id" class="border-t border-default">
<td class="px-3 py-2 font-semibold">{{ record.deviceCode }}</td>
<td class="px-3 py-2">{{ record.deviceName || '-' }}</td>
<td class="px-3 py-2">{{ record.modelSpec || '-' }}</td>
<td class="max-w-[260px] truncate px-3 py-2">{{ record.faultDescription }}</td>
<td class="truncate px-3 py-2 font-semibold" :title="record.deviceCode">{{ record.deviceCode }}</td>
<td class="truncate px-3 py-2" :title="record.deviceName || '-'">{{ record.deviceName || '-' }}</td>
<td class="truncate px-3 py-2" :title="record.faultDescription">{{ record.faultDescription }}</td>
<td class="px-3 py-2">{{ formatStatus(record.repairStatus) }}</td>
<td class="px-3 py-2">{{ record.repairer || '-' }}</td>
<td class="px-3 py-2">
<div class="flex gap-2">
<div class="flex justify-end gap-2">
<button type="button" class="admin-report-page-btn" @click="startEdit(record)">{{ t('maintenance.record.actions.edit') }}</button>
<button
type="button"
+6
View File
@@ -237,6 +237,11 @@
"title": "Routing & Capabilities",
"subtitle": "Configure intent fast paths and ERP knowledge base without relying on agent name heuristics",
"intentRoutesLabel": "Intent routes",
"advancedTitle": "Advanced settings",
"intentRoutesNone": "No intent routes enabled",
"intentRoutesSummary": "{count} enabled: {names}",
"intentRoutesPlaceholder": "No intent routes selected",
"intentRoutesSearch": "Search intent routes",
"intentRoutesHint": "Enable fast paths such as leave SQL, PLM material extraction, maintenance chat, or Text2SQL",
"contentProfileLabel": "Content profile",
"contentProfileHint": "Pick a profile such as generic_entrance or hr_policy, then apply default welcome text and suggested questions into structured columns",
@@ -1118,6 +1123,7 @@
"role": {
"user": "User",
"hr": "HR",
"maintenanceManager": "Maintenance Admin",
"admin": "Admin",
"guest": "Guest"
},
+5 -2
View File
@@ -80,7 +80,7 @@
"panel": {
"recordTitle": "Maintenance Records",
"ledgerTitle": "Ledger Config",
"adminOnly": "Admin actions: asset admins / maintenance supervisors only",
"adminOnly": "Admin actions: admins / maintenance admins only",
"resizeTitle": "Drag to resize",
"ledgerSubtitle": "Equipment List / Equipment Config",
"recordSubtitle": "Record List / Record Config",
@@ -189,9 +189,12 @@
},
"chat": {
"deviceLedgerInfo": "Equipment Ledger Info",
"recordInfo": "Equipment Maintenance Records",
"matched": "Matched",
"recordMatched": "Maintenance records matched",
"recentRecords": "Recent maintenance records ({count})",
"viewRepairHistory": "View Repair History",
"addRepairRecord": "Add Repair Record"
"addRepairRecord": "Add Repair Record",
"inputPlaceholder": "Ask me about equipment maintenance, e.g. query ledger info for A022700978"
}
}
+6
View File
@@ -237,6 +237,11 @@
"title": "เส้นทางและความสามารถ",
"subtitle": "กำหนด fast path ของ intent และ ERP knowledge base โดยไม่พึ่งชื่อแอป",
"intentRoutesLabel": "Intent routes",
"advancedTitle": "การตั้งค่าขั้นสูง",
"intentRoutesNone": "ยังไม่ได้เปิดใช้ intent routes",
"intentRoutesSummary": "เปิดใช้ {count} รายการ: {names}",
"intentRoutesPlaceholder": "ยังไม่ได้เลือก intent routes",
"intentRoutesSearch": "ค้นหา intent routes",
"intentRoutesHint": "เปิดใช้ fast path เช่น leave SQL, PLM, maintenance chat หรือ Text2SQL",
"contentProfileLabel": "Content profile",
"contentProfileHint": "เลือก profile เช่น generic_entrance หรือ hr_policy แล้วนำ welcome / suggested questions ไปเขียนลง structured columns",
@@ -977,6 +982,7 @@
"role": {
"user": "ผู้ใช้ทั่วไป",
"hr": "HR",
"maintenanceManager": "ผู้ดูแลซ่อมบำรุง",
"admin": "ผู้ดูแลระบบ",
"guest": "ผู้เยี่ยมชม"
},
+5 -2
View File
@@ -80,7 +80,7 @@
"panel": {
"recordTitle": "บันทึกซ่อมบำรุง",
"ledgerTitle": "ตั้งค่าทะเบียน",
"adminOnly": "งานผู้ดูแล: ใช้ได้เฉพาะผู้ดูแลทรัพย์สิน / หัวหน้าซ่อมบำรุง",
"adminOnly": "งานผู้ดูแล: เฉพาะผู้ดูแลระบบ / ผู้ดูแลซ่อมบำรุง",
"resizeTitle": "ลากเพื่อปรับความกว้าง",
"ledgerSubtitle": "รายการอุปกรณ์ / ตั้งค่าอุปกรณ์",
"recordSubtitle": "รายการบันทึก / ตั้งค่าบันทึก",
@@ -189,9 +189,12 @@
},
"chat": {
"deviceLedgerInfo": "ข้อมูลทะเบียนอุปกรณ์",
"recordInfo": "บันทึกซ่อมบำรุงอุปกรณ์",
"matched": "พบข้อมูล",
"recordMatched": "พบบันทึกซ่อมบำรุง",
"recentRecords": "บันทึกซ่อมบำรุงล่าสุด ({count})",
"viewRepairHistory": "ดูประวัติซ่อม",
"addRepairRecord": "เพิ่มบันทึกซ่อม"
"addRepairRecord": "เพิ่มบันทึกซ่อม",
"inputPlaceholder": "ถามข้อมูลซ่อมบำรุงอุปกรณ์ เช่น ค้นหาทะเบียนของ A022700978"
}
}
+6
View File
@@ -238,6 +238,11 @@
"title": "路由与能力",
"subtitle": "配置 Intent 快路径与 ERP 知识库等结构化能力,运行时不再依赖应用名称判断",
"intentRoutesLabel": "Intent 路由",
"advancedTitle": "高级配置",
"intentRoutesNone": "未启用 Intent 路由",
"intentRoutesSummary": "已启用 {count} 个:{names}",
"intentRoutesPlaceholder": "暂未选择 Intent 路由",
"intentRoutesSearch": "搜索 Intent 路由",
"intentRoutesHint": "勾选后启用对应快路径(如请假 SQL、PLM 物料、设备维保、Text2SQL)",
"contentProfileLabel": "内容 Profile",
"contentProfileHint": "选择 generic_entrance / hr_policy 等 profile,可套用默认欢迎语与推荐问题并写入结构化列",
@@ -1098,6 +1103,7 @@
"role": {
"user": "普通用户",
"hr": "HR",
"maintenanceManager": "维保管理员",
"admin": "管理员",
"guest": "访客"
},
+5 -2
View File
@@ -80,7 +80,7 @@
"panel": {
"recordTitle": "维修记录",
"ledgerTitle": "台账配置",
"adminOnly": "管理操作:仅资产管理员 / 维修主管可用",
"adminOnly": "管理操作:仅管理员 / 维保管理员可用",
"resizeTitle": "拖拽调整宽度",
"ledgerSubtitle": "设备列表 / 设备配置",
"recordSubtitle": "记录列表 / 记录配置",
@@ -189,9 +189,12 @@
},
"chat": {
"deviceLedgerInfo": "设备台账信息",
"recordInfo": "设备维修记录",
"matched": "已匹配",
"recordMatched": "已匹配维修记录",
"recentRecords": "最近维修记录({count} 条)",
"viewRepairHistory": "查维修历史",
"addRepairRecord": "新增维修记录"
"addRepairRecord": "新增维修记录",
"inputPlaceholder": "问我设备维保相关信息,例如:查询 A022700978 的设备台账信息"
}
}
+6
View File
@@ -237,6 +237,11 @@
"title": "路由與能力",
"subtitle": "配置 Intent 快路徑與 ERP 知識庫等結構化能力,執行時不再依賴應用名稱判斷",
"intentRoutesLabel": "Intent 路由",
"advancedTitle": "進階設定",
"intentRoutesNone": "未啟用 Intent 路由",
"intentRoutesSummary": "已啟用 {count} 個:{names}",
"intentRoutesPlaceholder": "暫未選擇 Intent 路由",
"intentRoutesSearch": "搜尋 Intent 路由",
"intentRoutesHint": "勾選後啟用對應快路徑(如請假 SQL、PLM 物料、設備維保、Text2SQL)",
"contentProfileLabel": "內容 Profile",
"contentProfileHint": "選擇 generic_entrance / hr_policy 等 profile,可套用預設歡迎語與推薦問題並寫入結構化欄位",
@@ -978,6 +983,7 @@
"role": {
"user": "普通用戶",
"hr": "HR",
"maintenanceManager": "維保管理員",
"admin": "管理員",
"guest": "訪客"
},
+5 -2
View File
@@ -80,7 +80,7 @@
"panel": {
"recordTitle": "維修記錄",
"ledgerTitle": "台帳配置",
"adminOnly": "管理操作:僅資產管理員 / 維修主管可用",
"adminOnly": "管理操作:僅管理員 / 維保管理員可用",
"resizeTitle": "拖曳調整寬度",
"ledgerSubtitle": "設備列表 / 設備配置",
"recordSubtitle": "記錄列表 / 記錄配置",
@@ -189,9 +189,12 @@
},
"chat": {
"deviceLedgerInfo": "設備台帳資訊",
"recordInfo": "設備維修記錄",
"matched": "已匹配",
"recordMatched": "已匹配維修記錄",
"recentRecords": "最近維修記錄({count} 筆)",
"viewRepairHistory": "查維修歷史",
"addRepairRecord": "新增維修記錄"
"addRepairRecord": "新增維修記錄",
"inputPlaceholder": "問我設備維保相關資訊,例如:查詢 A022700978 的設備台帳資訊"
}
}
@@ -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"