From 56b6ea06a8b41d3e89536c041eeb7bc455236d40 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Fri, 3 Jul 2026 18:59:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(chat-fixed-assets):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=B5=84=E4=BA=A7=E5=B1=A5=E5=8E=86=E7=9B=B4=E8=BE=BE=E9=A2=84?= =?UTF-8?q?=E8=A7=88=E5=B9=B6=E4=BC=98=E5=8C=96=20Excel=20=E9=A2=84?= =?UTF-8?q?=E8=A7=88=E4=BD=93=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/chat.py | 120 ++++++- backend/app/core/config/settings.py | 4 + backend/app/services/fixed_asset_history.py | 325 ++++++++++++++++++ docs/funclist.md | 1 + frontend/src/features/chat/api/chat.api.ts | 16 +- .../components/ChatAssetHistoryDialog.vue | 91 +++++ .../components/ChatQueryPreviewDialog.vue | 28 +- .../chat/components/ChatViewOverlays.vue | 15 +- .../components/messages/ChatMessageBubble.vue | 28 +- .../chat/composables/useChatAssetHistory.ts | 106 ++++++ .../features/chat/composables/useChatPage.ts | 8 + .../features/chat/page/useChatPageMarkdown.ts | 74 +++- .../src/features/chat/types/chat.types.ts | 18 + .../shared/components/FilePreviewModal.vue | 265 ++++++++++++-- 14 files changed, 1051 insertions(+), 48 deletions(-) create mode 100644 backend/app/services/fixed_asset_history.py create mode 100644 frontend/src/features/chat/components/ChatAssetHistoryDialog.vue create mode 100644 frontend/src/features/chat/composables/useChatAssetHistory.ts diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index ced422c2..c899dbef 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -21,6 +21,7 @@ from flask import Blueprint, request, Response, stream_with_context, jsonify, g, from sqlalchemy import func, desc, or_, exists, and_ from openpyxl import load_workbook from app.services.dify import DifyService +from app.core.config.settings import Config from app.services.integration_api import IntegrationApiService from app.core.decorators import require_agent_permission from app.models import Agent, ChatLog, ChatSession, Feedback @@ -217,8 +218,18 @@ def _normalize_windows_share_path(path_value: str) -> str: def _is_allowed_share_path(target_url: str) -> bool: normalized_target = _normalize_windows_share_path(target_url) - normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT) - return bool(normalized_root and normalized_target.startswith('\\\\') and normalized_target.lower().startswith(normalized_root.lower())) + if not normalized_target.startswith('\\\\'): + return False + history_share_root = '' + if has_request_context(): + history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip() + if not history_share_root: + history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip() + roots = [ + _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT), + _normalize_windows_share_path(history_share_root), + ] + return any(root and normalized_target.lower().startswith(root.lower()) for root in roots) def _is_allowed_preview_url(target_url: str) -> bool: """ @@ -1115,6 +1126,111 @@ def get_chat_query_preview(chat_log_id: int): 'query': query, }) + +@chat_bp.route('/asset-history/search', methods=['GET']) +@require_agent_permission +def search_asset_history_files(): + """ + 检索固定资产履历文件。 + + 用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。 + 约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。 + """ + asset_id = (request.args.get('asset_id') or '').strip() + asset_name = (request.args.get('asset_name') or '').strip() + limit = request.args.get('limit', type=int) or 20 + limit = max(1, min(limit, 50)) + # #region debug-point C:asset-history-api-entry + import json as _debug_json + import urllib.request as _debug_urllib_request + try: + _debug_payload = _debug_json.dumps({ + 'sessionId': 'asset-history-click', + 'runId': 'pre-fix', + 'hypothesisId': 'C', + 'location': 'backend/chat.py:search_asset_history_files', + 'msg': '[DEBUG] asset history api entry', + 'data': { + 'asset_id': asset_id, + 'asset_name': asset_name, + 'limit': limit, + }, + }).encode('utf-8') + _debug_urllib_request.urlopen(_debug_urllib_request.Request( + 'http://127.0.0.1:7777/event', + data=_debug_payload, + headers={'Content-Type': 'application/json'}, + method='POST', + ), timeout=2).read() + except Exception: + pass + # #endregion + + if not asset_id and not asset_name: + raise ValidationError('asset_id or asset_name is required') + + from app.services.fixed_asset_history import FixedAssetHistoryService + + if not FixedAssetHistoryService.is_enabled(): + # #region debug-point C:asset-history-api-disabled + try: + _debug_payload = _debug_json.dumps({ + 'sessionId': 'asset-history-click', + 'runId': 'pre-fix', + 'hypothesisId': 'C', + 'location': 'backend/chat.py:search_asset_history_files', + 'msg': '[DEBUG] asset history api disabled', + 'data': { + 'share_root': str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or ''), + }, + }).encode('utf-8') + _debug_urllib_request.urlopen(_debug_urllib_request.Request( + 'http://127.0.0.1:7777/event', + data=_debug_payload, + headers={'Content-Type': 'application/json'}, + method='POST', + ), timeout=2).read() + except Exception: + pass + # #endregion + raise ServiceUnavailableError('asset history share is not configured') + + items = FixedAssetHistoryService.search_history_files( + asset_id=asset_id, + asset_name=asset_name, + limit=limit, + ) + # #region debug-point C:asset-history-api-success + try: + _debug_payload = _debug_json.dumps({ + 'sessionId': 'asset-history-click', + 'runId': 'pre-fix', + 'hypothesisId': 'C', + 'location': 'backend/chat.py:search_asset_history_files', + 'msg': '[DEBUG] asset history api success', + 'data': { + 'asset_id': asset_id, + 'asset_name': asset_name, + 'item_count': len(items), + }, + }).encode('utf-8') + _debug_urllib_request.urlopen(_debug_urllib_request.Request( + 'http://127.0.0.1:7777/event', + data=_debug_payload, + headers={'Content-Type': 'application/json'}, + method='POST', + ), timeout=2).read() + except Exception: + pass + # #endregion + return jsonify({ + 'asset_id': asset_id, + 'asset_name': asset_name, + 'total': len(items), + 'items': items, + }) + + @chat_bp.route('/completions', methods=['POST']) @require_agent_permission def chat_completions(): diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 9bf62323..874f8e0b 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -282,6 +282,10 @@ class Config: ) FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3') FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets') + FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip() + FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip() + FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '') + FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20') FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv( 'FIXED_ASSETS_DOCS_EXPORT_ROOT', str(_ROOT_DIR / 'docs'), diff --git a/backend/app/services/fixed_asset_history.py b/backend/app/services/fixed_asset_history.py new file mode 100644 index 00000000..ef10e3b4 --- /dev/null +++ b/backend/app/services/fixed_asset_history.py @@ -0,0 +1,325 @@ +""" +backend/app/services/fixed_asset_history.py + +用途:为固资管理提供“资产履历”共享盘检索能力,按资产编号/资产名称匹配履历文件。 +依赖:app.core.config.settings.Config、chat.py 里的预览代理会复用这里返回的共享盘文件路径。 +逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索共享盘 -> 前端拿到候选履历文件后继续走既有预览弹窗。 +""" +from __future__ import annotations + +import os +import re +import subprocess +import threading +import time +from dataclasses import dataclass + +from flask import current_app, has_app_context + +from app.core.config.settings import Config + + +_CONNECT_LOCK = threading.Lock() +_LAST_CONNECT_AT = 0.0 +_CONNECT_COOLDOWN_SECONDS = 30.0 + + +@dataclass(slots=True) +class AssetHistoryCandidate: + """资产履历候选文件。""" + + path: str + relative_path: str + name: str + actual_ext: str + size_bytes: int + modified_at: str + score: int + match_reason: str + + def to_dict(self) -> dict[str, object]: + return { + "name": self.name, + "path": self.path, + "relative_path": self.relative_path, + "actual_ext": self.actual_ext, + "size_bytes": self.size_bytes, + "modified_at": self.modified_at, + "match_reason": self.match_reason, + "url": self.path, + } + + +class FixedAssetHistoryService: + """ + 固资履历检索服务。 + + AI 触发时机: + - 当聊天结果里已经拿到了具体资产编号,用户点击“资产编号”想看履历时调用; + - 输入必须至少包含资产编号或资产名称中的一个; + - 输出只返回共享盘上可预览的候选文件,不直接拼接文件内容。 + """ + + HISTORY_FILE_EXTENSIONS = {".xls", ".xlsx", ".pdf", ".doc", ".docx", ".txt"} + + @classmethod + def _get_runtime_setting(cls, key: str, default: str = "") -> str: + if has_app_context(): + try: + value = current_app.config.get(key) + if value is not None: + return str(value) + except Exception: + pass + return str(getattr(Config, key, default) or default) + + @classmethod + def is_enabled(cls) -> bool: + return bool(cls.get_share_root()) + + @classmethod + def get_share_root(cls) -> str: + return cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_ROOT').strip() + + @classmethod + def search_history_files( + cls, + *, + asset_id: str, + asset_name: str = "", + limit: int | None = None, + ) -> list[dict[str, object]]: + """ + 按资产编号/资产名称检索履历文件。 + + [STEP 1] 先尝试建立共享盘访问权限,避免 Windows 服务账号没有提前挂载网络盘。 + [STEP 2] 优先用资产编号做全局文件名命中,确保定位到唯一设备履历。 + [STEP 3] 再用资产名称命中同名文件夹/文件,补足部分历史文件只按设备名称归档的情况。 + """ + asset_id_value = cls._normalize_keyword(asset_id) + asset_name_value = cls._normalize_keyword(asset_name) + if not asset_id_value and not asset_name_value: + return [] + + root = cls.get_share_root() + if not root: + return [] + if not os.path.exists(root): + cls._ensure_share_connected(root) + if not os.path.isdir(root): + return [] + + max_results = max( + 1, + min(int(limit or cls._get_runtime_setting('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or 20), 50), + ) + candidates: dict[str, AssetHistoryCandidate] = {} + + if asset_id_value: + for current_root, _dirs, files in os.walk(root): + for filename in files: + candidate = cls._build_candidate( + root=root, + file_path=os.path.join(current_root, filename), + asset_id=asset_id_value, + asset_name=asset_name_value, + match_reason="asset_id", + ) + if candidate: + cls._merge_candidate(candidates, candidate) + + folder_candidates = cls._find_matching_folders(root, asset_name_value) + for folder_path in folder_candidates: + for current_root, _dirs, files in os.walk(folder_path): + for filename in files: + candidate = cls._build_candidate( + root=root, + file_path=os.path.join(current_root, filename), + asset_id=asset_id_value, + asset_name=asset_name_value, + match_reason="asset_name_folder", + ) + if candidate: + cls._merge_candidate(candidates, candidate) + + if asset_name_value: + for entry in os.scandir(root): + if not entry.is_file(): + continue + candidate = cls._build_candidate( + root=root, + file_path=entry.path, + asset_id=asset_id_value, + asset_name=asset_name_value, + match_reason="asset_name_file", + ) + if candidate: + cls._merge_candidate(candidates, candidate) + + ordered = sorted( + candidates.values(), + key=lambda item: (-item.score, item.relative_path.lower(), item.name.lower()), + ) + return [item.to_dict() for item in ordered[:max_results]] + + @classmethod + def _merge_candidate( + cls, + existing: dict[str, AssetHistoryCandidate], + candidate: AssetHistoryCandidate, + ) -> None: + previous = existing.get(candidate.path) + if previous is None or candidate.score > previous.score: + existing[candidate.path] = candidate + + @classmethod + def _find_matching_folders(cls, root: str, asset_name: str) -> list[str]: + if not asset_name: + return [] + matches: list[str] = [] + for entry in os.scandir(root): + if not entry.is_dir(): + continue + normalized_folder = cls._normalize_keyword(entry.name) + if asset_name and asset_name in normalized_folder: + matches.append(entry.path) + return matches + + @classmethod + def _build_candidate( + cls, + *, + root: str, + file_path: str, + asset_id: str, + asset_name: str, + match_reason: str, + ) -> AssetHistoryCandidate | None: + if not os.path.isfile(file_path): + return None + ext = os.path.splitext(file_path)[1].strip().lower() + if ext and ext not in cls.HISTORY_FILE_EXTENSIONS: + return None + + filename = os.path.basename(file_path) + searchable_parts = [ + cls._normalize_keyword(filename), + cls._normalize_keyword(os.path.relpath(file_path, root)), + ] + searchable_text = " ".join(part for part in searchable_parts if part) + if not searchable_text: + return None + + if asset_id and asset_id not in searchable_text: + return None + if asset_name and asset_name not in searchable_text and match_reason != "asset_id": + return None + + score = cls._score_candidate( + searchable_text=searchable_text, + filename=cls._normalize_keyword(filename), + asset_id=asset_id, + asset_name=asset_name, + match_reason=match_reason, + ) + if score <= 0: + return None + + stat = os.stat(file_path) + return AssetHistoryCandidate( + path=file_path, + relative_path=os.path.relpath(file_path, root).replace("/", "\\"), + name=filename, + actual_ext=ext.lstrip("."), + size_bytes=int(stat.st_size), + modified_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stat.st_mtime)), + score=score, + match_reason=match_reason, + ) + + @classmethod + def _score_candidate( + cls, + *, + searchable_text: str, + filename: str, + asset_id: str, + asset_name: str, + match_reason: str, + ) -> int: + score = 0 + if asset_id: + if asset_id in filename: + score += 120 + elif asset_id in searchable_text: + score += 80 + if asset_name: + if asset_name in filename: + score += 60 + elif asset_name in searchable_text: + score += 40 + if "履历" in filename: + score += 20 + if match_reason == "asset_name_folder": + score += 10 + return score + + @classmethod + def _normalize_keyword(cls, value: str | None) -> str: + text = str(value or "").strip().lower() + if not text: + return "" + return re.sub(r"[\s\\/_\-()()【】\[\],。,;;::]+", "", text) + + @classmethod + def _ensure_share_connected(cls, root: str) -> None: + """ + 尝试用配置的账号密码建立共享盘会话。 + + 账号密码只从环境变量读取,避免把敏感信息写进仓库。 + """ + username = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_USERNAME').strip() + password = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_PASSWORD') + if not username or not password: + return + + share_root = cls._extract_server_share_root(root) + if not share_root: + return + + global _LAST_CONNECT_AT + now = time.time() + if now - _LAST_CONNECT_AT < _CONNECT_COOLDOWN_SECONDS: + return + + with _CONNECT_LOCK: + if time.time() - _LAST_CONNECT_AT < _CONNECT_COOLDOWN_SECONDS: + return + try: + subprocess.run( + [ + "net", + "use", + share_root, + password, + f"/user:{username}", + "/persistent:no", + ], + check=False, + capture_output=True, + text=True, + timeout=8, + ) + except Exception: + return + _LAST_CONNECT_AT = time.time() + + @staticmethod + def _extract_server_share_root(path_value: str) -> str: + normalized = str(path_value or "").strip().replace("/", "\\") + if not normalized.startswith("\\\\"): + return "" + parts = [part for part in normalized[2:].split("\\") if part] + if len(parts) < 2: + return "" + return f"\\\\{parts[0]}\\{parts[1]}" diff --git a/docs/funclist.md b/docs/funclist.md index c3289040..48d8e744 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -61,6 +61,7 @@ | 固资备注模糊检索 | 已实现 | 同步时生成 `备注` 与标准化备注,查询时作为结构化条件兜底 | | 固资本地快照查询 | 已实现 | `固资管理` Agent 优先查询 SQLite 最新快照,减少实时 ERP 压力 | | 固资导出文件 | 已实现 | 同步成功后生成 `FixedAssets_latest.xlsx`,供人工核查与留档 | +| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看 | ### F-01 本人假期查询 diff --git a/frontend/src/features/chat/api/chat.api.ts b/frontend/src/features/chat/api/chat.api.ts index dc4d8124..8ab3c44f 100644 --- a/frontend/src/features/chat/api/chat.api.ts +++ b/frontend/src/features/chat/api/chat.api.ts @@ -1,10 +1,11 @@ -/** +/** * features/chat/api/chat.api.ts * 聊天域 HTTP API:会话、消息、源文件、附件上传。 */ import { getAuthHeaders } from '@/shared/utils/auth'; import { requestJson } from '@/shared/api/client'; import type { + AssetHistorySearchResult, ChatCrossAgentHistoryItem, ChatMessage, ChatQueryPreviewPage, @@ -90,4 +91,17 @@ export const getChatQueryPreviewPage = ( return requestJson(`/api/chat/query-preview/${chatLogId}?${qs.toString()}`, auth()); }; +export const searchAssetHistoryFiles = ( + agentId: number, + query: { asset_id?: string; asset_name?: string; limit?: number }, +) => { + const qs = new URLSearchParams({ + agent_id: String(agentId), + }); + if (query.asset_id) qs.set('asset_id', query.asset_id); + if (query.asset_name) qs.set('asset_name', query.asset_name); + if (query.limit) qs.set('limit', String(query.limit)); + return requestJson(`/api/chat/asset-history/search?${qs.toString()}`, auth()); +}; + export type { ChatSessionItem, ChatCrossAgentHistoryItem }; diff --git a/frontend/src/features/chat/components/ChatAssetHistoryDialog.vue b/frontend/src/features/chat/components/ChatAssetHistoryDialog.vue new file mode 100644 index 00000000..ee5c4f2d --- /dev/null +++ b/frontend/src/features/chat/components/ChatAssetHistoryDialog.vue @@ -0,0 +1,91 @@ + + + diff --git a/frontend/src/features/chat/components/ChatQueryPreviewDialog.vue b/frontend/src/features/chat/components/ChatQueryPreviewDialog.vue index ea1c718f..f23ead3f 100644 --- a/frontend/src/features/chat/components/ChatQueryPreviewDialog.vue +++ b/frontend/src/features/chat/components/ChatQueryPreviewDialog.vue @@ -18,11 +18,29 @@ const props = defineProps<{ const emit = defineEmits<{ close: []; 'change-page': [delta: number]; + 'open-asset-history': [payload: { assetId: string; assetName: string }]; }>(); const totalPages = computed(() => Math.max(1, Math.ceil((props.state.total || 0) / (props.state.pageSize || 100))), ); +const assetIdColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产编号')); +const assetNameColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产名称')); + +function normalizeCellText(cell: unknown): string { + return String(cell ?? '').trim(); +} + +function canOpenAssetHistory(row: unknown[], cellIndex: number): boolean { + return cellIndex === assetIdColumnIndex.value && !!normalizeCellText(row[cellIndex]); +} + +function emitAssetHistory(row: unknown[]): void { + const assetId = normalizeCellText(row[assetIdColumnIndex.value]); + const assetName = assetNameColumnIndex.value >= 0 ? normalizeCellText(row[assetNameColumnIndex.value]) : ''; + if (!assetId) return; + emit('open-asset-history', { assetId, assetName }); +}