feat(chat-fixed-assets): 支持资产履历直达预览并优化 Excel 预览体验
This commit is contained in:
1 parent
1164ae2e3c
commit
56b6ea06a8
14 files changed
+1051
-48
No files matched your search
+118
-2
@@ -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():
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -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]}"
|
||||
Reference in new issue
Block a user