Merge branch 'dev' of https://gitee.com/justop/hxops into dev

This commit is contained in:
sophie committed 2026-07-13 14:35:59 +08:00
commit 1ee4c69dee
9 files changed
+154 -125

No files matched your search

+7 -1
View File
@@ -85,6 +85,12 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+6
View File
@@ -118,6 +118,12 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
+47 -80
View File
@@ -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,
+1
View File
@@ -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')
+78 -23
View File
@@ -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:
+8
View File
@@ -257,6 +257,14 @@ backend/data/fixed_assets/
这样可避免同步失败导致固资查询整体不可用。
### 7.4 资产履历共享盘访问约定
固资聊天结果中的“资产编号”点击后,会走 `backend/app/services/fixed_asset_history.py` 检索履历文件,并经 `api/chat.py` 的预览代理读取二进制内容。为兼容不同部署环境,履历目录访问遵循以下约定:
- **Windows 本地开发环境**:可直接使用 `FIXED_ASSET_HISTORY_SHARE_ROOT=\\\\server\\share\\...` 访问 UNC 共享盘。
- **Linux 测试/生产环境**:应先由宿主机或容器把 SMB 共享盘挂载到本地目录,再配置 `FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/...`;运行时优先使用 `LOCAL_ROOT`,不依赖 `net use`。
- **预览安全限制**:`/api/chat/preview-file-raw` 只允许读取 `PLM_PREVIEW_SHARE_ROOT`、`FIXED_ASSET_HISTORY_SHARE_ROOT`、`FIXED_ASSET_HISTORY_LOCAL_ROOT` 这三类受信根目录下的文件路径,避免任意本地文件被前端透传读取。
---
## 8. 定时任务设计
+1 -1
View File
@@ -113,7 +113,7 @@
| 固资本地快照查询 | 已实现 | `固资管理` Agent 优先查询 SQLite 最新快照,减少实时 ERP 压力 |
| 固资导出文件 | 已实现 | 同步成功后生成 `FixedAssets_latest.xlsx`,供人工核查与留档 |
| 固资快照技术方案 | 已文档化 | 见 [docs/features/fixed-assets/technical.md](features/fixed-assets/technical.md) |
| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看 |
| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看;Windows 本地可直接访问 UNC 共享盘,Linux 测试/生产环境支持通过 `FIXED_ASSET_HISTORY_LOCAL_ROOT` 读取已挂载目录 |
### F-01 本人假期查询
@@ -28,6 +28,12 @@ function normalizeAssetHistoryErrorMessage(message: string): string {
if (lowerCaseMessage.includes('asset history share is not configured')) {
return '当前系统暂未配置资产履历文件目录,暂时无法查看履历,请联系管理员处理。';
}
if (lowerCaseMessage.includes('asset history share is unreachable')) {
return '当前环境暂时无法访问资产履历共享盘,请联系管理员检查测试环境共享盘挂载或访问权限。';
}
if (lowerCaseMessage.includes('asset history share is invalid')) {
return '当前环境的资产履历目录配置无效,请联系管理员检查共享盘目录配置。';
}
return normalizedMessage || '检索资产履历失败';
}
@@ -386,26 +386,6 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const target = event.target as HTMLElement | null;
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
const rawHref = anchor?.getAttribute('href') || '';
// #region debug-point A:asset-history-anchor-click
if (rawHref.startsWith('#asset-history?')) {
fetch('http://127.0.0.1:7777/event', {
method: 'POST',
body: JSON.stringify({
sessionId: 'asset-history-click',
runId: 'pre-fix',
hypothesisId: 'A',
location: 'frontend/useChatPageMarkdown.ts',
msg: '[DEBUG] asset history anchor clicked',
data: {
href: rawHref,
tagName: target?.tagName || '',
anchorText: String(anchor?.textContent || '').trim(),
},
ts: Date.now(),
}),
}).catch(() => {});
}
// #endregion
if (rawHref.startsWith('#asset-history?')) {
event.preventDefault();
const params = new URLSearchParams(rawHref.slice('#asset-history?'.length));