Merge branch 'dev' into hugo-shipping-notice
# Conflicts: # backend/app/services/maintenance_chat_service.py # backend/tests/test_maintenance_chat_service.py # frontend/src/features/chat/components/ChatViewContent.vue
This commit is contained in:
commit
2ce1aca023
25 files changed
+1609
-304
No files matched your search
@@ -9,6 +9,7 @@ backend/app/api/maintenance.py
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
@@ -21,6 +22,7 @@ from app.services.maintenance_ledger_service import (
|
||||
import_devices_from_excel,
|
||||
list_devices,
|
||||
update_device,
|
||||
_parse_date,
|
||||
)
|
||||
from app.services.maintenance_record_service import (
|
||||
build_records_import_template,
|
||||
@@ -58,6 +60,28 @@ def _require_ledger_admin():
|
||||
return user
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
"""
|
||||
从请求参数解析维修记录列表/导出共用的筛选条件。
|
||||
核心逻辑:兼容 snake_case 与 camelCase 报修日期参数;日期非法时抛出 ValidationError。
|
||||
"""
|
||||
report_date_from = _parse_date(
|
||||
request.args.get('report_date_from') or request.args.get('reportDateFrom'),
|
||||
'reportDateFrom',
|
||||
)
|
||||
report_date_to = _parse_date(
|
||||
request.args.get('report_date_to') or request.args.get('reportDateTo'),
|
||||
'reportDateTo',
|
||||
)
|
||||
return {
|
||||
'keyword': request.args.get('keyword'),
|
||||
'device_code': request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
'status': request.args.get('status'),
|
||||
'report_date_from': report_date_from,
|
||||
'report_date_to': report_date_to,
|
||||
}
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['GET'])
|
||||
def list_ledger_devices():
|
||||
"""查询设备台账列表,供 Agent 查询结果与右侧台账配置面板使用。"""
|
||||
@@ -121,10 +145,13 @@ def import_ledger_devices():
|
||||
def list_maintenance_records():
|
||||
"""查询设备维修记录,供 Agent 会话查询和结果卡片使用。"""
|
||||
_require_user()
|
||||
filters = _record_list_filters_from_request()
|
||||
result = list_records(
|
||||
keyword=request.args.get('keyword'),
|
||||
device_code=request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
status=request.args.get('status'),
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
@@ -142,10 +169,13 @@ def get_maintenance_record(record_id: int):
|
||||
def export_maintenance_records():
|
||||
"""按当前筛选条件导出设备维修记录 Excel。"""
|
||||
_require_ledger_admin()
|
||||
filters = _record_list_filters_from_request()
|
||||
data = build_records_export(
|
||||
keyword=request.args.get('keyword'),
|
||||
device_code=request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
status=request.args.get('status'),
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
)
|
||||
return send_file(
|
||||
BytesIO(data),
|
||||
|
||||
@@ -25,6 +25,7 @@ chat.py (/api/chat/completions)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
@@ -71,6 +72,66 @@ class DifyService:
|
||||
"video": {"mp4", "mov", "mpeg", "webm"},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _extract_workflow_failure_text(data: dict) -> str:
|
||||
"""
|
||||
从 Dify workflow_finished 失败事件里提取原始错误文本。
|
||||
AI 触发时机:Dify Tool/节点失败但 HTTP 仍为 200 时,用于日志留痕和用户友好提示转译。
|
||||
Args:
|
||||
data: Dify SSE 事件体。
|
||||
Returns:
|
||||
原始错误文本;没有失败信息时返回空字符串。
|
||||
"""
|
||||
if data.get("event") != "workflow_finished":
|
||||
return ""
|
||||
wf_data = data.get("data") if isinstance(data.get("data"), dict) else {}
|
||||
if str(wf_data.get("status") or "").lower() != "failed":
|
||||
return ""
|
||||
candidates = [
|
||||
data.get("message"),
|
||||
data.get("description"),
|
||||
data.get("error"),
|
||||
wf_data.get("message"),
|
||||
wf_data.get("description"),
|
||||
wf_data.get("error"),
|
||||
wf_data.get("errmsg"),
|
||||
]
|
||||
for candidate in candidates:
|
||||
if candidate is None:
|
||||
continue
|
||||
if isinstance(candidate, str) and candidate.strip():
|
||||
return candidate.strip()
|
||||
try:
|
||||
text = json.dumps(candidate, ensure_ascii=False, default=str)
|
||||
except Exception:
|
||||
text = str(candidate)
|
||||
if text.strip() and text.strip() != "null":
|
||||
return text.strip()
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _friendly_workflow_failure_message(raw_error: str) -> str:
|
||||
"""
|
||||
将 Dify/Tool 技术错误转成用户可读提示。
|
||||
Args:
|
||||
raw_error: Dify 返回的原始错误文本。
|
||||
Returns:
|
||||
面向用户展示的简短中文提示。
|
||||
"""
|
||||
text = str(raw_error or "")
|
||||
lower = text.lower()
|
||||
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
|
||||
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
|
||||
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
|
||||
return "设备维保查询服务暂时无法访问,请稍后重试或联系管理员检查工具授权。"
|
||||
if "ssrf" in lower or "blocked" in lower or "private or local network" in lower:
|
||||
return "设备维保查询服务暂时无法访问,请联系管理员检查工具网络访问配置。"
|
||||
if "failed to invoke tool" in lower or "tool" in lower:
|
||||
return "设备维保查询工具调用失败,请稍后重试;如持续失败请联系管理员。"
|
||||
if "maximum context length" in lower or "input_tokens" in lower:
|
||||
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
|
||||
return "设备维保助手暂时无法完成查询,请稍后重试。"
|
||||
|
||||
@staticmethod
|
||||
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if not isinstance(data, dict):
|
||||
@@ -944,6 +1005,22 @@ class DifyService:
|
||||
has_sent_answer = True
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
raw_workflow_error = DifyService._extract_workflow_failure_text(data)
|
||||
if raw_workflow_error:
|
||||
friendly_error = DifyService._friendly_workflow_failure_message(raw_workflow_error)
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[chat-stream] workflow failed request_id=%s agent_id=%s raw_error=%s",
|
||||
request_id,
|
||||
getattr(agent, 'id', None),
|
||||
raw_workflow_error,
|
||||
)
|
||||
data['message'] = friendly_error
|
||||
data['error'] = friendly_error
|
||||
if isinstance(data.get('data'), dict):
|
||||
data['data']['message'] = friendly_error
|
||||
data['data']['error'] = friendly_error
|
||||
|
||||
if event == 'workflow_finished' and not data.get('answer'):
|
||||
final_answer = build_final_answer_text(data, event)
|
||||
if final_answer:
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/maintenance_chat_service.py
|
||||
|
||||
用途:设备维保助手的会话查询直答服务,用于把设备编号/名称或上下文指代转换成设备台账卡片。
|
||||
依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、agent_registry.resolver、SQLAlchemy、SSE JSON 输出。
|
||||
逻辑:chat intent_routes/maintenance_chat 与 try_stream_chat 调用本服务;Agent 门控读 handler_config.intent_routes。
|
||||
逻辑:chat.py 先调用本服务尝试本地直答;识别到管理写入意图时返回固定引导文案;否则无法明确命中设备或记录时放行给 Dify。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,7 +23,16 @@ from app.services.maintenance_record_service import REPAIR_STATUS_LABELS, serial
|
||||
|
||||
MAINTENANCE_INTENT_ROUTE = 'maintenance_chat'
|
||||
MAINTENANCE_MESSAGE_TYPE = 'maintenance-device-result'
|
||||
MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE = (
|
||||
'该操作属于管理配置功能,请在设备维保助手底部点击“台账配置”或“登记维修”按钮进行操作。'
|
||||
'会话只处理查询和问答,不执行新增、修改、删除、导入、导出。'
|
||||
)
|
||||
REFERENCE_DEVICE_PATTERN = re.compile(r'(这个设备|這個設備|这台|這台|该设备|該設備|它|刚才那个|剛才那個|上一个设备|上一個設備|当前设备|當前設備)')
|
||||
RECORD_QUERY_PATTERN = re.compile(r'(维修|維修|报修|報修|故障|修复|修復|维修记录|維修記錄|维修历史|維修歷史|维修履历|維修履歷|记录|記錄|历史|歷史)')
|
||||
QUERY_HINT_PATTERN = re.compile(r'(查询|查詢|查看|检索|查一下|查下|最近|有哪些|是什么|多少|吗|嗎|么|麼|\?)')
|
||||
MANAGEMENT_WRITE_PATTERN = re.compile(
|
||||
r'(新增|新建|添加|修改|更新|编辑|編輯|删除|刪除|导入|導入|导出|導出|登记|登記|提交|配置|台账配置|台帳配置|设备配置|設備配置|报修|報修)'
|
||||
)
|
||||
|
||||
|
||||
def _agent_has_maintenance_chat_route(agent: Any) -> bool:
|
||||
@@ -164,6 +173,38 @@ def resolve_device_query_keyword(query: str, agent: Any, *, session_id: str | No
|
||||
return (keyword, 'explicit') if keyword else (None, 'none')
|
||||
|
||||
|
||||
def detect_query_mode(query: str) -> str:
|
||||
"""
|
||||
判断本轮维保查询应展示设备信息还是维修记录。
|
||||
AI 触发时机:本地直答生成卡片前调用,用于避免“查设备”和“查维修记录”渲染成同一张卡。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
Returns:
|
||||
records 表示维修记录查询;device 表示设备信息查询。
|
||||
"""
|
||||
return 'records' if RECORD_QUERY_PATTERN.search(_clean_text(query)) else 'device'
|
||||
|
||||
|
||||
def detect_management_write_intent(query: str) -> bool:
|
||||
"""
|
||||
判断用户是否在会话里尝试执行台账/维修记录的写入或管理配置动作。
|
||||
核心逻辑:出现新增、导入、删除等写入动词时拦截并引导到底部管理按钮;纯查询语句放行给本地直答或 Dify。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
Returns:
|
||||
True 表示应返回管理操作引导文案,不应继续走 Dify 写入流程。
|
||||
"""
|
||||
text = _clean_text(query)
|
||||
if not text or not MANAGEMENT_WRITE_PATTERN.search(text):
|
||||
return False
|
||||
if QUERY_HINT_PATTERN.search(text) and not re.search(
|
||||
r'(新增|新建|添加|修改|更新|编辑|編輯|删除|刪除|导入|導入|导出|導出|登记|登記|提交|配置|报修|報修)',
|
||||
text,
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _find_device(keyword: str) -> MaintenanceDevice | None:
|
||||
"""按设备编号优先,其次按设备名称模糊匹配查找单台设备。"""
|
||||
value = _clean_text(keyword)
|
||||
@@ -259,6 +300,7 @@ def _build_records_payload(keyword: str, records: list[MaintenanceRecord]) -> di
|
||||
status_counts[key] = status_counts.get(key, 0) + 1
|
||||
return {
|
||||
'source': 'maintenance_record_query',
|
||||
'queryMode': 'records',
|
||||
'matched': True,
|
||||
'keyword': keyword,
|
||||
'device': _build_record_device_snapshot(records[0]) if records else None,
|
||||
@@ -270,7 +312,6 @@ def _build_records_payload(keyword: str, records: list[MaintenanceRecord]) -> di
|
||||
'ledgerMatched': False,
|
||||
},
|
||||
'actions': [
|
||||
{'id': 'viewMaintenanceHistory', 'label': '查维修历史'},
|
||||
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
|
||||
],
|
||||
}
|
||||
@@ -293,6 +334,7 @@ def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, r
|
||||
status_counts[key] = status_counts.get(key, 0) + 1
|
||||
return {
|
||||
'source': 'maintenance_device_query',
|
||||
'queryMode': 'device',
|
||||
'matched': True,
|
||||
'device': serialize_device(device),
|
||||
'records': serialized_records,
|
||||
@@ -302,19 +344,19 @@ def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, r
|
||||
'statusLabels': REPAIR_STATUS_LABELS,
|
||||
},
|
||||
'actions': [
|
||||
{'id': 'viewMaintenanceHistory', 'label': '查维修历史'},
|
||||
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def build_device_query_result(keyword: str, *, include_records: bool = True, record_limit: int = 5) -> dict[str, Any]:
|
||||
def build_device_query_result(keyword: str, *, include_records: bool = True, record_limit: int = 5, query_mode: str = 'device') -> dict[str, Any]:
|
||||
"""
|
||||
查询设备台账并返回统一结构,供会话直答和 Dify Tool 共用。
|
||||
Args:
|
||||
keyword: 设备编号或设备名称。
|
||||
include_records: 是否附带最近维修记录。
|
||||
record_limit: 最近维修记录最大返回条数。
|
||||
query_mode: device 展示设备信息;records 展示维修记录。
|
||||
Returns:
|
||||
设备查询结果 payload。
|
||||
"""
|
||||
@@ -324,7 +366,38 @@ def build_device_query_result(keyword: str, *, include_records: bool = True, rec
|
||||
include_records,
|
||||
record_limit,
|
||||
)
|
||||
normalized_mode = 'records' if query_mode == 'records' else 'device'
|
||||
device = _find_device(keyword)
|
||||
if normalized_mode == 'records':
|
||||
records = _find_records(keyword, record_limit=record_limit) if include_records else []
|
||||
if records:
|
||||
current_app.logger.info('[maintenance-chat] records mode matched keyword=%s count=%s', keyword, len(records))
|
||||
payload = _build_records_payload(keyword, records)
|
||||
if device:
|
||||
payload['device'] = serialize_device(device)
|
||||
payload.setdefault('summary', {})['ledgerMatched'] = True
|
||||
return payload
|
||||
if device:
|
||||
payload = _build_payload(device, include_records=False, record_limit=0)
|
||||
payload['source'] = 'maintenance_record_query'
|
||||
payload['queryMode'] = 'records'
|
||||
payload['records'] = []
|
||||
payload['summary'] = {
|
||||
'recentRecordCount': 0,
|
||||
'statusCounts': {},
|
||||
'statusLabels': REPAIR_STATUS_LABELS,
|
||||
'ledgerMatched': True,
|
||||
}
|
||||
return payload
|
||||
current_app.logger.info('[maintenance-chat] no records matched keyword=%s', keyword)
|
||||
return {
|
||||
'source': 'maintenance_record_query',
|
||||
'queryMode': 'records',
|
||||
'matched': False,
|
||||
'keyword': keyword,
|
||||
'device': None,
|
||||
'records': [],
|
||||
}
|
||||
if not device:
|
||||
records = _find_records(keyword, record_limit=record_limit) if include_records else []
|
||||
if records:
|
||||
@@ -333,6 +406,7 @@ def build_device_query_result(keyword: str, *, include_records: bool = True, rec
|
||||
current_app.logger.info('[maintenance-chat] no device or records matched keyword=%s', keyword)
|
||||
return {
|
||||
'source': 'maintenance_device_query',
|
||||
'queryMode': 'device',
|
||||
'matched': False,
|
||||
'keyword': keyword,
|
||||
'device': None,
|
||||
@@ -428,10 +502,16 @@ def stream_chat(
|
||||
keyword_source,
|
||||
query,
|
||||
)
|
||||
result = result or build_device_query_result(keyword, include_records=True, record_limit=5)
|
||||
query_mode = detect_query_mode(query)
|
||||
result = result or build_device_query_result(
|
||||
keyword,
|
||||
include_records=query_mode == 'records',
|
||||
record_limit=10 if query_mode == 'records' else 0,
|
||||
query_mode=query_mode,
|
||||
)
|
||||
|
||||
if result.get('matched'):
|
||||
content = '已查询设备台账信息,下面是匹配结果。'
|
||||
content = '已查询设备信息,下面是匹配结果。'
|
||||
if result.get('source') == 'maintenance_record_query':
|
||||
content = '已查询设备维修记录,下面是匹配结果。'
|
||||
if keyword_source == 'context':
|
||||
@@ -439,7 +519,7 @@ def stream_chat(
|
||||
payload = result
|
||||
message_type = MAINTENANCE_MESSAGE_TYPE
|
||||
else:
|
||||
content = f'未找到与“{keyword or query}”匹配的设备台账信息,请检查设备编号或设备名称。'
|
||||
content = f'未找到与“{keyword or query}”匹配的设备信息,请检查设备编号或设备名称。'
|
||||
payload = result
|
||||
message_type = 'text'
|
||||
|
||||
@@ -489,6 +569,69 @@ def stream_chat(
|
||||
}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def stream_management_redirect(
|
||||
query: str,
|
||||
user: Any,
|
||||
agent: Any,
|
||||
conversation_id: str | None = None,
|
||||
session_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> Iterator[str]:
|
||||
"""
|
||||
返回管理配置类操作的统一引导文案,阻止会话内直接执行写入动作。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
user: 当前用户代理对象。
|
||||
agent: 当前 Agent 代理对象。
|
||||
conversation_id: 外部会话 ID。
|
||||
session_id: 本地会话 ID。
|
||||
request_id: 当前请求 ID。
|
||||
Yields:
|
||||
SSE data 帧。
|
||||
"""
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or session_id or f'maintenance_{int(time.time())}'
|
||||
content = MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE
|
||||
current_app.logger.info(
|
||||
'[maintenance-chat] management redirect request_id=%s user_id=%s agent_id=%s query=%s',
|
||||
request_id,
|
||||
getattr(user, 'id', None),
|
||||
getattr(agent, 'id', None),
|
||||
query,
|
||||
)
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': content}, ensure_ascii=False)}\n\n"
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=getattr(user, 'id', None),
|
||||
agent_id=getattr(agent, 'id', None),
|
||||
conversation_id=final_conversation_id,
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
answer=content,
|
||||
tokens_used=0,
|
||||
latency=int((time.time() - start_time) * 1000),
|
||||
message_type='text',
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[maintenance-chat] failed to log management redirect: %s', exc)
|
||||
db.session.rollback()
|
||||
|
||||
yield f"data: {json.dumps({
|
||||
'event': 'message_end',
|
||||
'answer': content,
|
||||
'replace_answer': True,
|
||||
'type': 'text',
|
||||
'chat_log_id': chat_log_id,
|
||||
'conversation_id': final_conversation_id,
|
||||
'metadata': {'source': 'maintenance_management_redirect'},
|
||||
}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def try_stream_chat(
|
||||
query: str,
|
||||
user: Any,
|
||||
@@ -510,6 +653,17 @@ def try_stream_chat(
|
||||
Returns:
|
||||
SSE 生成器;返回 None 表示本地无法处理,应继续走 Dify。
|
||||
"""
|
||||
if not is_maintenance_chat_agent(agent):
|
||||
return None
|
||||
if detect_management_write_intent(query):
|
||||
return stream_management_redirect(
|
||||
query,
|
||||
user,
|
||||
agent,
|
||||
conversation_id,
|
||||
session_id=session_id,
|
||||
request_id=request_id,
|
||||
)
|
||||
keyword, keyword_source = resolve_device_query_keyword(query, agent, session_id=session_id)
|
||||
if not keyword:
|
||||
current_app.logger.info(
|
||||
@@ -520,7 +674,13 @@ def try_stream_chat(
|
||||
query,
|
||||
)
|
||||
return None
|
||||
result = build_device_query_result(keyword, include_records=True, record_limit=5)
|
||||
query_mode = detect_query_mode(query)
|
||||
result = build_device_query_result(
|
||||
keyword,
|
||||
include_records=query_mode == 'records',
|
||||
record_limit=10 if query_mode == 'records' else 0,
|
||||
query_mode=query_mode,
|
||||
)
|
||||
if not result.get('matched'):
|
||||
current_app.logger.info(
|
||||
'[maintenance-chat] bypass local unmatched request_id=%s keyword=%s keyword_source=%s query=%s',
|
||||
@@ -548,5 +708,7 @@ class MaintenanceChatService:
|
||||
|
||||
supports = staticmethod(supports)
|
||||
can_attempt = staticmethod(can_attempt)
|
||||
detect_management_write_intent = staticmethod(detect_management_write_intent)
|
||||
stream_management_redirect = staticmethod(stream_management_redirect)
|
||||
stream_chat = staticmethod(stream_chat)
|
||||
try_stream_chat = staticmethod(try_stream_chat)
|
||||
@@ -25,6 +25,8 @@ from app.path_utils import backend_dir
|
||||
from app.services.maintenance_ledger_service import _load_import_workbook, _operator_name, _parse_date, _write_audit
|
||||
|
||||
REPAIR_STATUS_VALUES = {'pending', 'processing', 'done', 'cancelled'}
|
||||
REPAIR_STATUS_FILTER_ACTIVE = 'active'
|
||||
ACTIVE_REPAIR_STATUSES = ('pending', 'processing')
|
||||
REPAIR_STATUS_LABELS = {
|
||||
'pending': '待维修',
|
||||
'processing': '维修中',
|
||||
@@ -146,16 +148,60 @@ def _normalize_payload(data: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _get_required_device(device_code: str) -> MaintenanceDevice:
|
||||
"""
|
||||
按设备编号读取台账设备,维修记录写入前必须命中。
|
||||
Args:
|
||||
device_code: 维修记录表单里的设备编号。
|
||||
Returns:
|
||||
已存在的设备台账记录。
|
||||
Raises:
|
||||
ValidationError: 设备编号不存在于台账,禁止新增或更新维修记录。
|
||||
"""
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=device_code).first()
|
||||
if not device:
|
||||
raise ValidationError('设备不存在于台账中,不能添加维修记录', details={'deviceCode': device_code})
|
||||
return device
|
||||
|
||||
|
||||
def _apply_device_snapshot(values: dict[str, Any], device: MaintenanceDevice) -> None:
|
||||
"""
|
||||
将设备台账快照写入维修记录,保证记录归属和展示字段一致。
|
||||
Args:
|
||||
values: 待写入 MaintenanceRecord 的字段字典。
|
||||
device: 已校验存在的设备台账记录。
|
||||
"""
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def list_records(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
device_code: str | None = None,
|
||||
status: str | None = None,
|
||||
report_date_from: date | None = None,
|
||||
report_date_to: date | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""分页查询维修记录。"""
|
||||
query = _records_query(keyword=keyword, device_code=device_code, status=status)
|
||||
"""
|
||||
分页查询维修记录。
|
||||
核心逻辑:复用 _records_query 构造筛选;status=active 表示待维修+维修中;报修日期区间可选。
|
||||
"""
|
||||
query = _records_query(
|
||||
keyword=keyword,
|
||||
device_code=device_code,
|
||||
status=status,
|
||||
report_date_from=report_date_from,
|
||||
report_date_to=report_date_to,
|
||||
)
|
||||
total = query.count()
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(200, page_size))
|
||||
@@ -168,13 +214,30 @@ def list_records(
|
||||
return {'items': [serialize_record(item) for item in items], 'total': total, 'page': page, 'pageSize': page_size}
|
||||
|
||||
|
||||
def _records_query(*, keyword: str | None = None, device_code: str | None = None, status: str | None = None):
|
||||
"""构造维修记录查询,供列表和导出复用。"""
|
||||
def _records_query(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
device_code: str | None = None,
|
||||
status: str | None = None,
|
||||
report_date_from: date | None = None,
|
||||
report_date_to: date | None = None,
|
||||
):
|
||||
"""
|
||||
构造维修记录查询,供列表和导出复用。
|
||||
核心逻辑:status=active 映射为 pending+processing;report_date_from/to 按报修日期闭区间过滤。
|
||||
"""
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
if device_code:
|
||||
query = query.filter(MaintenanceRecord.device_code == device_code)
|
||||
if status:
|
||||
status = _clean_text(status)
|
||||
if status == REPAIR_STATUS_FILTER_ACTIVE:
|
||||
query = query.filter(MaintenanceRecord.repair_status.in_(ACTIVE_REPAIR_STATUSES))
|
||||
elif status in REPAIR_STATUS_VALUES:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
if report_date_from:
|
||||
query = query.filter(MaintenanceRecord.report_date >= report_date_from)
|
||||
if report_date_to:
|
||||
query = query.filter(MaintenanceRecord.report_date <= report_date_to)
|
||||
keyword = _clean_text(keyword)
|
||||
if keyword:
|
||||
like = f'%{keyword}%'
|
||||
@@ -331,10 +394,23 @@ def _fill_history_sheet(ws, records: list[MaintenanceRecord]) -> None:
|
||||
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
||||
|
||||
|
||||
def build_records_export(*, keyword: str | None = None, device_code: str | None = None, status: str | None = None) -> bytes:
|
||||
"""按设备维修保养履历模板导出维修记录 Excel。"""
|
||||
def build_records_export(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
device_code: str | None = None,
|
||||
status: str | None = None,
|
||||
report_date_from: date | None = None,
|
||||
report_date_to: date | None = None,
|
||||
) -> bytes:
|
||||
"""按设备维修保养履历模板导出维修记录 Excel,筛选条件与列表查询保持一致。"""
|
||||
rows = (
|
||||
_records_query(keyword=keyword, device_code=device_code, status=status)
|
||||
_records_query(
|
||||
keyword=keyword,
|
||||
device_code=device_code,
|
||||
status=status,
|
||||
report_date_from=report_date_from,
|
||||
report_date_to=report_date_to,
|
||||
)
|
||||
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
|
||||
.limit(5000)
|
||||
.all()
|
||||
@@ -394,9 +470,8 @@ def _parse_history_pair_value(text: str | None, label: str) -> str | None:
|
||||
return compact_raw[len(compact_label):].strip(' ::')
|
||||
return raw
|
||||
|
||||
|
||||
def _parse_history_date(value: Any) -> date | None:
|
||||
"""解析履历模板中的日期,兼容 Excel 序列号和常规日期字符串。"""
|
||||
"""Parse dates from legacy maintenance history templates."""
|
||||
if isinstance(value, (int, float)):
|
||||
try:
|
||||
import xlrd
|
||||
@@ -407,6 +482,28 @@ def _parse_history_date(value: Any) -> date | None:
|
||||
return _parse_date(value, 'repairDate')
|
||||
|
||||
|
||||
def _parse_history_row_date(value: Any, *, row_no: int, label: str) -> date | None:
|
||||
"""
|
||||
Parse a date cell in a history row and convert backend validation text into an import-friendly row error.
|
||||
Args:
|
||||
value: Raw worksheet cell value.
|
||||
row_no: Excel row number, shown to users for correction.
|
||||
label: User-facing date field label.
|
||||
Returns:
|
||||
Parsed date or None.
|
||||
Raises:
|
||||
ValidationError: The date is not a supported format.
|
||||
"""
|
||||
try:
|
||||
return _parse_history_date(value)
|
||||
except ValidationError as exc:
|
||||
text = str(value or '').strip() or '-'
|
||||
raise ValidationError(
|
||||
f'第 {row_no} 行{label}格式不正确:{text},请改为 YYYY-MM-DD 或 YYYY/MM/DD',
|
||||
details={'row': row_no, 'field': label, 'value': text},
|
||||
) from exc
|
||||
|
||||
|
||||
def _is_history_template(ws: Any) -> bool:
|
||||
"""判断工作表是否为设备维修保养履历模板。"""
|
||||
device_code = _find_history_device_code(ws)
|
||||
@@ -478,8 +575,8 @@ def _history_record_payloads(ws: Any) -> list[dict[str, Any]]:
|
||||
continue
|
||||
if not fault_description and not repair_description:
|
||||
continue
|
||||
report_date = _parse_history_date(raw_report_date) or date.today()
|
||||
repair_date = _parse_history_date(raw_repair_date) or report_date
|
||||
report_date = _parse_history_row_date(raw_report_date, row_no=row_no, label='报修日期') or date.today()
|
||||
repair_date = _parse_history_row_date(raw_repair_date, row_no=row_no, label='维修日期') or report_date
|
||||
payloads.append(
|
||||
{
|
||||
'device_code': device_code,
|
||||
@@ -543,16 +640,8 @@ def import_records_from_excel(file_obj: Any, *, operator: Any | None = None, req
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
values = _normalize_payload(raw)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
device = _get_required_device(values['device_code'])
|
||||
_apply_device_snapshot(values, device)
|
||||
record = MaintenanceRecord(**values, created_by=operator_name, updated_by=operator_name)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
@@ -588,28 +677,13 @@ def _import_history_records(ws: Any, *, operator: Any | None = None, request_id:
|
||||
operator_name = _operator_name(operator)
|
||||
for raw in payloads:
|
||||
row_no = raw.pop('_row_no', None)
|
||||
device_name = raw.pop('_device_name', None)
|
||||
model_spec = raw.pop('_model_spec', None)
|
||||
raw.pop('_device_name', None)
|
||||
raw.pop('_model_spec', None)
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
values = _normalize_payload(raw)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
else:
|
||||
values.update(
|
||||
{
|
||||
'device_name': device_name,
|
||||
'model_spec': model_spec,
|
||||
}
|
||||
)
|
||||
device = _get_required_device(values['device_code'])
|
||||
_apply_device_snapshot(values, device)
|
||||
record = MaintenanceRecord(**values, created_by=operator_name, updated_by=operator_name)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
@@ -641,16 +715,8 @@ def get_record(record_id: int) -> dict[str, Any]:
|
||||
def create_record(data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""新增维修记录,并写入审计日志。"""
|
||||
values = _normalize_payload(data)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
device = _get_required_device(values['device_code'])
|
||||
_apply_device_snapshot(values, device)
|
||||
operator_name = _operator_name(operator)
|
||||
record = MaintenanceRecord(**values, created_by=operator_name, updated_by=operator_name)
|
||||
db.session.add(record)
|
||||
@@ -675,15 +741,8 @@ def update_record(record_id: int, data: dict[str, Any], *, operator: Any | None
|
||||
raise NotFoundError('Maintenance record not found')
|
||||
before = _record_to_audit_dict(record)
|
||||
values = _normalize_payload(data)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id if device else None,
|
||||
'device_name': device.device_name if device else None,
|
||||
'model_spec': device.model_spec if device else None,
|
||||
'install_location': device.install_location if device else None,
|
||||
}
|
||||
)
|
||||
device = _get_required_device(values['device_code'])
|
||||
_apply_device_snapshot(values, device)
|
||||
for key, value in values.items():
|
||||
setattr(record, key, value)
|
||||
operator_name = _operator_name(operator)
|
||||
|
||||
@@ -10,6 +10,8 @@ from app import db
|
||||
from app.models import Agent, ChatLog, MaintenanceDevice, User
|
||||
from app.services.maintenance_chat_service import (
|
||||
MAINTENANCE_MESSAGE_TYPE,
|
||||
MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE,
|
||||
detect_management_write_intent,
|
||||
resolve_device_query_keyword,
|
||||
try_stream_chat,
|
||||
)
|
||||
@@ -132,3 +134,28 @@ def test_resolve_context_device_works_for_custom_agent_name_with_intent_route(ap
|
||||
|
||||
assert keyword == 'A070700002'
|
||||
assert source == 'context'
|
||||
|
||||
|
||||
def test_detect_management_write_intent(app):
|
||||
"""断言新增、导入等写入意图会被识别,纯查询语句不会误判。"""
|
||||
assert detect_management_write_intent('新增设备 A070700001') is True
|
||||
assert detect_management_write_intent('导入设备台账 Excel') is True
|
||||
assert detect_management_write_intent('A070700001 的维修记录') is False
|
||||
assert detect_management_write_intent('查询 A070700001 最近维修记录') is False
|
||||
|
||||
|
||||
def test_try_stream_chat_redirects_management_write_intent(app):
|
||||
"""断言管理写入类问题由本地返回引导文案,不再交给 Dify。"""
|
||||
user, agent = _create_user_and_agent()
|
||||
|
||||
redirect_stream = try_stream_chat(
|
||||
'新增一条维修记录,设备 A070700001,线断了',
|
||||
user,
|
||||
agent,
|
||||
session_id='session-maintenance-3',
|
||||
request_id='req-redirect',
|
||||
)
|
||||
|
||||
assert redirect_stream is not None
|
||||
frames = list(redirect_stream)
|
||||
assert any(MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE in frame for frame in frames)
|
||||
Reference in new issue
Block a user