Merge branch 'dev' of https://gitee.com/justop/hxops into dev
This commit is contained in:
commit
1ee4c69dee
9 files changed
+154
-125
No files matched your search
+47
-80
@@ -8,6 +8,8 @@ backend/app/api/chat.py
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
@@ -226,26 +228,60 @@ def _update_chat_session(
|
||||
return session
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or '').strip().strip('"').replace('/', '\\')
|
||||
if normalized.startswith('\\\\'):
|
||||
return '\\\\' + normalized[2:].rstrip('\\')
|
||||
return normalized.rstrip('\\')
|
||||
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
|
||||
"""
|
||||
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
|
||||
|
||||
Returns:
|
||||
(path_kind, normalized_path)
|
||||
- path_kind: 'windows' | 'posix' | ''
|
||||
- normalized_path: 归一化后的绝对路径文本
|
||||
"""
|
||||
raw_value = str(path_value or '').strip().strip('"')
|
||||
if not raw_value:
|
||||
return ('', '')
|
||||
if raw_value.startswith('\\\\'):
|
||||
normalized = raw_value.replace('/', '\\')
|
||||
normalized = '\\\\' + normalized[2:].rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
|
||||
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if raw_value.startswith('/'):
|
||||
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
|
||||
return ('posix', normalized.rstrip('/'))
|
||||
return ('', '')
|
||||
|
||||
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
|
||||
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
|
||||
if not normalized_target or not normalized_root or target_kind != root_kind:
|
||||
return False
|
||||
if target_kind == 'windows':
|
||||
target_lower = normalized_target.lower()
|
||||
root_lower = normalized_root.lower()
|
||||
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
|
||||
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
normalized_target = _normalize_windows_share_path(target_url)
|
||||
if not normalized_target.startswith('\\\\'):
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
|
||||
if not normalized_target:
|
||||
return False
|
||||
history_share_root = ''
|
||||
history_local_root = ''
|
||||
if has_request_context():
|
||||
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
|
||||
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
|
||||
if not history_share_root:
|
||||
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
|
||||
if not history_local_root:
|
||||
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
|
||||
roots = [
|
||||
_normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT),
|
||||
_normalize_windows_share_path(history_share_root),
|
||||
PLM_PREVIEW_SHARE_ROOT,
|
||||
history_share_root,
|
||||
history_local_root,
|
||||
]
|
||||
return any(root and normalized_target.lower().startswith(root.lower()) for root in roots)
|
||||
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
@@ -300,7 +336,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
if _is_allowed_share_path(file_url):
|
||||
normalized_path = _normalize_windows_share_path(file_url)
|
||||
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
return (None, None, ('source file not found', 404))
|
||||
@@ -1166,31 +1202,6 @@ def search_asset_history_files():
|
||||
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')
|
||||
@@ -1198,27 +1209,6 @@ def search_asset_history_files():
|
||||
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(
|
||||
@@ -1226,29 +1216,6 @@ def search_asset_history_files():
|
||||
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,
|
||||
|
||||
@@ -343,6 +343,7 @@ 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_LOCAL_ROOT = os.getenv('FIXED_ASSET_HISTORY_LOCAL_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')
|
||||
|
||||
@@ -3,7 +3,8 @@ backend/app/services/fixed_asset_history.py
|
||||
|
||||
用途:为固资管理提供“资产履历”共享盘检索能力,按资产编号/资产名称匹配履历文件。
|
||||
依赖:app.core.config.settings.Config、chat.py 里的预览代理会复用这里返回的共享盘文件路径。
|
||||
逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索共享盘 -> 前端拿到候选履历文件后继续走既有预览弹窗。
|
||||
逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索履历目录 -> 前端拿到候选履历文件后继续走既有预览弹窗;
|
||||
支持 Windows 直接访问 UNC 共享盘,也支持 Linux 通过本地挂载目录访问同一批履历文件。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,6 +18,7 @@ from dataclasses import dataclass
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
|
||||
|
||||
_CONNECT_LOCK = threading.Lock()
|
||||
@@ -75,12 +77,64 @@ class FixedAssetHistoryService:
|
||||
|
||||
@classmethod
|
||||
def is_enabled(cls) -> bool:
|
||||
return bool(cls.get_share_root())
|
||||
return bool(cls.get_local_root() or cls.get_share_root())
|
||||
|
||||
@classmethod
|
||||
def get_share_root(cls) -> str:
|
||||
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_ROOT').strip()
|
||||
|
||||
@classmethod
|
||||
def get_local_root(cls) -> str:
|
||||
return cls._get_runtime_setting('FIXED_ASSET_HISTORY_LOCAL_ROOT').strip()
|
||||
|
||||
@classmethod
|
||||
def get_access_root(cls) -> str:
|
||||
"""
|
||||
返回当前环境实际用于检索/预览履历文件的可访问根目录。
|
||||
|
||||
AI 触发时机:
|
||||
- Windows 本地开发环境通常直接访问 UNC 共享盘;
|
||||
- Linux 测试/生产环境通常通过宿主机或容器挂载目录访问共享盘;
|
||||
- 因此优先读取 `FIXED_ASSET_HISTORY_LOCAL_ROOT`,未配置时再回退到原共享盘根目录。
|
||||
"""
|
||||
return cls.get_local_root() or cls.get_share_root()
|
||||
|
||||
@classmethod
|
||||
def _resolve_share_root(cls) -> str:
|
||||
"""
|
||||
解析并校验资产履历共享盘根目录。
|
||||
|
||||
AI 触发时机:当用户点击资产编号查询履历时,必须先确认后端能访问配置的共享盘;
|
||||
若测试/生产环境未挂载成功,不应误报成“未找到履历文件”,而应返回更准确的环境异常提示。
|
||||
"""
|
||||
root = cls.get_access_root()
|
||||
if not root:
|
||||
raise ServiceUnavailableError('asset history share is not configured')
|
||||
if not os.path.exists(root):
|
||||
cls._ensure_share_connected(root)
|
||||
if not os.path.exists(root):
|
||||
raise ServiceUnavailableError('asset history share is unreachable')
|
||||
if not os.path.isdir(root):
|
||||
raise ServiceUnavailableError('asset history share is invalid')
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _build_asset_id_variants(cls, asset_id: str) -> tuple[str, ...]:
|
||||
"""
|
||||
生成资产编号匹配变体。
|
||||
|
||||
AI 触发时机:测试/生产环境的共享盘文件名可能出现“带前缀 A”与“不带前缀”两种写法;
|
||||
这里统一构造多个匹配 key,避免因为命名差一个前缀就查不到履历。
|
||||
"""
|
||||
normalized = cls._normalize_keyword(asset_id)
|
||||
if not normalized:
|
||||
return tuple()
|
||||
variants = [normalized]
|
||||
stripped = re.sub(r'^[a-z]+', '', normalized)
|
||||
if stripped and stripped not in variants:
|
||||
variants.append(stripped)
|
||||
return tuple(variants)
|
||||
|
||||
@classmethod
|
||||
def search_history_files(
|
||||
cls,
|
||||
@@ -97,17 +151,12 @@ class FixedAssetHistoryService:
|
||||
[STEP 3] 再用资产名称命中同名文件夹/文件,补足部分历史文件只按设备名称归档的情况。
|
||||
"""
|
||||
asset_id_value = cls._normalize_keyword(asset_id)
|
||||
asset_id_variants = cls._build_asset_id_variants(asset_id)
|
||||
asset_name_value = cls._normalize_keyword(asset_name)
|
||||
if not asset_id_value and not asset_name_value:
|
||||
if not asset_id_variants 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 []
|
||||
root = cls._resolve_share_root()
|
||||
|
||||
max_results = max(
|
||||
1,
|
||||
@@ -115,13 +164,13 @@ class FixedAssetHistoryService:
|
||||
)
|
||||
candidates: dict[str, AssetHistoryCandidate] = {}
|
||||
|
||||
if asset_id_value:
|
||||
if asset_id_variants:
|
||||
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_id_variants=asset_id_variants,
|
||||
asset_name=asset_name_value,
|
||||
match_reason="asset_id",
|
||||
)
|
||||
@@ -135,7 +184,7 @@ class FixedAssetHistoryService:
|
||||
candidate = cls._build_candidate(
|
||||
root=root,
|
||||
file_path=os.path.join(current_root, filename),
|
||||
asset_id=asset_id_value,
|
||||
asset_id_variants=asset_id_variants,
|
||||
asset_name=asset_name_value,
|
||||
match_reason="asset_name_folder",
|
||||
)
|
||||
@@ -149,7 +198,7 @@ class FixedAssetHistoryService:
|
||||
candidate = cls._build_candidate(
|
||||
root=root,
|
||||
file_path=entry.path,
|
||||
asset_id=asset_id_value,
|
||||
asset_id_variants=asset_id_variants,
|
||||
asset_name=asset_name_value,
|
||||
match_reason="asset_name_file",
|
||||
)
|
||||
@@ -191,7 +240,7 @@ class FixedAssetHistoryService:
|
||||
*,
|
||||
root: str,
|
||||
file_path: str,
|
||||
asset_id: str,
|
||||
asset_id_variants: tuple[str, ...],
|
||||
asset_name: str,
|
||||
match_reason: str,
|
||||
) -> AssetHistoryCandidate | None:
|
||||
@@ -210,7 +259,7 @@ class FixedAssetHistoryService:
|
||||
if not searchable_text:
|
||||
return None
|
||||
|
||||
if asset_id and asset_id not in searchable_text:
|
||||
if asset_id_variants and not any(variant in searchable_text for variant in asset_id_variants):
|
||||
return None
|
||||
if asset_name and asset_name not in searchable_text and match_reason != "asset_id":
|
||||
return None
|
||||
@@ -218,7 +267,7 @@ class FixedAssetHistoryService:
|
||||
score = cls._score_candidate(
|
||||
searchable_text=searchable_text,
|
||||
filename=cls._normalize_keyword(filename),
|
||||
asset_id=asset_id,
|
||||
asset_id_variants=asset_id_variants,
|
||||
asset_name=asset_name,
|
||||
match_reason=match_reason,
|
||||
)
|
||||
@@ -243,16 +292,19 @@ class FixedAssetHistoryService:
|
||||
*,
|
||||
searchable_text: str,
|
||||
filename: str,
|
||||
asset_id: str,
|
||||
asset_id_variants: tuple[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_id_variants:
|
||||
for index, asset_id in enumerate(asset_id_variants):
|
||||
exact_bonus = 120 if index == 0 else 100
|
||||
fuzzy_bonus = 80 if index == 0 else 60
|
||||
if asset_id in filename:
|
||||
score = max(score, exact_bonus)
|
||||
elif asset_id in searchable_text:
|
||||
score = max(score, fuzzy_bonus)
|
||||
if asset_name:
|
||||
if asset_name in filename:
|
||||
score += 60
|
||||
@@ -277,7 +329,10 @@ class FixedAssetHistoryService:
|
||||
尝试用配置的账号密码建立共享盘会话。
|
||||
|
||||
账号密码只从环境变量读取,避免把敏感信息写进仓库。
|
||||
Linux 测试/生产环境应优先通过挂载目录访问共享盘,此处仅作为 Windows UNC 共享盘的兜底建连。
|
||||
"""
|
||||
if os.name != 'nt':
|
||||
return
|
||||
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:
|
||||
|
||||
Reference in new issue
Block a user