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:
commit
fc694a8f43
55 files changed
+2107
-192
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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(
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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"
|
||||
@@ -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'
|
||||
Reference in new issue
Block a user