diff --git a/.dbg/retry-rpa-no-request.env b/.dbg/retry-rpa-no-request.env new file mode 100644 index 00000000..b2e50e0d --- /dev/null +++ b/.dbg/retry-rpa-no-request.env @@ -0,0 +1,2 @@ +DEBUG_SERVER_URL=http://127.0.0.1:7778/event +DEBUG_SESSION_ID=retry-rpa-no-request diff --git a/.env.prod b/.env.prod index 8a69d170..3ef20958 100644 --- a/.env.prod +++ b/.env.prod @@ -58,5 +58,5 @@ MINIO_SECURE=false # MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问 MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000 -# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致) +# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致) HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890 \ No newline at end of file diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index 453fa033..808ca7b9 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -24,6 +24,7 @@ def register_blueprints(app: Flask) -> None: from app.api.user import user_bp from app.api.integration import integration_bp from app.api.internal_jobs import internal_jobs_bp + from app.api.maintenance import maintenance_bp from app.api.speech import speech_bp from app.api.training import training_admin_bp, training_user_bp from app.api.agent_runtime_context_tools import agent_runtime_context_bp @@ -37,7 +38,7 @@ def register_blueprints(app: Flask) -> None: workspace_schedule_bp, workspace_shipping_notice_bp, ) - from app.api.tools import file_check_bp, shipping_notice_bp + from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp app.register_blueprint(chat_bp, url_prefix='/api/chat') app.register_blueprint(admin_bp, url_prefix='/api/admin') @@ -52,8 +53,10 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace') app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace') app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') + app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance') app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') app.register_blueprint(file_check_bp, url_prefix='/api/file-check') app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context') + app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance') app.register_blueprint(speech_bp, url_prefix='/api/speech') app.register_blueprint(training_admin_bp, url_prefix='/api/admin') diff --git a/backend/app/api/admin/agents.py b/backend/app/api/admin/agents.py index b39b4aa7..16e54e97 100644 --- a/backend/app/api/admin/agents.py +++ b/backend/app/api/admin/agents.py @@ -61,3 +61,19 @@ def update_agent_permissions(id: int): user_ids = data.get('user_ids', []) agent_service.update_agent_permissions(id, user_ids) return jsonify({'status': 'ok'}) + + +@admin_bp.route('/agents//training-question-bank/import-pdf', methods=['POST']) +@require_admin +def import_training_question_bank_from_pdf(id: int): + """ + 从已上传的培训试题 PDF 解析题库。 + + 用途:给 Agent 管理表单提供“从试题 PDF 导入题库”入口,返回结构化题目供前端回填并继续人工微调。 + """ + data = request.get_json(silent=True) or {} + payload = agent_service.import_training_question_bank_from_pdf( + agent_id=id, + guide_id=data.get('guide_id'), + ) + return jsonify(payload), 200 diff --git a/backend/app/api/agents.py b/backend/app/api/agents.py index 0873cc37..1aa44808 100644 --- a/backend/app/api/agents.py +++ b/backend/app/api/agents.py @@ -87,6 +87,7 @@ def list_agent_guides(agent_id): 'id': g.id, 'file_name': g.file_name, 'file_type': g.file_type, + 'guide_usage': g.guide_usage, 'file_url': minio_service.get_public_url(g.file_path), 'file_size': g.file_size, 'remark': g.remark, diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index f473086c..7fc65fca 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -22,6 +22,7 @@ from sqlalchemy import func, desc, or_, exists, and_ from openpyxl import load_workbook from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs from app.services.dify import DifyService +from app.core.config.settings import Config from app.services.integration_api import IntegrationApiService from app.core.decorators import require_agent_permission from app.models import Agent, ChatLog, ChatSession, Feedback @@ -237,8 +238,18 @@ def _normalize_windows_share_path(path_value: str) -> str: def _is_allowed_share_path(target_url: str) -> bool: normalized_target = _normalize_windows_share_path(target_url) - normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT) - return bool(normalized_root and normalized_target.startswith('\\\\') and normalized_target.lower().startswith(normalized_root.lower())) + if not normalized_target.startswith('\\\\'): + return False + history_share_root = '' + if has_request_context(): + history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip() + if not history_share_root: + history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip() + roots = [ + _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT), + _normalize_windows_share_path(history_share_root), + ] + return any(root and normalized_target.lower().startswith(root.lower()) for root in roots) def _is_allowed_preview_url(target_url: str) -> bool: """ @@ -1135,6 +1146,111 @@ def get_chat_query_preview(chat_log_id: int): 'query': query, }) + +@chat_bp.route('/asset-history/search', methods=['GET']) +@require_agent_permission +def search_asset_history_files(): + """ + 检索固定资产履历文件。 + + 用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。 + 约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。 + """ + asset_id = (request.args.get('asset_id') or '').strip() + asset_name = (request.args.get('asset_name') or '').strip() + limit = request.args.get('limit', type=int) or 20 + limit = max(1, min(limit, 50)) + # #region debug-point C:asset-history-api-entry + import json as _debug_json + import urllib.request as _debug_urllib_request + try: + _debug_payload = _debug_json.dumps({ + 'sessionId': 'asset-history-click', + 'runId': 'pre-fix', + 'hypothesisId': 'C', + 'location': 'backend/chat.py:search_asset_history_files', + 'msg': '[DEBUG] asset history api entry', + 'data': { + 'asset_id': asset_id, + 'asset_name': asset_name, + 'limit': limit, + }, + }).encode('utf-8') + _debug_urllib_request.urlopen(_debug_urllib_request.Request( + 'http://127.0.0.1:7777/event', + data=_debug_payload, + headers={'Content-Type': 'application/json'}, + method='POST', + ), timeout=2).read() + except Exception: + pass + # #endregion + + if not asset_id and not asset_name: + raise ValidationError('asset_id or asset_name is required') + + from app.services.fixed_asset_history import FixedAssetHistoryService + + if not FixedAssetHistoryService.is_enabled(): + # #region debug-point C:asset-history-api-disabled + try: + _debug_payload = _debug_json.dumps({ + 'sessionId': 'asset-history-click', + 'runId': 'pre-fix', + 'hypothesisId': 'C', + 'location': 'backend/chat.py:search_asset_history_files', + 'msg': '[DEBUG] asset history api disabled', + 'data': { + 'share_root': str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or ''), + }, + }).encode('utf-8') + _debug_urllib_request.urlopen(_debug_urllib_request.Request( + 'http://127.0.0.1:7777/event', + data=_debug_payload, + headers={'Content-Type': 'application/json'}, + method='POST', + ), timeout=2).read() + except Exception: + pass + # #endregion + raise ServiceUnavailableError('asset history share is not configured') + + items = FixedAssetHistoryService.search_history_files( + asset_id=asset_id, + asset_name=asset_name, + limit=limit, + ) + # #region debug-point C:asset-history-api-success + try: + _debug_payload = _debug_json.dumps({ + 'sessionId': 'asset-history-click', + 'runId': 'pre-fix', + 'hypothesisId': 'C', + 'location': 'backend/chat.py:search_asset_history_files', + 'msg': '[DEBUG] asset history api success', + 'data': { + 'asset_id': asset_id, + 'asset_name': asset_name, + 'item_count': len(items), + }, + }).encode('utf-8') + _debug_urllib_request.urlopen(_debug_urllib_request.Request( + 'http://127.0.0.1:7777/event', + data=_debug_payload, + headers={'Content-Type': 'application/json'}, + method='POST', + ), timeout=2).read() + except Exception: + pass + # #endregion + return jsonify({ + 'asset_id': asset_id, + 'asset_name': asset_name, + 'total': len(items), + 'items': items, + }) + + @chat_bp.route('/completions', methods=['POST']) @require_agent_permission def chat_completions(): @@ -1260,6 +1376,7 @@ def chat_completions(): leave_feature_enabled = _can_use_leave_feature(agent_proxy) from app.services.faq_cache import FaqCacheService + from app.services.maintenance_chat_service import MaintenanceChatService faq_hit = FaqCacheService.try_match(query, agent_id) if not normalized_files else None if faq_hit: @@ -1271,6 +1388,14 @@ def chat_completions(): external_conversation_id, session_id=session.session_id, ) + elif not normalized_files and MaintenanceChatService.supports(query, agent_proxy): + generator = MaintenanceChatService.stream_chat( + query, + user_proxy, + agent_proxy, + external_conversation_id, + session_id=session.session_id, + ) elif PLMOracleService.supports(query, agent_proxy): generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id) elif leave_supported and leave_feature_enabled: diff --git a/backend/app/api/maintenance.py b/backend/app/api/maintenance.py new file mode 100644 index 00000000..fd379212 --- /dev/null +++ b/backend/app/api/maintenance.py @@ -0,0 +1,176 @@ +""" +backend/app/api/maintenance.py + +用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。 +依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。 +逻辑:查询接口面向会话与面板复用;写入/导入接口先做角色校验,再委托 service。 +""" + +from __future__ import annotations + +from io import BytesIO + +from flask import Blueprint, g, jsonify, request, send_file + +from app.core.auth.jwt import get_current_user +from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError +from app.services.maintenance_ledger_service import ( + build_import_template, + create_device, + get_device, + import_devices_from_excel, + list_devices, + update_device, +) +from app.services.maintenance_record_service import ( + build_records_export, + create_record, + delete_record, + get_record, + list_records, + update_record, +) + +maintenance_bp = Blueprint('maintenance', __name__) + + +def _require_user(): + """确保当前请求存在登录用户。""" + user = get_current_user() + if not user: + raise UnauthorizedError() + return user + + +def _require_ledger_admin(): + """ + 校验设备台账管理权限。 + Returns: + 当前用户对象。 + Raises: + ForbiddenError: 当前角色不允许写入台账。 + """ + user = _require_user() + if getattr(user, 'role', None) not in {'admin', 'asset_admin', 'maintenance_manager'}: + raise ForbiddenError('Maintenance ledger admin privilege required') + return user + + +@maintenance_bp.route('/ledger/devices', methods=['GET']) +def list_ledger_devices(): + """查询设备台账列表,供 Agent 查询结果与右侧台账配置面板使用。""" + _require_user() + result = list_devices( + keyword=request.args.get('keyword'), + status=request.args.get('status'), + page=request.args.get('page', type=int) or 1, + page_size=request.args.get('page_size', type=int) or 20, + ) + return jsonify(result) + + +@maintenance_bp.route('/ledger/devices/', methods=['GET']) +def get_ledger_device(device_id: int): + """读取设备台账详情。""" + _require_user() + return jsonify(get_device(device_id)) + + +@maintenance_bp.route('/ledger/devices', methods=['POST']) +def create_ledger_device(): + """新增设备台账,仅固定管理角色可用。""" + user = _require_ledger_admin() + payload = request.get_json() or {} + return jsonify(create_device(payload, operator=user, request_id=getattr(g, 'request_id', None))) + + +@maintenance_bp.route('/ledger/devices/', methods=['PUT']) +def update_ledger_device(device_id: int): + """更新设备台账,仅固定管理角色可用。""" + user = _require_ledger_admin() + payload = request.get_json() or {} + return jsonify(update_device(device_id, payload, operator=user, request_id=getattr(g, 'request_id', None))) + + +@maintenance_bp.route('/ledger/import-template', methods=['GET']) +def download_ledger_import_template(): + """下载设备台账 Excel 导入模板。""" + _require_ledger_admin() + return send_file( + BytesIO(build_import_template()), + as_attachment=True, + download_name='maintenance_devices_import_template.xlsx', + mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ) + + +@maintenance_bp.route('/ledger/import', methods=['POST']) +def import_ledger_devices(): + """上传 Excel 模板并批量新增/更新设备台账。""" + user = _require_ledger_admin() + upload = request.files.get('file') + if not upload: + raise ValidationError('file is required') + result = import_devices_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None)) + return jsonify(result) + + +@maintenance_bp.route('/records', methods=['GET']) +def list_maintenance_records(): + """查询设备维修记录,供 Agent 会话查询和结果卡片使用。""" + _require_user() + 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'), + page=request.args.get('page', type=int) or 1, + page_size=request.args.get('page_size', type=int) or 20, + ) + return jsonify(result) + + +@maintenance_bp.route('/records/', methods=['GET']) +def get_maintenance_record(record_id: int): + """读取设备维修记录详情。""" + _require_user() + return jsonify(get_record(record_id)) + + +@maintenance_bp.route('/records/export', methods=['GET']) +def export_maintenance_records(): + """按当前筛选条件导出设备维修记录 Excel。""" + _require_user() + 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'), + ) + return send_file( + BytesIO(data), + as_attachment=True, + download_name='maintenance_records.xlsx', + mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ) + + +@maintenance_bp.route('/records', methods=['POST']) +def create_maintenance_record(): + """新增设备维修记录,仅固定管理角色可用。""" + user = _require_ledger_admin() + payload = request.get_json() or {} + return jsonify(create_record(payload, operator=user, request_id=getattr(g, 'request_id', None))) + + +@maintenance_bp.route('/records/', methods=['PUT']) +def update_maintenance_record(record_id: int): + """更新设备维修记录,仅固定管理角色可用。""" + user = _require_ledger_admin() + payload = request.get_json() or {} + return jsonify(update_record(record_id, payload, operator=user, request_id=getattr(g, 'request_id', None))) + + +@maintenance_bp.route('/records/', methods=['DELETE']) +def delete_maintenance_record(record_id: int): + """删除设备维修记录,仅固定管理角色可用。""" + user = _require_ledger_admin() + return jsonify(delete_record(record_id, operator=user, request_id=getattr(g, 'request_id', None))) diff --git a/backend/app/api/maintenance_tools.py b/backend/app/api/maintenance_tools.py new file mode 100644 index 00000000..3f204893 --- /dev/null +++ b/backend/app/api/maintenance_tools.py @@ -0,0 +1,149 @@ +""" +backend/app/api/maintenance_tools.py + +用途:设备维保助手 Dify Tool API,只开放只读查询工具。 +依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。 +逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。 +""" + +from __future__ import annotations + +from flask import Blueprint, current_app, jsonify, request +from sqlalchemy import or_ + +from app import db +from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError +from app.models import MaintenanceRecord +from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE +from app.services.maintenance_chat_service import build_device_query_result +from app.services.maintenance_record_service import serialize_record +from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec + +maintenance_tool_bp = Blueprint("maintenance_tools", __name__) + + +def _require_tool_auth() -> None: + """ + 校验设备维保 Tool API 鉴权。 + AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。 + """ + configured = str( + current_app.config.get("MAINTENANCE_TOOL_API_KEY") + or current_app.config.get("INTEGRATION_API_KEY") + or "" + ).strip() + if not configured: + raise ServiceUnavailableError( + "MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured", + code="missing_auth", + ) + + bearer = str(request.headers.get("Authorization") or "").strip() + token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else "" + integration_key = str(request.headers.get("X-Integration-Key") or "").strip() + if configured in {token, integration_key}: + return + if not token and not integration_key: + raise UnauthorizedError("missing_auth") + raise UnauthorizedError("invalid_auth") + + +def _tool_error_code(exc: AppError) -> str: + """把 AppError 归一成 Dify Tool 侧可读错误码。""" + message = str(exc.message or "").strip() + if message in {"missing_auth", "invalid_auth"}: + return message + if exc.code == "AUTH.UNAUTHORIZED": + return "invalid_auth" + if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower(): + return "missing_auth" + if exc.code == "VALIDATION.INVALID_PARAM": + return message or "invalid_request" + return exc.code + + +@maintenance_tool_bp.errorhandler(AppError) +def _handle_tool_app_error(exc: AppError): + """Tool API 统一错误响应。""" + return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status + + +@maintenance_tool_bp.before_request +def _verify_tool_access(): + """除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。""" + if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"): + return None + _require_tool_auth() + return None + + +def _payload() -> dict: + """读取 JSON 请求体。""" + return request.get_json(silent=True) or {} + + +def _clean_text(value) -> str: + return str(value or "").strip() + + +@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"]) +def openapi_spec(): + """返回 Dify 导入用的 OpenAPI JSON。""" + return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE())) + + +@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"]) +def openapi_dify_yaml(): + """返回 Dify 导入用的 OpenAPI YAML。""" + import yaml + + body = yaml.safe_dump( + build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()), + allow_unicode=True, + sort_keys=False, + ) + return current_app.response_class(body, mimetype="text/yaml; charset=utf-8") + + +@maintenance_tool_bp.route("/tools/query_device", methods=["POST"]) +def query_device(): + """按设备编号或名称查询设备台账,并可带出最近维修记录。""" + data = _payload() + keyword = _clean_text(data.get("keyword")) + if not keyword: + raise ValidationError("keyword is required") + include_records = bool(data.get("include_records", True)) + record_limit = max(0, min(20, int(data.get("record_limit") or 5))) + result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit) + return jsonify({"ok": True, **result}) + + +@maintenance_tool_bp.route("/tools/query_records", methods=["POST"]) +def query_records(): + """按设备编号/名称和状态查询维修记录。""" + data = _payload() + keyword = _clean_text(data.get("keyword")) + if not keyword: + raise ValidationError("keyword is required") + status = _clean_text(data.get("status")) + limit = max(1, min(50, int(data.get("limit") or 10))) + + query = db.session.query(MaintenanceRecord) + like = f"%{keyword}%" + query = query.filter( + or_( + MaintenanceRecord.device_code.ilike(like), + MaintenanceRecord.device_name.ilike(like), + ) + ) + if status: + query = query.filter(MaintenanceRecord.repair_status == status) + rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all() + return jsonify({ + "ok": True, + "matched": bool(rows), + "keyword": keyword, + "items": [serialize_record(item) for item in rows], + "totalReturned": len(rows), + }) + diff --git a/backend/app/api/tools/__init__.py b/backend/app/api/tools/__init__.py index 6627ca7e..38316390 100644 --- a/backend/app/api/tools/__init__.py +++ b/backend/app/api/tools/__init__.py @@ -6,5 +6,6 @@ backend/app/api/tools/__init__.py """ from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401 from app.api.tools.file_check import file_check_bp # noqa: F401 +from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401 __all__ = ['shipping_notice_bp', 'file_check_bp'] diff --git a/backend/app/api/tools/maintenance.py b/backend/app/api/tools/maintenance.py new file mode 100644 index 00000000..a078a130 --- /dev/null +++ b/backend/app/api/tools/maintenance.py @@ -0,0 +1,9 @@ +""" +backend/app/api/tools/maintenance.py + +用途:设备维保 Tool API Blueprint re-export。 +依赖:app.api.maintenance_tools。 +逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。 +""" + +from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401 diff --git a/backend/app/api/training.py b/backend/app/api/training.py index 81cad6ee..141d52f8 100644 --- a/backend/app/api/training.py +++ b/backend/app/api/training.py @@ -36,9 +36,14 @@ def _require_user(): def _require_training_admin(): - """确保当前用户具备培训管理权限。""" + """ + 确保当前用户具备培训管理权限。 + + 用途:统一拦截 HR 管理面板的数据查询、统计与导出接口。 + 核心逻辑:优先复用 User.can_manage_training(),把“角色默认权限 + 前端可配置功能权限”收敛到同一个判断入口。 + """ user = _require_user() - if user.role not in {"admin", "hr"}: + if not user.can_manage_training(): raise ForbiddenError("Training admin privilege required") return user diff --git a/backend/app/api/user.py b/backend/app/api/user.py index a2127923..757fe100 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -436,7 +436,16 @@ def _get_wecom_access_token(): return _wecom_svc.get_access_token() def _build_login_payload(user: User, source: str='password', bind_status: str=None): - payload = {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': source, 'access_token': issue_local_access_token(user), 'token_type': 'Bearer'} + payload = { + 'id': user.id, + 'username': user.username, + 'role': user.role, + 'default_agent_id': user.default_agent_id, + 'feature_permissions': user.get_feature_permissions(), + 'source': source, + 'access_token': issue_local_access_token(user), + 'token_type': 'Bearer', + } if bind_status: payload['bind_status'] = bind_status return payload @@ -760,7 +769,7 @@ def casdoor_password_login(): _write_login_audit('casdoor', 'success', user=user) db.session.commit() api_bearer_token = id_token or access_token - return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in}) + return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in}) except WeComLoginError: db.session.rollback() raise @@ -890,7 +899,7 @@ def casdoor_login(): _write_login_audit('casdoor', 'success', user=user) db.session.commit() api_bearer_token = id_token or access_token - return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in}) + return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in}) except WeComLoginError: db.session.rollback() current_app.logger.warning('[casdoor_login] business_reject') @@ -1352,7 +1361,7 @@ def home(): agent = db.session.get(Agent, rel.agent_id) if agent: embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None}) - return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout}) + return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout}) try: return _run_db_with_retry(_load_home_payload, label='user.home') except (OperationalError, DatabaseError) as exc: @@ -1436,7 +1445,7 @@ def user_profile(): if not user: raise UnauthorizedError('Unauthorized') if request.method == 'GET': - return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}) + return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}) data = request.get_json() or {} def _update_profile(): diff --git a/backend/app/core/auth/jwt.py b/backend/app/core/auth/jwt.py index 44a40d5b..60ae9586 100644 --- a/backend/app/core/auth/jwt.py +++ b/backend/app/core/auth/jwt.py @@ -233,14 +233,26 @@ def _legacy_header_user() -> Optional[User]: return _lookup() +def _current_user_cache_key() -> tuple[str, str, str, str]: + """构造当前请求用户缓存键,避免测试或保留上下文场景串用上一条请求的用户缓存。""" + return ( + str(request.headers.get('Authorization') or '').strip(), + str(request.headers.get('X-User-Id') or '').strip(), + str(request.headers.get('X-Username') or '').strip(), + f'{request.method}:{request.path}', + ) + + def get_current_user() -> Optional[User]: """ 解析当前请求用户:优先 JWT Bearer,其次 legacy header(若配置启用)。 Returns: User 实例;未认证时返回 None。 """ + cache_key = _current_user_cache_key() cached = getattr(g, 'current_user', None) - if cached is not None: + cached_key = getattr(g, 'current_user_cache_key', None) + if cached is not None and cached_key == cache_key: return cached token = _extract_bearer_token() @@ -271,12 +283,14 @@ def get_current_user() -> Optional[User]: if user: g.jwt_claims = claims g.current_user = user + g.current_user_cache_key = cache_key return user if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)): user = _legacy_header_user() if user: g.current_user = user + g.current_user_cache_key = cache_key return user return None diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 92c02c95..699c440c 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -289,6 +289,10 @@ class Config: ) FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3') FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets') + FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip() + FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip() + FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '') + FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20') FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv( 'FIXED_ASSETS_DOCS_EXPORT_ROOT', str(_ROOT_DIR / 'docs'), diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index a81c3ec8..43260383 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -13,6 +13,7 @@ from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlL from app.models.department import Department from app.models.job import Job from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob +from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig from app.models.settings import AppSetting from app.models.shipping import ( @@ -66,4 +67,7 @@ __all__ = [ 'ShippingInventoryMapping', 'AgentGuide', 'TrainingRecord', + 'MaintenanceDevice', + 'MaintenanceRecord', + 'MaintenanceAuditLog', ] diff --git a/backend/app/models/agent.py b/backend/app/models/agent.py index 8f0424c9..472d680f 100644 --- a/backend/app/models/agent.py +++ b/backend/app/models/agent.py @@ -57,6 +57,7 @@ class AgentGuide(Base): file_type: Mapped[str] = mapped_column(String(50), nullable=False) file_path: Mapped[str] = mapped_column(String(500), nullable=False) file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + guide_usage: Mapped[str] = mapped_column(String(50), nullable=False, default='general') remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) sort_order: Mapped[int] = mapped_column(Integer, default=0) status: Mapped[int] = mapped_column(Integer, default=1) diff --git a/backend/app/models/maintenance.py b/backend/app/models/maintenance.py new file mode 100644 index 00000000..fac4565b --- /dev/null +++ b/backend/app/models/maintenance.py @@ -0,0 +1,101 @@ +""" +backend/app/models/maintenance.py + +用途:设备维保域数据模型,当前覆盖设备台账与台账变更审计。 +依赖:models.base.Base、SQLAlchemy mapped_column。 +逻辑:maintenance_devices 为维保助手查询/配置的设备主数据;audit_logs 记录台账导入与人工修改。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from typing import Optional + +from sqlalchemy import Date, DateTime, Index, Numeric, String, Text, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class MaintenanceDevice(Base): + """设备台账主数据;责任人暂存用户名字符串,不与 users 表建立外键关系。""" + + __tablename__ = 'maintenance_devices' + __table_args__ = ( + UniqueConstraint('device_code', name='uq_maintenance_devices_device_code'), + Index('ix_maintenance_devices_name', 'device_name'), + Index('ix_maintenance_devices_location', 'install_location'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + device_code: Mapped[str] = mapped_column(String(80), nullable=False) + device_name: Mapped[str] = mapped_column(String(200), nullable=False) + model_spec: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + department: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + install_location: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + device_status: Mapped[str] = mapped_column(String(30), default='in_use', nullable=False) + manufacturer: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + entry_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + production_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + start_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + responsible_user: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + maintenance_cycle: Mapped[Optional[str]] = mapped_column(String(80), nullable=True) + original_value: Mapped[Optional[float]] = mapped_column(Numeric(14, 2), nullable=True) + residual_value: Mapped[Optional[float]] = mapped_column(Numeric(14, 2), nullable=True) + account_set: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + updated_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + +class MaintenanceAuditLog(Base): + """设备维保域审计日志,记录台账新增、更新、Excel 导入等写入动作。""" + + __tablename__ = 'maintenance_audit_logs' + + id: Mapped[int] = mapped_column(primary_key=True) + object_type: Mapped[str] = mapped_column(String(40), nullable=False) + object_id: Mapped[Optional[int]] = mapped_column(nullable=True) + action: Mapped[str] = mapped_column(String(40), nullable=False) + before_data: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + after_data: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + operator_name: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + request_id: Mapped[Optional[str]] = mapped_column(String(80), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + +class MaintenanceRecord(Base): + """设备维修记录,保存报修、修复与费用工时信息。""" + + __tablename__ = 'maintenance_records' + __table_args__ = ( + Index('ix_maintenance_records_device_code', 'device_code'), + Index('ix_maintenance_records_report_date', 'report_date'), + Index('ix_maintenance_records_status', 'repair_status'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + device_id: Mapped[Optional[int]] = mapped_column(nullable=True) + device_code: Mapped[str] = mapped_column(String(80), nullable=False) + device_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + model_spec: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + install_location: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + report_date: Mapped[date] = mapped_column(Date, nullable=False) + repair_category: Mapped[Optional[str]] = mapped_column(String(80), nullable=True) + fault_description: Mapped[str] = mapped_column(Text, nullable=False) + reporter: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + approver: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + repair_status: Mapped[str] = mapped_column(String(30), default='pending', nullable=False) + repair_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + repair_unit: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + repairer: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + repair_cost: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + repair_hours: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + repair_description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + source_order_no: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + created_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + updated_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) diff --git a/backend/app/models/user.py b/backend/app/models/user.py index bdf8cb21..6c85ffd9 100644 --- a/backend/app/models/user.py +++ b/backend/app/models/user.py @@ -61,6 +61,7 @@ class User(Base): department: Mapped[Optional[str]] = mapped_column(String(100)) role: Mapped[str] = mapped_column(String(20), default='user') status: Mapped[str] = mapped_column(String(20), default='active') + feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False) password_hash: Mapped[Optional[str]] = mapped_column(String(255)) language: Mapped[str] = mapped_column(String(10), default='zh-CN') theme_preference: Mapped[str] = mapped_column(String(10), default='system') @@ -84,6 +85,57 @@ class User(Base): uselist=False, ) + def _role_default_feature_permissions(self) -> dict[str, bool]: + """返回当前角色自带的功能权限默认值。""" + return { + 'training_hr_manage': self.role in {'admin', 'hr'}, + } + + def get_feature_permissions(self) -> dict[str, bool]: + """ + 返回当前用户的有效功能权限。 + + 用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。 + 核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训类业务权限硬编码在多个模块。 + 输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。 + """ + defaults = self._role_default_feature_permissions() + raw = self.feature_permissions if isinstance(self.feature_permissions, dict) else {} + result: dict[str, bool] = {} + for key, default_value in defaults.items(): + if key in raw: + result[key] = bool(raw.get(key)) + else: + result[key] = bool(default_value) + return result + + def set_feature_permissions(self, permissions: dict | None) -> None: + """ + 保存用户显式配置的功能权限覆盖项。 + + 用途:给管理后台用户编辑表单落库权限配置。 + 核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。 + 参数约束:permissions 必须为 dict 或 None;未知键会被忽略。 + """ + defaults = self._role_default_feature_permissions() + raw = permissions if isinstance(permissions, dict) else {} + overrides: dict[str, bool] = {} + for key, default_value in defaults.items(): + if key not in raw: + continue + normalized = bool(raw.get(key)) + if normalized != bool(default_value): + overrides[key] = normalized + self.feature_permissions = overrides + + def has_feature_permission(self, permission_key: str) -> bool: + """判断当前用户是否具备指定功能权限。""" + return bool(self.get_feature_permissions().get(permission_key)) + + def can_manage_training(self) -> bool: + """判断当前用户是否可使用培训 HR 管理面板与接口。""" + return self.has_feature_permission('training_hr_manage') + def set_password(self, password: str) -> None: """设置密码哈希。""" self.password_hash = generate_password_hash(password) diff --git a/backend/app/services/admin/agent_service.py b/backend/app/services/admin/agent_service.py index 9789ee49..a9330525 100644 --- a/backend/app/services/admin/agent_service.py +++ b/backend/app/services/admin/agent_service.py @@ -17,6 +17,7 @@ from app.core.config.settings import Config from app.core.errors import NotFoundError, ValidationError from app.models import Agent, User from app.services.dify import DifyService +from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide def serialize_agent(agent: Agent) -> dict: @@ -288,3 +289,15 @@ def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None: for user in users_to_remove: user.agents.remove(agent) db.session.commit() + + +def import_training_question_bank_from_pdf(agent_id: int, guide_id: int | None = None) -> dict[str, Any]: + """ + 解析指定 Agent 的培训试题 PDF,并返回结构化题库。 + + 用途:当前端点击“从试题 PDF 导入”时使用;这里只做解析,不直接覆盖 Agent 配置,避免误导入后无法人工复核。 + """ + agent = db.session.get(Agent, agent_id) + if not agent: + raise NotFoundError('Not found') + return parse_training_question_bank_from_guide(agent_id=agent_id, guide_id=guide_id) diff --git a/backend/app/services/admin/guide_service.py b/backend/app/services/admin/guide_service.py index 45867c1e..23d4af1d 100644 --- a/backend/app/services/admin/guide_service.py +++ b/backend/app/services/admin/guide_service.py @@ -17,6 +17,16 @@ from app.models import AgentGuide from app.services.minio_service import minio_service +GUIDE_USAGE_GENERAL = 'general' +GUIDE_USAGE_TRAINING_VIDEO = 'training_video' +GUIDE_USAGE_TRAINING_EXAM_PDF = 'training_exam_pdf' +ALLOWED_GUIDE_USAGES = { + GUIDE_USAGE_GENERAL, + GUIDE_USAGE_TRAINING_VIDEO, + GUIDE_USAGE_TRAINING_EXAM_PDF, +} + + def _infer_file_type(content_type: str | None) -> str: ct = str(content_type or '') if ct.startswith('video'): @@ -36,6 +46,7 @@ def serialize_guide(guide: AgentGuide) -> dict: 'file_path': guide.file_path, 'file_url': minio_service.get_public_url(guide.file_path), 'file_size': guide.file_size, + 'guide_usage': guide.guide_usage, 'remark': guide.remark, 'sort_order': guide.sort_order, 'status': guide.status, @@ -43,6 +54,23 @@ def serialize_guide(guide: AgentGuide) -> dict: } +def _normalize_guide_usage(raw_usage: Any, *, file_type: str) -> str: + """ + 归一化指南用途并校验与文件类型是否匹配。 + + 用途:给后台上传/编辑指南时统一约束“培训视频”“培训试题 PDF”等资料用途,避免前端再靠排序或文件名猜测。 + 参数约束:training_video 仅允许 video 文件;training_exam_pdf 仅允许 pdf 文件。 + """ + usage = str(raw_usage or GUIDE_USAGE_GENERAL).strip() or GUIDE_USAGE_GENERAL + if usage not in ALLOWED_GUIDE_USAGES: + raise ValidationError('Invalid guide usage') + if usage == GUIDE_USAGE_TRAINING_VIDEO and file_type != 'video': + raise ValidationError('Training video usage requires a video file') + if usage == GUIDE_USAGE_TRAINING_EXAM_PDF and file_type != 'pdf': + raise ValidationError('Training exam PDF usage requires a PDF file') + return usage + + def upload_guide_file(file_storage: FileStorage | None) -> dict: """ 上传引导文件至 MinIO。 @@ -80,12 +108,14 @@ def list_guides(*, agent_id: int | None = None) -> list[dict]: def create_guide(data: dict[str, Any], *, created_by_id: int | None) -> dict: """创建 AgentGuide 记录。""" + file_type = str(data['file_type']) guide = AgentGuide( agent_id=data['agent_id'], file_name=data['file_name'], - file_type=data['file_type'], + file_type=file_type, file_path=data['file_path'], file_size=data.get('file_size'), + guide_usage=_normalize_guide_usage(data.get('guide_usage'), file_type=file_type), remark=data.get('remark'), sort_order=data.get('sort_order', 0), status=data.get('status', 1), @@ -109,6 +139,8 @@ def update_guide(guide_id: int, data: dict[str, Any]) -> None: guide.sort_order = data['sort_order'] if 'status' in data: guide.status = data['status'] + if 'guide_usage' in data: + guide.guide_usage = _normalize_guide_usage(data.get('guide_usage'), file_type=guide.file_type) db.session.commit() diff --git a/backend/app/services/admin/training_exam_pdf_service.py b/backend/app/services/admin/training_exam_pdf_service.py new file mode 100644 index 00000000..5f0e4cc6 --- /dev/null +++ b/backend/app/services/admin/training_exam_pdf_service.py @@ -0,0 +1,445 @@ +""" +backend/app/services/admin/training_exam_pdf_service.py + +用途:把员工培训试题 PDF 解析成结构化题库,供 Agent extra_config.training_config 回填。 +依赖:models.AgentGuide、minio_service、pypdf、edkb_system PDF/OCR 技能。 +逻辑:优先读取已标记为 training_exam_pdf 的指南文件,先抽取 PDF 原生文本;若文本缺失或解析失败,再回退到 OCR 识别,最终把题目、选项、答案与解析返回给管理端表单继续人工校验。 +""" +from __future__ import annotations + +import io +import re +import tempfile +from pathlib import Path +from typing import Any + +from pypdf import PdfReader + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import AgentGuide +from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF +from app.services.minio_service import minio_service +from edkb_system.contracts import Block, Context +from edkb_system.skills import loader_pdf, ocr + +_QUESTION_START_PATTERN = re.compile(r'^\s*(\d{1,3})\s*[\.\、\.\)]\s*(.+?)\s*$') +_OPTION_PATTERN = re.compile(r'([A-D])\s*[\.\、\.\)\::]\s*') +_INLINE_ANSWER_PATTERN = re.compile(r'答案\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE) +_INLINE_EXPLANATION_PATTERN = re.compile(r'解析\s*[::]?\s*(.+)$', re.IGNORECASE) +_ANSWER_PAIR_PATTERN = re.compile(r'(?:^|(?<=[\s,,;;]))(\d{1,3})\s*[\.\、\.\)]?\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE) +_SECTION_HEADING_PATTERN = re.compile(r'^[一二三四五六七八九十]+[\.\、\.\)]\s*[^\n]*题') +_BOOLEAN_PROMPT_HINT_PATTERN = re.compile(r'正确还是错误|对还是错|判断题|[\((]\s*[\))]|是否') +_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s+(.+)$') +_BOOLEAN_TOKEN_PATTERN = re.compile(r'正确|错误|对|错|T|F|V|X|√|×', re.IGNORECASE) + + +def _normalize_line_breaks(text: str) -> str: + return str(text or '').replace('\r\n', '\n').replace('\r', '\n') + + +def _normalize_spaces(text: str) -> str: + return re.sub(r'[ \t\u3000]+', ' ', str(text or '')).strip() + + +def _normalize_answer_token(raw_answer: str) -> str: + answer = str(raw_answer or '').strip().upper() + if answer in {'A', 'B', 'C', 'D'}: + return answer.lower() + if answer in {'正确', '对', 'T', 'V', '√', 'TRUE'}: + return 'true' + if answer in {'错误', '错', 'F', 'X', '×', 'FALSE'}: + return 'false' + return '' + + +def _extract_pdf_text(raw_bytes: bytes) -> str: + """ + 从 PDF 原始字节中抽取纯文本。 + + 用途:为培训试题导入提供统一文本输入,避免每个管理接口重复组装 PdfReader。 + 参数约束:raw_bytes 必须是 PDF 文件内容;若整份文件无可读文本,将由上层决定是否报错。 + """ + reader = PdfReader(io.BytesIO(raw_bytes)) + page_texts: list[str] = [] + for page in reader.pages: + text = _normalize_spaces(_normalize_line_breaks(page.extract_text() or '')) + if text: + page_texts.append(text) + return '\n'.join(page_texts).strip() + + +def _blocks_to_text(blocks: list[Block]) -> str: + """ + 把 edkb_system 的段落/OCR 结果统一折叠成纯文本。 + + 用途:扫描件 PDF 会先被 loader_pdf 切成 paragraph/image/ocr_text block,这里负责收敛成后续题库解析可消费的文本。 + 参数约束:只拼接 paragraph 与 ocr_text,避免把图片元数据等噪音混入题干。 + """ + lines: list[str] = [] + for block in blocks: + if block.type not in {'paragraph', 'ocr_text'}: + continue + text = _normalize_line_breaks(block.text or '').strip() + if not text: + continue + if block.type == 'ocr_text': + if text.startswith('OCR_TEXT:'): + text = text[len('OCR_TEXT:') :].strip() + text = re.sub(r'(?m)^\s*-\s*', '', text).strip() + if text: + lines.append(text) + return '\n'.join(lines).strip() + + +def _extract_pdf_text_via_ocr(raw_bytes: bytes) -> tuple[str, list[str]]: + """ + 使用仓库内置 PDF loader + OCR 管线提取扫描件文本。 + + 用途:当 pypdf 拿不到可读文本,或题目结构解析失败时,回退到这条路径兼容图片型 PDF。 + 参数约束:raw_bytes 必须是完整 PDF 字节;若当前环境未安装 rapidocr 相关依赖,会在 warnings 中返回原因而不是直接抛异常。 + """ + temp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file: + temp_file.write(raw_bytes) + temp_path = Path(temp_file.name) + + context = Context(file_type='pdf') + blocks = loader_pdf.run({'file_path': str(temp_path)}, context) + if any(block.type == 'image' for block in blocks): + blocks = ocr.run(blocks, context) + return _blocks_to_text(blocks), list(context.warnings) + finally: + if temp_path is not None: + try: + temp_path.unlink(missing_ok=True) + except Exception: + pass + + +def _collect_candidate_lines(text: str) -> list[str]: + normalized_text = _normalize_line_breaks(text) + lines: list[str] = [] + for raw_line in normalized_text.split('\n'): + line = _normalize_spaces(raw_line) + if line: + lines.append(line) + return lines + + +def _is_answer_sheet_line(line: str) -> bool: + """ + 判断当前行是否更像“答案表”而不是题干。 + + 用途:很多培训试卷会在末尾给出“1.B 2.A 3.正确”这类答案表;这些行不能再被当成题目块切进去,否则会污染上一题或额外生成伪题目。 + 参数约束:仅识别高置信度答案行,避免误伤正常题干。 + """ + normalized_line = _normalize_spaces(line) + if not normalized_line: + return False + if '答案' in normalized_line: + return True + range_match = _ANSWER_RANGE_PATTERN.match(normalized_line) + if range_match: + token_matches = _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3)) + expected_count = int(range_match.group(2)) - int(range_match.group(1)) + 1 + if len(token_matches) >= max(expected_count - 1, 2): + return True + matches = list(_ANSWER_PAIR_PATTERN.finditer(normalized_line)) + return len(matches) >= 2 + + +def _extract_answer_sequence(lines: list[str]) -> list[str]: + """ + 按文本顺序提取整卷答案序列。 + + 用途:当 PDF 内部“单选题/判断题”分别从 1 重新编号,或答案表使用整卷顺序编号时,单靠题号已无法稳定对齐,这里保留顺序型答案用于按题目出现顺序兜底匹配。 + 参数约束:只从明确的答案行提取,避免把题干中的 A/B/C/D 选项误收进答案序列。 + """ + answers: list[str] = [] + for line in lines: + if not _is_answer_sheet_line(line): + continue + range_match = _ANSWER_RANGE_PATTERN.match(_normalize_spaces(line)) + if range_match: + for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3)): + answer = _normalize_answer_token(raw_token) + if answer: + answers.append(answer) + continue + for match in _ANSWER_PAIR_PATTERN.finditer(line): + answer = _normalize_answer_token(match.group(2)) + if answer: + answers.append(answer) + return answers + + +def _extract_answer_map(lines: list[str]) -> dict[int, str]: + """ + 从“参考答案”区域提取题号与答案映射。 + + 用途:很多试卷会把题目和答案分成两段展示,这里先把独立答案表收集出来,供后续题目块回填正确答案。 + 参数约束:只解析明显的答案行,避免把题干里的选项误判成答案。 + """ + answer_map: dict[int, str] = {} + for line in lines: + matches = list(_ANSWER_PAIR_PATTERN.finditer(line)) + if not _is_answer_sheet_line(line): + continue + for match in matches: + question_no = int(match.group(1)) + answer = _normalize_answer_token(match.group(2)) + if answer and question_no not in answer_map: + answer_map[question_no] = answer + return answer_map + + +def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]: + blocks: list[tuple[int, str]] = [] + current_no: int | None = None + current_lines: list[str] = [] + + for line in lines: + if _SECTION_HEADING_PATTERN.match(line): + if current_no is not None and current_lines: + blocks.append((current_no, ' '.join(current_lines).strip())) + current_no = None + current_lines = [] + continue + question_match = _QUESTION_START_PATTERN.match(line) + if question_match: + if _is_answer_sheet_line(line) and '答案' not in line: + continue + if current_no is not None and current_lines: + blocks.append((current_no, ' '.join(current_lines).strip())) + current_no = int(question_match.group(1)) + current_lines = [question_match.group(2)] + continue + if _is_answer_sheet_line(line): + continue + if current_no is not None: + current_lines.append(line) + + if current_no is not None and current_lines: + blocks.append((current_no, ' '.join(current_lines).strip())) + return blocks + + +def _extract_inline_answer(block_text: str) -> str: + match = _INLINE_ANSWER_PATTERN.search(block_text) + if not match: + return '' + return _normalize_answer_token(match.group(1)) + + +def _extract_inline_explanation(block_text: str) -> str: + match = _INLINE_EXPLANATION_PATTERN.search(block_text) + return _normalize_spaces(match.group(1)) if match else '' + + +def _strip_inline_meta(block_text: str) -> str: + cleaned = _INLINE_EXPLANATION_PATTERN.sub('', block_text) + cleaned = _INLINE_ANSWER_PATTERN.sub('', cleaned) + return _normalize_spaces(cleaned) + + +def _build_boolean_question(question_no: int, prompt: str, answer: str, explanation: str) -> dict[str, Any] | None: + if answer not in {'true', 'false'}: + return None + return { + 'id': f'q{question_no}', + 'type': 'boolean', + 'prompt': prompt, + 'answer': answer, + 'explanation': explanation, + } + + +def _build_answer_candidates( + *, + inline_answer: str, + mapped_answer: str, + ordered_answer: str, +) -> list[str]: + """ + 组合单题可用的答案候选,并按可信度排序。 + + 用途:优先使用题干内联答案,其次使用题号映射;若 PDF 存在分节重编号,再退回整卷顺序答案,尽量把判断题补齐。 + 参数约束:返回结果会去重,避免同一答案在多种来源下重复尝试。 + """ + candidates: list[str] = [] + for raw in (inline_answer, mapped_answer, ordered_answer): + value = _normalize_answer_token(raw) + if value and value not in candidates: + candidates.append(value) + return candidates + + +def _looks_like_boolean_question(prompt: str, option_matches: list[re.Match[str]], answer_candidates: list[str]) -> bool: + """ + 判断题型是否更接近判断题。 + + 用途:避免答案表错位时把带 A/B/C/D 选项的单选题误判成判断题,同时允许“句子 + ( )”这类常见判断题格式被识别。 + 参数约束:只在没有完整选项结构时才考虑判断题,单选题仍以选项结构为主。 + """ + if len(option_matches) >= 2: + return False + if any(answer in {'true', 'false'} for answer in answer_candidates): + return True + return bool(_BOOLEAN_PROMPT_HINT_PATTERN.search(prompt)) + + +def _build_single_choice_question(question_no: int, prompt: str, option_matches: list[re.Match[str]], answer: str, explanation: str) -> dict[str, Any] | None: + if len(option_matches) < 2: + return None + + options: list[dict[str, str]] = [] + for index, match in enumerate(option_matches): + start = match.end() + end = option_matches[index + 1].start() if index + 1 < len(option_matches) else len(prompt) + label = _normalize_spaces(prompt[start:end]) + option_id = match.group(1).lower() + if not label: + continue + options.append({'id': option_id, 'label': f"{match.group(1).upper()}. {label}"}) + + if len(options) < 2 or answer not in {item['id'] for item in options}: + return None + + prompt_text = _normalize_spaces(prompt[:option_matches[0].start()]) + if not prompt_text: + return None + + return { + 'id': f'q{question_no}', + 'type': 'single', + 'prompt': prompt_text, + 'answer': answer, + 'explanation': explanation, + 'options': options, + } + + +def parse_training_question_bank_text(text: str) -> dict[str, Any]: + """ + 将 PDF 抽出的纯文本解析成培训题库。 + + 用途:给管理后台的“从试题 PDF 导入题库”提供核心解析逻辑;优先保证答题链路可用,无法确定答案的题目宁可跳过也不乱导入。 + 参数约束:text 应来自同一份试卷文本;若完全无法识别题目或答案,调用方应直接提示人工处理。 + """ + lines = _collect_candidate_lines(text) + answer_map = _extract_answer_map(lines) + answer_sequence = _extract_answer_sequence(lines) + question_blocks = _split_question_blocks(lines) + question_bank: list[dict[str, Any]] = [] + skipped_questions: list[int] = [] + + # [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。 + for index, (question_no, raw_block) in enumerate(question_blocks): + inline_answer = _extract_inline_answer(raw_block) + explanation = _extract_inline_explanation(raw_block) + block_text = _strip_inline_meta(raw_block) + option_matches = list(_OPTION_PATTERN.finditer(block_text)) + answer_candidates = _build_answer_candidates( + inline_answer=inline_answer, + mapped_answer=answer_map.get(question_no, ''), + ordered_answer=answer_sequence[index] if index < len(answer_sequence) else '', + ) + + if _looks_like_boolean_question(block_text, option_matches, answer_candidates): + for answer in answer_candidates: + question_payload = _build_boolean_question( + question_no=question_no, + prompt=block_text, + answer=answer, + explanation=explanation, + ) + if question_payload: + question_payload['id'] = f'q{len(question_bank) + 1}' + question_bank.append(question_payload) + break + else: + question_payload = None + if question_payload: + continue + + for answer in answer_candidates: + question_payload = _build_single_choice_question( + question_no=question_no, + prompt=block_text, + option_matches=option_matches, + answer=answer, + explanation=explanation, + ) + if question_payload: + question_payload['id'] = f'q{len(question_bank) + 1}' + question_bank.append(question_payload) + break + else: + question_payload = None + if question_payload: + continue + + skipped_questions.append(question_no) + + if not question_bank: + raise ValidationError('未能从试题 PDF 中识别出可用题目,请检查 PDF 是否包含可复制文本与标准答案') + + return { + 'question_bank': question_bank, + 'parsed_count': len(question_bank), + 'skipped_question_numbers': skipped_questions, + } + + +def parse_training_question_bank_from_guide(agent_id: int, guide_id: int | None = None) -> dict[str, Any]: + """ + 从指定 Agent 的试题 PDF 指南中解析题库。 + + 用途:管理后台点击“从已上传试题 PDF 导入”时使用,优先读取显式标记为 training_exam_pdf 的资料。 + 参数约束:guide_id 若传入,必须属于当前 agent 且文件类型为 pdf。 + """ + query = db.session.query(AgentGuide).filter(AgentGuide.agent_id == agent_id) + if guide_id is not None: + query = query.filter(AgentGuide.id == guide_id) + query = query.filter(AgentGuide.file_type == 'pdf') + guide = query.order_by(AgentGuide.sort_order.asc(), AgentGuide.id.desc()).first() + if not guide: + raise NotFoundError('Training exam PDF guide not found') + if guide.guide_usage != GUIDE_USAGE_TRAINING_EXAM_PDF: + raise ValidationError('Selected guide is not marked as training exam PDF') + + raw_bytes = minio_service.get_file_bytes(guide.file_path) + text = _extract_pdf_text(raw_bytes) + ocr_text = '' + ocr_warnings: list[str] = [] + extraction_mode = 'pdf_text' + + # [STEP 1] 先尝试 PDF 原生文本,速度快且不会引入 OCR 噪音。 + if text: + try: + parsed = parse_training_question_bank_text(text) + except ValidationError as primary_error: + # [STEP 2] 原生文本存在但结构解析失败时,再尝试 OCR,兼容“页面能选中文本但题号/答案错位”的扫描型 PDF。 + ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes) + if not ocr_text or ocr_text == text: + raise primary_error + parsed = parse_training_question_bank_text(ocr_text) + extraction_mode = 'ocr_fallback' + else: + # [STEP 2] 完全拿不到 PDF 文本时,直接走 OCR;若 OCR 依旧为空,则给管理端明确报错并带回诊断 warnings。 + ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes) + if not ocr_text: + raise ValidationError( + '试题 PDF 未提取到可读文本,请检查是否为扫描件或图片 PDF,并确认 OCR 依赖已正确安装', + details={'ocr_warnings': ocr_warnings}, + ) + parsed = parse_training_question_bank_text(ocr_text) + extraction_mode = 'ocr' + + parsed['guide_id'] = guide.id + parsed['guide_file_name'] = guide.file_name + parsed['extraction_mode'] = extraction_mode + parsed['extraction_warnings'] = ocr_warnings + return parsed diff --git a/backend/app/services/admin/user_service.py b/backend/app/services/admin/user_service.py index 43060754..cbd4b29e 100644 --- a/backend/app/services/admin/user_service.py +++ b/backend/app/services/admin/user_service.py @@ -79,6 +79,7 @@ def serialize_admin_user(user: User) -> dict: 'real_name': user.real_name, 'employee_id': user.employee_id, 'phone_number': user.phone_number, + 'feature_permissions': user.get_feature_permissions(), 'agent_ids': [agent.id for agent in user.agents], } @@ -174,6 +175,7 @@ def create_user(data: dict[str, Any]) -> dict: employee_id=empty_to_none(data.get('employee_id')), phone_number=empty_to_none(data.get('phone_number')), ) + user.set_feature_permissions(data.get('feature_permissions')) user.set_password(data['password']) db.session.add(user) try: @@ -224,6 +226,9 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict: setattr(user, key, empty_to_none(data[key])) else: setattr(user, key, data[key]) + if 'feature_permissions' in data or 'role' in data: + permissions_payload = data.get('feature_permissions', user.feature_permissions) + user.set_feature_permissions(permissions_payload) if new_password: user.set_password(new_password) if 'agent_ids' in data: diff --git a/backend/app/services/fixed_asset_history.py b/backend/app/services/fixed_asset_history.py new file mode 100644 index 00000000..ef10e3b4 --- /dev/null +++ b/backend/app/services/fixed_asset_history.py @@ -0,0 +1,325 @@ +""" +backend/app/services/fixed_asset_history.py + +用途:为固资管理提供“资产履历”共享盘检索能力,按资产编号/资产名称匹配履历文件。 +依赖:app.core.config.settings.Config、chat.py 里的预览代理会复用这里返回的共享盘文件路径。 +逻辑:聊天表格点击资产编号 -> chat API 调用本服务检索共享盘 -> 前端拿到候选履历文件后继续走既有预览弹窗。 +""" +from __future__ import annotations + +import os +import re +import subprocess +import threading +import time +from dataclasses import dataclass + +from flask import current_app, has_app_context + +from app.core.config.settings import Config + + +_CONNECT_LOCK = threading.Lock() +_LAST_CONNECT_AT = 0.0 +_CONNECT_COOLDOWN_SECONDS = 30.0 + + +@dataclass(slots=True) +class AssetHistoryCandidate: + """资产履历候选文件。""" + + path: str + relative_path: str + name: str + actual_ext: str + size_bytes: int + modified_at: str + score: int + match_reason: str + + def to_dict(self) -> dict[str, object]: + return { + "name": self.name, + "path": self.path, + "relative_path": self.relative_path, + "actual_ext": self.actual_ext, + "size_bytes": self.size_bytes, + "modified_at": self.modified_at, + "match_reason": self.match_reason, + "url": self.path, + } + + +class FixedAssetHistoryService: + """ + 固资履历检索服务。 + + AI 触发时机: + - 当聊天结果里已经拿到了具体资产编号,用户点击“资产编号”想看履历时调用; + - 输入必须至少包含资产编号或资产名称中的一个; + - 输出只返回共享盘上可预览的候选文件,不直接拼接文件内容。 + """ + + HISTORY_FILE_EXTENSIONS = {".xls", ".xlsx", ".pdf", ".doc", ".docx", ".txt"} + + @classmethod + def _get_runtime_setting(cls, key: str, default: str = "") -> str: + if has_app_context(): + try: + value = current_app.config.get(key) + if value is not None: + return str(value) + except Exception: + pass + return str(getattr(Config, key, default) or default) + + @classmethod + def is_enabled(cls) -> bool: + return bool(cls.get_share_root()) + + @classmethod + def get_share_root(cls) -> str: + return cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_ROOT').strip() + + @classmethod + def search_history_files( + cls, + *, + asset_id: str, + asset_name: str = "", + limit: int | None = None, + ) -> list[dict[str, object]]: + """ + 按资产编号/资产名称检索履历文件。 + + [STEP 1] 先尝试建立共享盘访问权限,避免 Windows 服务账号没有提前挂载网络盘。 + [STEP 2] 优先用资产编号做全局文件名命中,确保定位到唯一设备履历。 + [STEP 3] 再用资产名称命中同名文件夹/文件,补足部分历史文件只按设备名称归档的情况。 + """ + asset_id_value = cls._normalize_keyword(asset_id) + asset_name_value = cls._normalize_keyword(asset_name) + if not asset_id_value and not asset_name_value: + return [] + + root = cls.get_share_root() + if not root: + return [] + if not os.path.exists(root): + cls._ensure_share_connected(root) + if not os.path.isdir(root): + return [] + + max_results = max( + 1, + min(int(limit or cls._get_runtime_setting('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or 20), 50), + ) + candidates: dict[str, AssetHistoryCandidate] = {} + + if asset_id_value: + for current_root, _dirs, files in os.walk(root): + for filename in files: + candidate = cls._build_candidate( + root=root, + file_path=os.path.join(current_root, filename), + asset_id=asset_id_value, + asset_name=asset_name_value, + match_reason="asset_id", + ) + if candidate: + cls._merge_candidate(candidates, candidate) + + folder_candidates = cls._find_matching_folders(root, asset_name_value) + for folder_path in folder_candidates: + for current_root, _dirs, files in os.walk(folder_path): + for filename in files: + candidate = cls._build_candidate( + root=root, + file_path=os.path.join(current_root, filename), + asset_id=asset_id_value, + asset_name=asset_name_value, + match_reason="asset_name_folder", + ) + if candidate: + cls._merge_candidate(candidates, candidate) + + if asset_name_value: + for entry in os.scandir(root): + if not entry.is_file(): + continue + candidate = cls._build_candidate( + root=root, + file_path=entry.path, + asset_id=asset_id_value, + asset_name=asset_name_value, + match_reason="asset_name_file", + ) + if candidate: + cls._merge_candidate(candidates, candidate) + + ordered = sorted( + candidates.values(), + key=lambda item: (-item.score, item.relative_path.lower(), item.name.lower()), + ) + return [item.to_dict() for item in ordered[:max_results]] + + @classmethod + def _merge_candidate( + cls, + existing: dict[str, AssetHistoryCandidate], + candidate: AssetHistoryCandidate, + ) -> None: + previous = existing.get(candidate.path) + if previous is None or candidate.score > previous.score: + existing[candidate.path] = candidate + + @classmethod + def _find_matching_folders(cls, root: str, asset_name: str) -> list[str]: + if not asset_name: + return [] + matches: list[str] = [] + for entry in os.scandir(root): + if not entry.is_dir(): + continue + normalized_folder = cls._normalize_keyword(entry.name) + if asset_name and asset_name in normalized_folder: + matches.append(entry.path) + return matches + + @classmethod + def _build_candidate( + cls, + *, + root: str, + file_path: str, + asset_id: str, + asset_name: str, + match_reason: str, + ) -> AssetHistoryCandidate | None: + if not os.path.isfile(file_path): + return None + ext = os.path.splitext(file_path)[1].strip().lower() + if ext and ext not in cls.HISTORY_FILE_EXTENSIONS: + return None + + filename = os.path.basename(file_path) + searchable_parts = [ + cls._normalize_keyword(filename), + cls._normalize_keyword(os.path.relpath(file_path, root)), + ] + searchable_text = " ".join(part for part in searchable_parts if part) + if not searchable_text: + return None + + if asset_id and asset_id not in searchable_text: + return None + if asset_name and asset_name not in searchable_text and match_reason != "asset_id": + return None + + score = cls._score_candidate( + searchable_text=searchable_text, + filename=cls._normalize_keyword(filename), + asset_id=asset_id, + asset_name=asset_name, + match_reason=match_reason, + ) + if score <= 0: + return None + + stat = os.stat(file_path) + return AssetHistoryCandidate( + path=file_path, + relative_path=os.path.relpath(file_path, root).replace("/", "\\"), + name=filename, + actual_ext=ext.lstrip("."), + size_bytes=int(stat.st_size), + modified_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stat.st_mtime)), + score=score, + match_reason=match_reason, + ) + + @classmethod + def _score_candidate( + cls, + *, + searchable_text: str, + filename: str, + asset_id: str, + asset_name: str, + match_reason: str, + ) -> int: + score = 0 + if asset_id: + if asset_id in filename: + score += 120 + elif asset_id in searchable_text: + score += 80 + if asset_name: + if asset_name in filename: + score += 60 + elif asset_name in searchable_text: + score += 40 + if "履历" in filename: + score += 20 + if match_reason == "asset_name_folder": + score += 10 + return score + + @classmethod + def _normalize_keyword(cls, value: str | None) -> str: + text = str(value or "").strip().lower() + if not text: + return "" + return re.sub(r"[\s\\/_\-()()【】\[\],。,;;::]+", "", text) + + @classmethod + def _ensure_share_connected(cls, root: str) -> None: + """ + 尝试用配置的账号密码建立共享盘会话。 + + 账号密码只从环境变量读取,避免把敏感信息写进仓库。 + """ + username = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_USERNAME').strip() + password = cls._get_runtime_setting('FIXED_ASSET_HISTORY_SHARE_PASSWORD') + if not username or not password: + return + + share_root = cls._extract_server_share_root(root) + if not share_root: + return + + global _LAST_CONNECT_AT + now = time.time() + if now - _LAST_CONNECT_AT < _CONNECT_COOLDOWN_SECONDS: + return + + with _CONNECT_LOCK: + if time.time() - _LAST_CONNECT_AT < _CONNECT_COOLDOWN_SECONDS: + return + try: + subprocess.run( + [ + "net", + "use", + share_root, + password, + f"/user:{username}", + "/persistent:no", + ], + check=False, + capture_output=True, + text=True, + timeout=8, + ) + except Exception: + return + _LAST_CONNECT_AT = time.time() + + @staticmethod + def _extract_server_share_root(path_value: str) -> str: + normalized = str(path_value or "").strip().replace("/", "\\") + if not normalized.startswith("\\\\"): + return "" + parts = [part for part in normalized[2:].split("\\") if part] + if len(parts) < 2: + return "" + return f"\\\\{parts[0]}\\{parts[1]}" diff --git a/backend/app/services/maintenance_chat_service.py b/backend/app/services/maintenance_chat_service.py new file mode 100644 index 00000000..db875042 --- /dev/null +++ b/backend/app/services/maintenance_chat_service.py @@ -0,0 +1,229 @@ +""" +backend/app/services/maintenance_chat_service.py + +用途:设备维保助手的会话查询直答服务,用于把设备编号/名称查询转换成设备台账卡片。 +依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、SQLAlchemy、SSE JSON 输出。 +逻辑:chat.py 在设备维保助手命中查询意图时调用本服务;本服务查询台账和维修记录,写入聊天历史并返回结构化消息。 +""" + +from __future__ import annotations + +import json +import re +import time +from typing import Any, Iterator + +from flask import current_app +from sqlalchemy import or_ + +from app import db +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_AGENT_NAME = '设备维保助手' + + +def is_maintenance_chat_agent(agent: Any) -> bool: + """ + 判断当前 Agent 是否为设备维保助手。 + Args: + agent: Agent ORM 或代理对象。 + Returns: + 命中设备维保助手时返回 True。 + """ + name = str(getattr(agent, 'name', '') or '').strip() + return name == MAINTENANCE_AGENT_NAME or ('设备维保' in name and '助手' in name) + + +def _clean_text(value: Any) -> str: + return str(value or '').strip() + + +def extract_device_query_keyword(query: str) -> str | None: + """ + 从用户自然语言里提取设备编号或设备名称关键词。 + AI 触发时机:当用户在设备维保助手里询问“查询某设备/某编号/维修记录”时,用它判断是否走本地台账查询。 + Args: + query: 用户原始问题。 + Returns: + 设备编号或名称关键词;无法判断时返回 None。 + """ + text = _clean_text(query) + if not text: + return None + 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) + if code_match: + return code_match.group(0).strip() + digit_match = re.search(r'\b\d{6,}\b', text) + if digit_match: + return digit_match.group(0).strip() + + cleaned = re.sub( + r'(查询|查詢|查看|检索|一下|这条|這條|这个|這個|设备|設備|台账|台帳|信息|資料|维保|維保|维修|維修|记录|記錄|历史|歷史|的|了|请|請|帮我|幫我)', + ' ', + text, + ) + cleaned = re.sub(r'[\s,。,.??!!::;;]+', ' ', cleaned).strip() + return cleaned[:80] or None + + +def _find_device(keyword: str) -> MaintenanceDevice | None: + """按设备编号优先,其次按设备名称模糊匹配查找单台设备。""" + value = _clean_text(keyword) + if not value: + return None + exact = db.session.query(MaintenanceDevice).filter(MaintenanceDevice.device_code == value).first() + if exact: + return exact + like = f'%{value}%' + return ( + 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() + ) + + +def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, record_limit: int = 5) -> dict[str, Any]: + """构建设备台账卡片 payload,包含设备信息和最近维修记录。""" + record_limit = max(0, min(20, int(record_limit or 0))) + records = ( + db.session.query(MaintenanceRecord) + .filter(MaintenanceRecord.device_code == device.device_code) + .order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()) + .limit(record_limit) + .all() + ) if include_records and record_limit > 0 else [] + 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_device_query', + 'matched': True, + 'device': serialize_device(device), + 'records': serialized_records, + 'summary': { + 'recentRecordCount': len(serialized_records), + 'statusCounts': status_counts, + '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]: + """ + 查询设备台账并返回统一结构,供会话直答和 Dify Tool 共用。 + Args: + keyword: 设备编号或设备名称。 + include_records: 是否附带最近维修记录。 + record_limit: 最近维修记录最大返回条数。 + Returns: + 设备查询结果 payload。 + """ + device = _find_device(keyword) + if not device: + return { + 'source': 'maintenance_device_query', + 'matched': False, + 'keyword': keyword, + 'device': None, + 'records': [], + } + return _build_payload(device, include_records=include_records, record_limit=record_limit) + + +def supports(query: str, agent: Any) -> bool: + """ + 判断是否应由设备维保本地查询服务接管。 + Args: + query: 用户原始问题。 + agent: 当前 Agent。 + Returns: + True 表示命中设备查询意图。 + """ + return is_maintenance_chat_agent(agent) and bool(extract_device_query_keyword(query)) + + +def stream_chat( + query: str, + user: Any, + agent: Any, + conversation_id: str | None = None, + session_id: str | None = None, +) -> Iterator[str]: + """ + 以 SSE 返回设备查询结果,并写入 ChatLog 供历史会话回放。 + Args: + query: 用户原始问题。 + user: 当前用户代理对象。 + agent: 当前 Agent 代理对象。 + conversation_id: 外部会话 ID,设备本地查询会沿用本地 session。 + session_id: 本地会话 ID。 + 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 result.get('matched'): + content = '已查询设备台账信息,下面是匹配结果。' + payload = result + message_type = 'maintenance-device-result' + else: + content = f'未找到与“{keyword or query}”匹配的设备台账信息,请检查设备编号或设备名称。' + payload = result + message_type = 'text' + + 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=message_type if message_type != 'text' else None, + payload=payload, + ) + 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 chat: %s', exc) + db.session.rollback() + + yield f"data: {json.dumps({ + 'event': 'message_end', + 'answer': content, + 'replace_answer': True, + 'type': message_type, + 'payload': payload, + 'message_payload': payload, + 'chat_log_id': chat_log_id, + 'conversation_id': final_conversation_id, + 'metadata': {'source': 'maintenance_device_query'}, + }, ensure_ascii=False)}\n\n" + + +class MaintenanceChatService: + """设备维保助手会话查询服务门面,供 chat.py 按统一 Service 风格调用。""" + + supports = staticmethod(supports) + stream_chat = staticmethod(stream_chat) diff --git a/backend/app/services/maintenance_ledger_service.py b/backend/app/services/maintenance_ledger_service.py new file mode 100644 index 00000000..9fbd4b9c --- /dev/null +++ b/backend/app/services/maintenance_ledger_service.py @@ -0,0 +1,423 @@ +""" +backend/app/services/maintenance_ledger_service.py + +用途:设备维保台账的查询、保存、Excel 模板与导入业务编排。 +依赖:MaintenanceDevice/MaintenanceAuditLog、openpyxl、统一 AppError。 +逻辑:API 层只做请求解析;本服务负责字段校验、upsert、审计与 Excel 行级导入。 +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from datetime import date, datetime +from io import BytesIO +from typing import Any + +from openpyxl import Workbook, load_workbook +from openpyxl.styles import Font, PatternFill +from sqlalchemy import or_ + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import MaintenanceAuditLog, MaintenanceDevice + +DEVICE_STATUS_VALUES = {'in_use', 'disabled', 'scrapped', 'sold'} +ACCOUNT_SET_VALUES = {'和信', '科技', '电子', '和宏智'} +DEFAULT_ACCOUNT_SET = '和信' + +TEMPLATE_COLUMNS = [ + '设备编号', + '设备名称', + '型号规格', + '使用部门', + '安装地点', + '设备状态', + '制造厂家', + '进厂日期', + '生产日期', + '启用日期', + '责任人用户名', + '维护周期', + '原值', + '残值', + '账套', + '备注', +] + +HEADER_MAP = { + '设备编号': 'device_code', + '设备名称': 'device_name', + '型号规格': 'model_spec', + '使用部门': 'department', + '安装地点': 'install_location', + '设备状态': 'device_status', + '制造厂家': 'manufacturer', + '进厂日期': 'entry_date', + '生产日期': 'production_date', + '启用日期': 'start_date', + '责任人用户名': 'responsible_user', + '维护周期': 'maintenance_cycle', + '原值': 'original_value', + '残值': 'residual_value', + '账套': 'account_set', + '备注': 'remark', +} + + +@dataclass +class ImportResult: + """Excel 导入统计结果。""" + + total: int = 0 + created: int = 0 + updated: int = 0 + failed: int = 0 + errors: list[dict[str, Any]] | None = None + + +def _clean_text(value: Any) -> str | None: + text = str(value or '').strip() + return text or None + + +def _parse_date(value: Any, field_name: str) -> date | None: + """ + 解析台账日期字段。 + Args: + value: Excel/JSON 中传入的日期、日期时间或 YYYY-MM-DD 字符串。 + field_name: 字段名,用于错误提示。 + Returns: + date 或 None。 + Raises: + ValidationError: 日期格式不合法。 + """ + if value in (None, ''): + return None + if isinstance(value, datetime): + return value.date() + if isinstance(value, date): + return value + text = str(value).strip() + for fmt in ('%Y-%m-%d', '%Y/%m/%d'): + try: + return datetime.strptime(text, fmt).date() + except ValueError: + continue + raise ValidationError(f'{field_name} must be YYYY-MM-DD') + + +def _parse_amount(value: Any, field_name: str) -> float | None: + """ + 解析设备金额字段。 + Args: + value: JSON/Excel 中传入的金额,可为空、数字或数字字符串。 + field_name: 字段名,用于错误提示。 + Returns: + 两位小数浮点数或 None。 + Raises: + ValidationError: 金额格式非法或小于 0。 + """ + if value in (None, ''): + return None + try: + amount = round(float(str(value).replace(',', '').strip()), 2) + except (TypeError, ValueError) as exc: + raise ValidationError(f'{field_name} must be numeric') from exc + if amount < 0: + raise ValidationError(f'{field_name} must be greater than or equal to 0') + return amount + + +def _device_to_audit_dict(device: MaintenanceDevice) -> dict[str, Any]: + """设备 ORM 转审计快照 dict。""" + return serialize_device(device) + + +def _operator_name(user: Any | None) -> str | None: + """从当前用户对象中取展示用户名;未登录时返回 None。""" + if not user: + return None + return getattr(user, 'real_name', None) or getattr(user, 'username', None) or str(getattr(user, 'id', '') or '') or None + + +def _write_audit( + *, + object_type: str, + object_id: int | None, + action: str, + before_data: dict[str, Any] | None, + after_data: dict[str, Any] | None, + operator_name: str | None, + request_id: str | None, +) -> None: + """写入设备维保域审计日志,随业务事务一起提交。""" + db.session.add( + MaintenanceAuditLog( + object_type=object_type, + object_id=object_id, + action=action, + before_data=json.dumps(before_data, ensure_ascii=False, default=str) if before_data else None, + after_data=json.dumps(after_data, ensure_ascii=False, default=str) if after_data else None, + operator_name=operator_name, + request_id=request_id, + ) + ) + + +def serialize_device(device: MaintenanceDevice) -> dict[str, Any]: + """设备 ORM 转 API dict,保持前端 camelCase 命名。""" + return { + 'id': device.id, + 'deviceCode': device.device_code, + 'deviceName': device.device_name, + 'modelSpec': device.model_spec, + 'department': device.department, + 'installLocation': device.install_location, + 'deviceStatus': device.device_status, + 'manufacturer': device.manufacturer, + 'entryDate': device.entry_date.isoformat() if device.entry_date else None, + 'productionDate': device.production_date.isoformat() if device.production_date else None, + 'startDate': device.start_date.isoformat() if device.start_date else None, + 'responsibleUser': device.responsible_user, + 'maintenanceCycle': device.maintenance_cycle, + 'originalValue': float(device.original_value) if device.original_value is not None else None, + 'residualValue': float(device.residual_value) if device.residual_value is not None else None, + 'accountSet': device.account_set, + 'remark': device.remark, + 'createdAt': device.created_at.isoformat() if device.created_at else None, + 'updatedAt': device.updated_at.isoformat() if device.updated_at else None, + } + + +def _normalize_payload(data: dict[str, Any]) -> dict[str, Any]: + """ + 标准化设备台账入参。 + Args: + data: 前端 JSON 或 Excel 行映射。 + Returns: + 可直接写入 MaintenanceDevice 的 snake_case dict。 + Raises: + ValidationError: 必填字段缺失或状态/日期非法。 + """ + device_code = _clean_text(data.get('deviceCode') or data.get('device_code')) + device_name = _clean_text(data.get('deviceName') or data.get('device_name')) + if not device_code: + raise ValidationError('deviceCode is required') + if not device_name: + raise ValidationError('deviceName is required') + + status = _clean_text(data.get('deviceStatus') or data.get('device_status')) or 'in_use' + status_map = {'在用': 'in_use', '停用': 'disabled', '报废': 'scrapped', '出售': 'sold', '已出售': 'sold'} + status = status_map.get(status, status) + if status not in DEVICE_STATUS_VALUES: + raise ValidationError('deviceStatus is invalid') + account_set = _clean_text(data.get('accountSet') or data.get('account_set')) or DEFAULT_ACCOUNT_SET + if account_set and account_set not in ACCOUNT_SET_VALUES: + raise ValidationError('accountSet is invalid') + + return { + 'device_code': device_code, + 'device_name': device_name, + 'model_spec': _clean_text(data.get('modelSpec') or data.get('model_spec')), + 'department': _clean_text(data.get('department')), + 'install_location': _clean_text(data.get('installLocation') or data.get('install_location')), + 'device_status': status, + 'manufacturer': _clean_text(data.get('manufacturer')), + 'entry_date': _parse_date(data.get('entryDate') or data.get('entry_date'), 'entryDate'), + 'production_date': _parse_date(data.get('productionDate') or data.get('production_date'), 'productionDate'), + 'start_date': _parse_date(data.get('startDate') or data.get('start_date'), 'startDate'), + 'responsible_user': _clean_text(data.get('responsibleUser') or data.get('responsible_user')), + 'maintenance_cycle': _clean_text(data.get('maintenanceCycle') or data.get('maintenance_cycle')), + 'original_value': _parse_amount(data.get('originalValue') or data.get('original_value'), 'originalValue'), + 'residual_value': _parse_amount(data.get('residualValue') or data.get('residual_value'), 'residualValue'), + 'account_set': account_set, + 'remark': _clean_text(data.get('remark')), + } + + +def list_devices(*, keyword: str | None = None, status: str | None = None, page: int = 1, page_size: int = 20) -> dict[str, Any]: + """分页查询设备台账,支持关键字与状态筛选。""" + query = db.session.query(MaintenanceDevice) + keyword = _clean_text(keyword) + if keyword: + like = f'%{keyword}%' + query = query.filter( + or_( + MaintenanceDevice.device_code.ilike(like), + MaintenanceDevice.device_name.ilike(like), + ) + ) + if status: + query = query.filter(MaintenanceDevice.device_status == status) + total = query.count() + page = max(1, page) + page_size = max(1, min(200, page_size)) + items = ( + query.order_by(MaintenanceDevice.updated_at.desc(), MaintenanceDevice.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + .all() + ) + return {'items': [serialize_device(item) for item in items], 'total': total, 'page': page, 'pageSize': page_size} + + +def get_device(device_id: int) -> dict[str, Any]: + """读取单台设备详情。""" + device = db.session.get(MaintenanceDevice, device_id) + if not device: + raise NotFoundError('Device not found') + return serialize_device(device) + + +def create_device(data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]: + """新增设备台账,并写入审计日志。""" + values = _normalize_payload(data) + if db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first(): + raise ConflictError('deviceCode exists', code='MAINTENANCE.DEVICE_CODE_EXISTS') + now_operator = _operator_name(operator) + device = MaintenanceDevice(**values, created_by=now_operator, updated_by=now_operator) + db.session.add(device) + db.session.flush() + after = _device_to_audit_dict(device) + _write_audit( + object_type='device', + object_id=device.id, + action='create', + before_data=None, + after_data=after, + operator_name=now_operator, + request_id=request_id, + ) + db.session.commit() + return serialize_device(device) + + +def update_device(device_id: int, data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]: + """更新设备台账,并写入审计日志。""" + device = db.session.get(MaintenanceDevice, device_id) + if not device: + raise NotFoundError('Device not found') + values = _normalize_payload(data) + exists = db.session.query(MaintenanceDevice).filter( + MaintenanceDevice.device_code == values['device_code'], + MaintenanceDevice.id != device_id, + ).first() + if exists: + raise ConflictError('deviceCode exists', code='MAINTENANCE.DEVICE_CODE_EXISTS') + before = _device_to_audit_dict(device) + for key, value in values.items(): + setattr(device, key, value) + device.updated_by = _operator_name(operator) + db.session.flush() + after = _device_to_audit_dict(device) + _write_audit( + object_type='device', + object_id=device.id, + action='update', + before_data=before, + after_data=after, + operator_name=_operator_name(operator), + request_id=request_id, + ) + db.session.commit() + return serialize_device(device) + + +def build_import_template() -> bytes: + """生成设备台账导入模板 Excel。""" + wb = Workbook() + ws = wb.active + ws.title = '设备台账导入' + ws.append(TEMPLATE_COLUMNS) + ws.append(['A022700978', '注塑件自动冲切水口机', 'ML-ZS030', '注塑部', '二期车间一楼注塑区', '在用', '昆山开发区盟荣机械厂', '2021-06-18', '2021-05-20', '2021-06-18', '张三', '按需维修', 120000, 12000, '和信', '示例行,可删除']) + header_fill = PatternFill(fill_type='solid', fgColor='D9EAF7') + for col in range(1, len(TEMPLATE_COLUMNS) + 1): + cell = ws.cell(row=1, column=col) + cell.font = Font(bold=True) + cell.fill = header_fill + ws.column_dimensions[cell.column_letter].width = 18 + out = BytesIO() + wb.save(out) + return out.getvalue() + + +def import_devices_from_excel(file_obj: Any, *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]: + """ + 从 Excel 模板导入设备台账。 + Args: + file_obj: Flask upload file object。 + operator: 当前登录用户。 + request_id: 请求 ID。 + Returns: + 导入统计,含行级错误。 + """ + filename = (getattr(file_obj, 'filename', '') or '').lower() + if not filename.endswith('.xlsx'): + raise ValidationError('Only .xlsx template is supported') + try: + wb = load_workbook(file_obj, data_only=True) + except Exception as exc: + raise ValidationError('Invalid Excel file') from exc + ws = wb.active + headers = [str(cell.value or '').strip() for cell in ws[1]] + missing = [name for name in ('设备编号', '设备名称') if name not in headers] + if missing: + raise ValidationError('Template columns missing', details={'missing': missing}) + idx = {name: headers.index(name) for name in headers if name} + result = ImportResult(errors=[]) + operator_name = _operator_name(operator) + + for row_no, row in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2): + if not any(row): + continue + result.total += 1 + raw = {} + for header, field in HEADER_MAP.items(): + if header in idx and idx[header] < len(row): + raw[field] = row[idx[header]] + 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: + before = _device_to_audit_dict(device) + for key, value in values.items(): + setattr(device, key, value) + device.updated_by = operator_name + db.session.flush() + _write_audit( + object_type='device', + object_id=device.id, + action='import_update', + before_data=before, + after_data=_device_to_audit_dict(device), + operator_name=operator_name, + request_id=request_id, + ) + result.updated += 1 + else: + device = MaintenanceDevice(**values, created_by=operator_name, updated_by=operator_name) + db.session.add(device) + db.session.flush() + _write_audit( + object_type='device', + object_id=device.id, + action='import_create', + before_data=None, + after_data=_device_to_audit_dict(device), + operator_name=operator_name, + request_id=request_id, + ) + result.created += 1 + except Exception as exc: + result.failed += 1 + result.errors.append({'row': row_no, 'message': str(getattr(exc, 'message', None) or exc)}) + db.session.commit() + return { + 'total': result.total, + 'created': result.created, + 'updated': result.updated, + 'failed': result.failed, + 'errors': result.errors or [], + } diff --git a/backend/app/services/maintenance_record_service.py b/backend/app/services/maintenance_record_service.py new file mode 100644 index 00000000..e641bd33 --- /dev/null +++ b/backend/app/services/maintenance_record_service.py @@ -0,0 +1,307 @@ +""" +backend/app/services/maintenance_record_service.py + +用途:设备维修记录查询与新增业务编排。 +依赖:MaintenanceRecord/MaintenanceDevice、统一 AppError、审计日志写入。 +逻辑:新增记录时按设备编号带出台账快照;查询结果供 Agent 会话和右侧面板复用。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from io import BytesIO +from typing import Any + +from openpyxl import Workbook +from openpyxl.styles import Font, PatternFill +from sqlalchemy import or_ + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import MaintenanceDevice, MaintenanceRecord +from app.services.maintenance_ledger_service import _operator_name, _parse_date, _write_audit + +REPAIR_STATUS_VALUES = {'pending', 'processing', 'done', 'cancelled'} +REPAIR_STATUS_LABELS = { + 'pending': '待维修', + 'processing': '维修中', + 'done': '已完成', + 'cancelled': '已取消', +} + + +def _clean_text(value: Any) -> str | None: + text = str(value or '').strip() + return text or None + + +def serialize_record(record: MaintenanceRecord) -> dict[str, Any]: + """维修记录 ORM 转 API dict。""" + return { + 'id': record.id, + 'deviceId': record.device_id, + 'deviceCode': record.device_code, + 'deviceName': record.device_name, + 'modelSpec': record.model_spec, + 'installLocation': record.install_location, + 'reportDate': record.report_date.isoformat() if record.report_date else None, + 'repairCategory': record.repair_category, + 'faultDescription': record.fault_description, + 'reporter': record.reporter, + 'approver': record.approver, + 'repairStatus': record.repair_status, + 'repairDate': record.repair_date.isoformat() if record.repair_date else None, + 'repairUnit': record.repair_unit, + 'repairer': record.repairer, + 'repairCost': record.repair_cost, + 'repairHours': record.repair_hours, + 'repairDescription': record.repair_description, + 'sourceOrderNo': record.source_order_no, + 'createdAt': record.created_at.isoformat() if record.created_at else None, + 'updatedAt': record.updated_at.isoformat() if record.updated_at else None, + } + + +def _record_to_audit_dict(record: MaintenanceRecord) -> dict[str, Any]: + """维修记录 ORM 转审计快照。""" + return serialize_record(record) + + +def _normalize_payload(data: dict[str, Any]) -> dict[str, Any]: + """ + 标准化维修记录入参。 + Args: + data: 前端 JSON。 + Returns: + 可写入 MaintenanceRecord 的 snake_case dict。 + Raises: + ValidationError: 必填字段缺失或日期/状态非法。 + """ + device_code = _clean_text(data.get('deviceCode') or data.get('device_code')) + fault_description = _clean_text(data.get('faultDescription') or data.get('fault_description')) + if not device_code: + raise ValidationError('deviceCode is required') + if not fault_description: + raise ValidationError('faultDescription is required') + status = _clean_text(data.get('repairStatus') or data.get('repair_status')) or 'pending' + status_map = {'待维修': 'pending', '维修中': 'processing', '已完成': 'done', '已取消': 'cancelled'} + status = status_map.get(status, status) + if status not in REPAIR_STATUS_VALUES: + raise ValidationError('repairStatus is invalid') + report_date = _parse_date(data.get('reportDate') or data.get('report_date') or date.today().isoformat(), 'reportDate') + if not report_date: + raise ValidationError('reportDate is required') + return { + 'device_code': device_code, + 'report_date': report_date, + 'repair_category': _clean_text(data.get('repairCategory') or data.get('repair_category')), + 'fault_description': fault_description, + 'reporter': _clean_text(data.get('reporter')), + 'approver': _clean_text(data.get('approver')), + 'repair_status': status, + 'repair_date': _parse_date(data.get('repairDate') or data.get('repair_date'), 'repairDate'), + 'repair_unit': _clean_text(data.get('repairUnit') or data.get('repair_unit')), + 'repairer': _clean_text(data.get('repairer')), + 'repair_cost': _clean_text(data.get('repairCost') or data.get('repair_cost')), + 'repair_hours': _clean_text(data.get('repairHours') or data.get('repair_hours')), + 'repair_description': _clean_text(data.get('repairDescription') or data.get('repair_description')), + 'source_order_no': _clean_text(data.get('sourceOrderNo') or data.get('source_order_no')), + } + + +def list_records( + *, + keyword: str | None = None, + device_code: str | None = None, + status: str | None = None, + page: int = 1, + page_size: int = 20, +) -> dict[str, Any]: + """分页查询维修记录。""" + query = _records_query(keyword=keyword, device_code=device_code, status=status) + total = query.count() + page = max(1, page) + page_size = max(1, min(200, page_size)) + items = ( + query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()) + .offset((page - 1) * page_size) + .limit(page_size) + .all() + ) + 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): + """构造维修记录查询,供列表和导出复用。""" + query = db.session.query(MaintenanceRecord) + if device_code: + query = query.filter(MaintenanceRecord.device_code == device_code) + if status: + query = query.filter(MaintenanceRecord.repair_status == status) + keyword = _clean_text(keyword) + if keyword: + like = f'%{keyword}%' + query = query.filter( + or_( + MaintenanceRecord.device_code.ilike(like), + MaintenanceRecord.device_name.ilike(like), + ) + ) + return query + + +def build_records_export(*, keyword: str | None = None, device_code: str | None = None, status: str | None = None) -> bytes: + """按当前筛选条件导出维修记录 Excel。""" + rows = ( + _records_query(keyword=keyword, device_code=device_code, status=status) + .order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()) + .limit(5000) + .all() + ) + wb = Workbook() + ws = wb.active + ws.title = '维修记录' + headers = [ + '设备编号', + '设备名称', + '型号规格', + '设备位置', + '报修日期', + '维修类别', + '故障描述', + '维修状态', + '维修日期', + '维修单位', + '维修人', + '维修费用', + '维修工时', + '维修说明', + '报修人', + '审批人', + '来源工单号', + ] + ws.append(headers) + for item in rows: + ws.append( + [ + item.device_code, + item.device_name, + item.model_spec, + item.install_location, + item.report_date.isoformat() if item.report_date else '', + item.repair_category, + item.fault_description, + REPAIR_STATUS_LABELS.get(item.repair_status, item.repair_status), + item.repair_date.isoformat() if item.repair_date else '', + item.repair_unit, + item.repairer, + item.repair_cost, + item.repair_hours, + item.repair_description, + item.reporter, + item.approver, + item.source_order_no, + ] + ) + header_fill = PatternFill(fill_type='solid', fgColor='D9EAF7') + for col in range(1, len(headers) + 1): + cell = ws.cell(row=1, column=col) + cell.font = Font(bold=True) + cell.fill = header_fill + ws.column_dimensions[cell.column_letter].width = 18 + out = BytesIO() + wb.save(out) + return out.getvalue() + + +def get_record(record_id: int) -> dict[str, Any]: + """读取维修记录详情。""" + record = db.session.get(MaintenanceRecord, record_id) + if not record: + raise NotFoundError('Maintenance record not found') + return serialize_record(record) + + +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, + } + ) + operator_name = _operator_name(operator) + record = MaintenanceRecord(**values, created_by=operator_name, updated_by=operator_name) + db.session.add(record) + db.session.flush() + _write_audit( + object_type='record', + object_id=record.id, + action='create', + before_data=None, + after_data=_record_to_audit_dict(record), + operator_name=operator_name, + request_id=request_id, + ) + db.session.commit() + return serialize_record(record) + + +def update_record(record_id: int, data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]: + """更新维修记录,并重新按设备编号刷新台账快照。""" + record = db.session.get(MaintenanceRecord, record_id) + if not record: + 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, + } + ) + for key, value in values.items(): + setattr(record, key, value) + operator_name = _operator_name(operator) + record.updated_by = operator_name + db.session.flush() + _write_audit( + object_type='record', + object_id=record.id, + action='update', + before_data=before, + after_data=_record_to_audit_dict(record), + operator_name=operator_name, + request_id=request_id, + ) + db.session.commit() + return serialize_record(record) + + +def delete_record(record_id: int, *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]: + """删除维修记录,并写入删除审计。""" + record = db.session.get(MaintenanceRecord, record_id) + if not record: + raise NotFoundError('Maintenance record not found') + before = _record_to_audit_dict(record) + operator_name = _operator_name(operator) + _write_audit( + object_type='record', + object_id=record.id, + action='delete', + before_data=before, + after_data=None, + operator_name=operator_name, + request_id=request_id, + ) + db.session.delete(record) + db.session.commit() + return {'deleted': True, 'id': record_id} diff --git a/backend/app/services/maintenance_tools/__init__.py b/backend/app/services/maintenance_tools/__init__.py new file mode 100644 index 00000000..2a7fe8ab --- /dev/null +++ b/backend/app/services/maintenance_tools/__init__.py @@ -0,0 +1,8 @@ +""" +backend/app/services/maintenance_tools/__init__.py + +用途:设备维保 Dify Tool 服务包入口。 +依赖:openapi_spec 等子模块。 +逻辑:api/maintenance_tools.py 通过本包导入 OpenAPI 构建能力,后续可继续扩展工具编排。 +""" + diff --git a/backend/app/services/maintenance_tools/openapi_spec.py b/backend/app/services/maintenance_tools/openapi_spec.py new file mode 100644 index 00000000..dcafcd52 --- /dev/null +++ b/backend/app/services/maintenance_tools/openapi_spec.py @@ -0,0 +1,123 @@ +""" +backend/app/services/maintenance_tools/openapi_spec.py + +用途:构建设备维保助手 Dify Tool API 的 OpenAPI 描述。 +依赖:标准 typing。 +逻辑:/api/maintenance/tools/openapi.json 调用本模块;Dify 导入后可调用只读设备台账与维修记录查询工具。 +""" + +from __future__ import annotations + +from typing import Any + + +def _str_prop(description: str) -> dict[str, Any]: + """构造字符串字段描述。""" + return {"type": "string", "description": description} + + +def _bool_prop(description: str, *, default: bool = False) -> dict[str, Any]: + """构造布尔字段描述。""" + return {"type": "boolean", "description": description, "default": default} + + +def _int_prop(description: str, *, default: int | None = None) -> dict[str, Any]: + """构造整数字段描述。""" + prop: dict[str, Any] = {"type": "integer", "description": description} + if default is not None: + prop["default"] = default + return prop + + +def _post_op( + operation_id: str, + summary: str, + properties: dict[str, Any], + *, + required: list[str] | None = None, +) -> dict[str, Any]: + """构造 Dify Tool 兼容的 POST OpenAPI 操作。""" + schema: dict[str, Any] = {"type": "object", "properties": properties} + if required: + schema["required"] = required + return { + "post": { + "operationId": operation_id, + "summary": summary, + "description": summary, + "parameters": [], + "requestBody": { + "required": True, + "content": {"application/json": {"schema": schema}}, + }, + "responses": { + "200": { + "description": "Tool response. ok=true 表示调用成功;matched=false 表示未匹配到设备或记录。", + "content": {"application/json": {"schema": {"type": "object"}}}, + } + }, + "security": [{"BearerAuth": []}, {"IntegrationKey": []}], + } + } + + +def build_maintenance_openapi_spec(base_url: str) -> dict[str, Any]: + """ + 构建设备维保 Dify Tool OpenAPI。 + Args: + base_url: HXOPS 对外 Tool API 根地址。 + Returns: + OpenAPI 3.0 dict。 + """ + server = str(base_url or "").strip().rstrip("/") + if not server.endswith("/api/maintenance"): + server = f"{server}/api/maintenance" if server else "/api/maintenance" + + return { + "openapi": "3.0.0", + "info": { + "title": "Maintenance Tools", + "version": "1.0.0", + "description": ( + "设备维保助手只读 Tool API。适合 Dify 处理复杂自然语言问法时查询设备台账、最近维修记录;" + "新增、编辑、删除等配置动作不得通过 Dify Tool 执行,应由 HXOPS 右侧管理面板完成。" + "鉴权:Authorization Bearer 或 X-Integration-Key。" + ), + }, + "servers": [{"url": server, "description": "HXOPS_TOOLS_API_BASE"}], + "paths": { + "/tools/query_device": _post_op( + "queryMaintenanceDevice", + "查询设备台账信息,可附带最近维修记录", + { + "keyword": _str_prop("设备编号或设备名称,例如 A022700978 或 注塑件自动冲切水口机"), + "include_records": _bool_prop("是否返回最近维修记录", default=True), + "record_limit": _int_prop("最多返回几条最近维修记录,建议 3-10", default=5), + }, + required=["keyword"], + ), + "/tools/query_records": _post_op( + "queryMaintenanceRecords", + "查询设备维修记录", + { + "keyword": _str_prop("设备编号或设备名称关键词"), + "status": _str_prop("维修状态,可选:pending、processing、done、cancelled"), + "limit": _int_prop("最多返回记录数,建议 5-20", default=10), + }, + required=["keyword"], + ), + }, + "components": { + "securitySchemes": { + "BearerAuth": {"type": "http", "scheme": "bearer"}, + "IntegrationKey": { + "type": "apiKey", + "in": "header", + "name": "X-Integration-Key", + "description": "与 Bearer 二选一", + }, + } + }, + "security": [{"BearerAuth": []}, {"IntegrationKey": []}], + } + diff --git a/backend/app/services/minio_service.py b/backend/app/services/minio_service.py index ade0019f..45a919e8 100644 --- a/backend/app/services/minio_service.py +++ b/backend/app/services/minio_service.py @@ -88,6 +88,25 @@ class MinioService: base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/') return f"{base_url}/{self.bucket_name}/{object_name}" + def get_file_bytes(self, object_name: str) -> bytes: + """ + 读取对象的原始字节内容。 + + 用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。 + 参数约束:object_name 必须是已存储的对象名,不接受外部 URL。 + """ + local_path = os.path.join('data/agent-guides', object_name) + if os.path.exists(local_path): + with open(local_path, 'rb') as file_obj: + return file_obj.read() + + response = self.client.get_object(self.bucket_name, object_name) + try: + return response.read() + finally: + response.close() + response.release_conn() + def delete_file(self, object_name: str): try: self.client.remove_object(self.bucket_name, object_name) diff --git a/backend/migrations/versions/a1b2c3d4e610_add_agent_guide_usage.py b/backend/migrations/versions/a1b2c3d4e610_add_agent_guide_usage.py new file mode 100644 index 00000000..610ed2e1 --- /dev/null +++ b/backend/migrations/versions/a1b2c3d4e610_add_agent_guide_usage.py @@ -0,0 +1,27 @@ +"""add agent guide usage + +Revision ID: a1b2c3d4e610 +Revises: fe5f6a7b8c9d +Create Date: 2026-07-05 23:40:00.000000 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'a1b2c3d4e610' +down_revision = 'fe5f6a7b8c9d' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + 'agent_guides', + sa.Column('guide_usage', sa.String(length=50), nullable=False, server_default='general'), + ) + op.alter_column('agent_guides', 'guide_usage', server_default=None) + + +def downgrade(): + op.drop_column('agent_guides', 'guide_usage') diff --git a/backend/migrations/versions/fd4e5f6a7b8c_add_maintenance_ledger_tables.py b/backend/migrations/versions/fd4e5f6a7b8c_add_maintenance_ledger_tables.py new file mode 100644 index 00000000..2a2946c6 --- /dev/null +++ b/backend/migrations/versions/fd4e5f6a7b8c_add_maintenance_ledger_tables.py @@ -0,0 +1,102 @@ +"""add maintenance ledger tables + +Revision ID: fd4e5f6a7b8c +Revises: fc3d4e5f6a7b +Create Date: 2026-07-03 09:30:00.000000 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'fd4e5f6a7b8c' +down_revision = 'fc3d4e5f6a7b' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'maintenance_devices', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('device_code', sa.String(length=80), nullable=False), + sa.Column('device_name', sa.String(length=200), nullable=False), + sa.Column('model_spec', sa.String(length=200), nullable=True), + sa.Column('department', sa.String(length=120), nullable=True), + sa.Column('install_location', sa.String(length=255), nullable=True), + sa.Column('device_status', sa.String(length=30), nullable=False), + sa.Column('manufacturer', sa.String(length=200), nullable=True), + sa.Column('entry_date', sa.Date(), nullable=True), + sa.Column('production_date', sa.Date(), nullable=True), + sa.Column('start_date', sa.Date(), nullable=True), + sa.Column('responsible_user', sa.String(length=120), nullable=True), + sa.Column('maintenance_cycle', sa.String(length=80), nullable=True), + sa.Column('original_value', sa.Numeric(14, 2), nullable=True), + sa.Column('residual_value', sa.Numeric(14, 2), nullable=True), + sa.Column('account_set', sa.String(length=40), nullable=True), + sa.Column('remark', sa.Text(), nullable=True), + sa.Column('created_by', sa.String(length=120), nullable=True), + sa.Column('updated_by', sa.String(length=120), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('device_code', name='uq_maintenance_devices_device_code'), + ) + op.create_index('ix_maintenance_devices_location', 'maintenance_devices', ['install_location'], unique=False) + op.create_index('ix_maintenance_devices_name', 'maintenance_devices', ['device_name'], unique=False) + + op.create_table( + 'maintenance_audit_logs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('object_type', sa.String(length=40), nullable=False), + sa.Column('object_id', sa.Integer(), nullable=True), + sa.Column('action', sa.String(length=40), nullable=False), + sa.Column('before_data', sa.Text(), nullable=True), + sa.Column('after_data', sa.Text(), nullable=True), + sa.Column('operator_name', sa.String(length=120), nullable=True), + sa.Column('request_id', sa.String(length=80), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + + op.create_table( + 'maintenance_records', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('device_id', sa.Integer(), nullable=True), + sa.Column('device_code', sa.String(length=80), nullable=False), + sa.Column('device_name', sa.String(length=200), nullable=True), + sa.Column('model_spec', sa.String(length=200), nullable=True), + sa.Column('install_location', sa.String(length=255), nullable=True), + sa.Column('report_date', sa.Date(), nullable=False), + sa.Column('repair_category', sa.String(length=80), nullable=True), + sa.Column('fault_description', sa.Text(), nullable=False), + sa.Column('reporter', sa.String(length=120), nullable=True), + sa.Column('approver', sa.String(length=120), nullable=True), + sa.Column('repair_status', sa.String(length=30), nullable=False), + sa.Column('repair_date', sa.Date(), nullable=True), + sa.Column('repair_unit', sa.String(length=200), nullable=True), + sa.Column('repairer', sa.String(length=120), nullable=True), + sa.Column('repair_cost', sa.String(length=40), nullable=True), + sa.Column('repair_hours', sa.String(length=40), nullable=True), + sa.Column('repair_description', sa.Text(), nullable=True), + sa.Column('source_order_no', sa.String(length=120), nullable=True), + sa.Column('created_by', sa.String(length=120), nullable=True), + sa.Column('updated_by', sa.String(length=120), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_maintenance_records_device_code', 'maintenance_records', ['device_code'], unique=False) + op.create_index('ix_maintenance_records_report_date', 'maintenance_records', ['report_date'], unique=False) + op.create_index('ix_maintenance_records_status', 'maintenance_records', ['repair_status'], unique=False) + + +def downgrade(): + op.drop_index('ix_maintenance_records_status', table_name='maintenance_records') + op.drop_index('ix_maintenance_records_report_date', table_name='maintenance_records') + op.drop_index('ix_maintenance_records_device_code', table_name='maintenance_records') + op.drop_table('maintenance_records') + op.drop_table('maintenance_audit_logs') + op.drop_index('ix_maintenance_devices_name', table_name='maintenance_devices') + op.drop_index('ix_maintenance_devices_location', table_name='maintenance_devices') + op.drop_table('maintenance_devices') diff --git a/backend/migrations/versions/fe5f6a7b8c9d_add_user_feature_permissions.py b/backend/migrations/versions/fe5f6a7b8c9d_add_user_feature_permissions.py new file mode 100644 index 00000000..933031b7 --- /dev/null +++ b/backend/migrations/versions/fe5f6a7b8c9d_add_user_feature_permissions.py @@ -0,0 +1,39 @@ +"""add user feature permissions + +Revision ID: fe5f6a7b8c9d +Revises: fd4e5f6a7b8c +Create Date: 2026-07-05 23:00:00.000000 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'fe5f6a7b8c9d' +down_revision = 'fd4e5f6a7b8c' +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + 'users', + sa.Column( + 'feature_permissions', + sa.JSON(), + nullable=False, + server_default=sa.text("'{}'::json"), + ), + ) + op.execute( + """ + UPDATE users + SET feature_permissions = '{"training_hr_manage": true}'::json + WHERE role = 'hr' + """ + ) + op.alter_column('users', 'feature_permissions', server_default=None) + + +def downgrade(): + op.drop_column('users', 'feature_permissions') diff --git a/backend/tests/services/admin/test_training_exam_pdf_service.py b/backend/tests/services/admin/test_training_exam_pdf_service.py new file mode 100644 index 00000000..db00ee1c --- /dev/null +++ b/backend/tests/services/admin/test_training_exam_pdf_service.py @@ -0,0 +1,209 @@ +""" +tests/services/admin/test_training_exam_pdf_service.py + +用途:验证培训试题 PDF 文本解析逻辑,确保可从常见试卷文本中抽出题目、选项、答案与解析。 +""" +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import Agent, AgentGuide +from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF +from app.services.admin.training_exam_pdf_service import ( + parse_training_question_bank_from_guide, + parse_training_question_bank_text, +) + + +def test_parse_training_question_bank_text_supports_inline_answers(): + text = """ + 一、单选题 + 1. 工资每月几号发放? A. 8号 B. 9号 C. 15号 D. 27号 答案:C 解析:工资固定在每月15号发放。 + 2. 餐厅订餐的系统是? A. OA B. 中米新订餐系统 C. ERP 答案:B + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 2 + assert payload['skipped_question_numbers'] == [] + assert payload['question_bank'][0]['type'] == 'single' + assert payload['question_bank'][0]['answer'] == 'c' + assert payload['question_bank'][0]['options'][2]['label'] == 'C. 15号' + assert payload['question_bank'][0]['explanation'] == '工资固定在每月15号发放。' + + +def test_parse_training_question_bank_text_supports_answer_sheet_mapping(): + text = """ + 1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122 + 2、入职培训未达到90分必须重新考试。 正确还是错误? + + 参考答案: + 1.B 2.正确 + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 2 + assert payload['question_bank'][0]['answer'] == 'b' + assert payload['question_bank'][1]['type'] == 'boolean' + assert payload['question_bank'][1]['answer'] == 'true' + + +def test_parse_training_question_bank_text_supports_global_answer_sequence_for_section_reset_numbering(): + text = """ + 一、单选题 + 1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122 + 2、餐厅订餐系统是? A.OA B.中米新订餐系统 C.ERP D.PLM + + 二、判断题(每题5分) + 1、正常出勤必须打卡。( ) + 2、忘记刷卡需要OA补刷卡单。( ) + + 参考答案: + 1.B 2.B 3.正确 4.正确 + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 4 + assert payload['skipped_question_numbers'] == [] + assert [item['type'] for item in payload['question_bank']] == ['single', 'single', 'boolean', 'boolean'] + assert payload['question_bank'][2]['answer'] == 'true' + assert payload['question_bank'][3]['answer'] == 'true' + + +def test_parse_training_question_bank_text_supports_answer_sheet_with_section_local_numbering(): + text = """ + 一、单选题 + 1、发生火灾时应第一时间拨打哪个号码? A.110 B.119 C.120 D.122 + 2、餐厅订餐系统是? A.OA B.中米新订餐系统 C.ERP D.PLM + + 二、判断题 + 1、正常出勤必须打卡。( ) + 2、忘记刷卡需要OA补刷卡单。( ) + + 单选题答案: + 1.B 2.B + 判断题答案: + 1.正确 2.错误 + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 4 + assert payload['skipped_question_numbers'] == [] + assert payload['question_bank'][2]['type'] == 'boolean' + assert payload['question_bank'][2]['answer'] == 'true' + assert payload['question_bank'][3]['answer'] == 'false' + + +def test_parse_training_question_bank_text_supports_boolean_range_answer_sheet(): + text = """ + 一、选择题(每题5分) + 1、工资每月几号发放( ) + A、8号 B、9号 C、15号 D、27号 + 2、餐厅订餐的系统是( ) + A、OA B、中米新订餐系统 C、ERP + + 二、判断题(每题5分) + 1、正常出勤必须打卡,加班需要提前申请提报。( ) + 2、忘记刷卡需要OA开补刷卡单。( ) + 3、每月工资从上月21日至本月20日为止计算。( ) + + 一、单选题(每题10分) + 1、C 2、B + 二、判断题(每题10分) + 1-3 V V × + """ + + payload = parse_training_question_bank_text(text) + + assert payload['parsed_count'] == 5 + assert payload['skipped_question_numbers'] == [] + assert [item['type'] for item in payload['question_bank']] == ['single', 'single', 'boolean', 'boolean', 'boolean'] + assert [item['answer'] for item in payload['question_bank']] == ['c', 'b', 'true', 'true', 'false'] + + +def test_parse_training_question_bank_text_raises_when_no_usable_questions(): + with pytest.raises(ValidationError, match='未能从试题 PDF 中识别出可用题目'): + parse_training_question_bank_text('这是一份扫描件占位文本,没有题号也没有答案。') + + +def test_parse_training_question_bank_from_guide_falls_back_to_ocr_when_pdf_text_empty(app, monkeypatch): + with app.app_context(): + agent = Agent(name='员工培训', type='api', is_active=True) + db.session.add(agent) + db.session.flush() + guide = AgentGuide( + agent_id=agent.id, + file_name='training.pdf', + file_type='pdf', + file_path='training/training.pdf', + guide_usage=GUIDE_USAGE_TRAINING_EXAM_PDF, + status=1, + ) + db.session.add(guide) + db.session.commit() + + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service.minio_service.get_file_bytes', + lambda _path: b'%PDF-1.4 fake', + ) + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service._extract_pdf_text', + lambda _raw: '', + ) + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service._extract_pdf_text_via_ocr', + lambda _raw: ( + '1. 消防电话是多少? A.110 B.119 C.120 D.122 答案:B', + ['pdf likely scanned; OCR recommended'], + ), + ) + + payload = parse_training_question_bank_from_guide(agent.id, guide.id) + + assert payload['parsed_count'] == 1 + assert payload['extraction_mode'] == 'ocr' + assert payload['extraction_warnings'] == ['pdf likely scanned; OCR recommended'] + assert payload['question_bank'][0]['answer'] == 'b' + + +def test_parse_training_question_bank_from_guide_retries_ocr_when_native_text_parse_fails(app, monkeypatch): + with app.app_context(): + agent = Agent(name='员工培训', type='api', is_active=True) + db.session.add(agent) + db.session.flush() + guide = AgentGuide( + agent_id=agent.id, + file_name='training.pdf', + file_type='pdf', + file_path='training/training.pdf', + guide_usage=GUIDE_USAGE_TRAINING_EXAM_PDF, + status=1, + ) + db.session.add(guide) + db.session.commit() + + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service.minio_service.get_file_bytes', + lambda _path: b'%PDF-1.4 fake', + ) + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service._extract_pdf_text', + lambda _raw: '这是错位文本,题号和答案都缺失', + ) + monkeypatch.setattr( + 'app.services.admin.training_exam_pdf_service._extract_pdf_text_via_ocr', + lambda _raw: ( + '1. 工资每月几号发放? A.8号 B.9号 C.15号 D.27号 答案:C', + ['pdf page-image mode pages: 1'], + ), + ) + + payload = parse_training_question_bank_from_guide(agent.id, guide.id) + + assert payload['parsed_count'] == 1 + assert payload['extraction_mode'] == 'ocr_fallback' + assert payload['extraction_warnings'] == ['pdf page-image mode pages: 1'] + assert payload['question_bank'][0]['answer'] == 'c' diff --git a/backend/tests/test_training_api.py b/backend/tests/test_training_api.py new file mode 100644 index 00000000..1059891e --- /dev/null +++ b/backend/tests/test_training_api.py @@ -0,0 +1,318 @@ +""" +backend/tests/test_training_api.py + +用途:覆盖新人培训主链的后端接口闭环,包括个人进度读写、管理端权限、统计筛选与导出。 +依赖:pytest、Flask test client、TrainingRecord/User 模型、openpyxl。 +逻辑:验证“员工个人培训记录”与“HR 管理统计导出”共用同一事实源,确保培训主链在后端可落库、可筛选、可导出。 +""" + +from __future__ import annotations + +from datetime import date, datetime +from io import BytesIO + +from openpyxl import load_workbook + +from app import db +from app.models import TrainingRecord, User + + +def _create_user( + *, + username: str, + role: str = "user", + department: str = "生产一部", + feature_permissions: dict | None = None, +) -> User: + """创建训练测试用户,供 legacy header 认证读取。""" + user = User( + username=username, + email=f"{username}@example.com", + role=role, + status="active", + real_name=f"{username}-实名", + employee_id=f"{username.upper()}-EMP", + department=department, + ) + user.set_feature_permissions(feature_permissions) + user.set_password("password123") + db.session.add(user) + db.session.commit() + db.session.refresh(user) + db.session.expunge(user) + return user + + +def _json_error(response) -> dict: + """提取统一错误 envelope,便于断言错误码与详情。""" + body = response.get_json() + assert isinstance(body, dict) + assert body.get("success") is False + assert isinstance(body.get("error"), dict) + return body["error"] + + +def _auth_headers(user: User) -> dict[str, str]: + """生成训练接口测试鉴权头,优先显式携带 user_id 以稳定命中 legacy 用户解析。""" + return { + "X-User-Id": str(user.id), + "X-Username": user.username, + "Content-Type": "application/json", + } + + +def test_training_user_progress_round_trip_and_completion(client, app): + """员工侧培训进度应支持空记录读取、过程保存、结果结算与再次读取回显。""" + with app.app_context(): + user = _create_user(username="trainee_roundtrip") + + headers = _auth_headers(user) + + empty_res = client.get("/api/user/training-record", headers=headers) + assert empty_res.status_code == 200 + assert empty_res.get_json() is None + + process_payload = { + "stage": "exam", + "current_question_index": 3, + "score": 15, + "passed": False, + "attempt_count": 1, + "join_date": "2026-07-04", + "answer_details": [ + {"question_id": "q1", "selected_option_id": "A", "correct": True}, + {"question_id": "q2", "selected_option_id": "B", "correct": False}, + {"question_id": "q3", "selected_option_id": "C", "correct": True}, + ], + } + save_process_res = client.put("/api/user/training-record/progress", headers=headers, json=process_payload) + assert save_process_res.status_code == 200 + process_body = save_process_res.get_json() + assert process_body["stage"] == "exam" + assert process_body["current_question_index"] == 3 + assert process_body["score"] == 15 + assert process_body["passed"] is False + assert process_body["status"] == "in_progress" + assert process_body["employee_id"] == user.employee_id + assert process_body["name"] == user.real_name + assert len(process_body["answer_details"]) == 3 + + read_back_res = client.get("/api/user/training-record", headers=headers) + assert read_back_res.status_code == 200 + assert read_back_res.get_json()["current_question_index"] == 3 + + result_payload = { + "stage": "result", + "current_question_index": 20, + "score": 95, + "passed": False, + "attempt_count": 2, + "join_date": "2026-07-04", + "answer_details": process_payload["answer_details"], + } + save_result_res = client.put("/api/user/training-record/progress", headers=headers, json=result_payload) + assert save_result_res.status_code == 200 + result_body = save_result_res.get_json() + assert result_body["stage"] == "result" + assert result_body["score"] == 95 + assert result_body["passed"] is True + assert result_body["status"] == "passed" + assert isinstance(result_body["completion_time"], str) and result_body["completion_time"] + + with app.app_context(): + record = db.session.query(TrainingRecord).filter_by(user_id=user.id).one() + assert record.stage == "result" + assert record.score == 95 + assert record.passed is True + assert record.attempt_count == 2 + assert record.join_date == date(2026, 7, 4) + assert record.completion_time is not None + + +def test_training_user_progress_requires_auth_and_valid_payload(client, app): + """培训个人接口必须拒绝未登录请求,并对非法参数返回统一校验错误。""" + unauth_res = client.get("/api/user/training-record") + assert unauth_res.status_code == 401 + assert _json_error(unauth_res)["code"] == "AUTH.UNAUTHORIZED" + + with app.app_context(): + user = _create_user(username="trainee_validation") + + headers = _auth_headers(user) + invalid_stage_res = client.put( + "/api/user/training-record/progress", + headers=headers, + json={ + "stage": "invalid-stage", + "current_question_index": 0, + "score": 0, + "attempt_count": 0, + "answer_details": [], + }, + ) + assert invalid_stage_res.status_code == 400 + invalid_stage_error = _json_error(invalid_stage_res) + assert invalid_stage_error["code"] == "VALIDATION.INVALID_PARAM" + assert invalid_stage_error["details"]["field"] == "stage" + + invalid_answer_res = client.put( + "/api/user/training-record/progress", + headers=headers, + json={ + "stage": "exam", + "current_question_index": 1, + "score": 5, + "attempt_count": 1, + "answer_details": ["not-object"], + }, + ) + assert invalid_answer_res.status_code == 400 + invalid_answer_error = _json_error(invalid_answer_res) + assert invalid_answer_error["code"] == "VALIDATION.INVALID_PARAM" + assert invalid_answer_error["details"]["field"] == "answer_details" + assert invalid_answer_error["details"]["index"] == 0 + + +def test_training_admin_list_stats_and_export_share_one_fact_source(client, app): + """HR 管理列表、统计与导出应共用同一批 TrainingRecord,并支持部门/状态筛选。""" + with app.app_context(): + hr_user = _create_user(username="training_hr", role="hr", department="人事部") + ordinary_user = _create_user(username="training_user_denied", role="user", department="生产一部") + passed_user = _create_user(username="passed_learner", department="生产一部") + failed_user = _create_user(username="failed_learner", department="生产一部") + progress_user = _create_user(username="progress_learner", department="品质部") + + db.session.add_all( + [ + TrainingRecord( + user_id=passed_user.id, + employee_id=passed_user.employee_id, + name=passed_user.real_name, + department=passed_user.department, + join_date=date(2026, 7, 1), + stage="result", + current_question_index=20, + score=95, + passed=True, + attempt_count=1, + answer_details=[], + started_at=datetime(2026, 7, 1, 9, 0, 0), + completion_time=datetime(2026, 7, 1, 10, 0, 0), + ), + TrainingRecord( + user_id=failed_user.id, + employee_id=failed_user.employee_id, + name=failed_user.real_name, + department=failed_user.department, + join_date=date(2026, 7, 2), + stage="result", + current_question_index=20, + score=60, + passed=False, + attempt_count=2, + answer_details=[], + started_at=datetime(2026, 7, 2, 9, 0, 0), + completion_time=datetime(2026, 7, 2, 10, 0, 0), + ), + TrainingRecord( + user_id=progress_user.id, + employee_id=progress_user.employee_id, + name=progress_user.real_name, + department=progress_user.department, + join_date=date(2026, 7, 3), + stage="exam", + current_question_index=6, + score=25, + passed=False, + attempt_count=1, + answer_details=[], + started_at=datetime(2026, 7, 3, 9, 0, 0), + completion_time=None, + ), + ] + ) + db.session.commit() + + denied_headers = _auth_headers(ordinary_user) + denied_res = client.get("/api/admin/training-records", headers=denied_headers) + assert denied_res.status_code == 403 + assert _json_error(denied_res)["code"] == "AUTH.FORBIDDEN" + + hr_headers = _auth_headers(hr_user) + list_res = client.get( + "/api/admin/training-records?department=生产一部&status=passed&page=1&page_size=10", + headers=hr_headers, + ) + assert list_res.status_code == 200 + list_body = list_res.get_json() + assert list_body["total"] == 1 + assert list_body["page"] == 1 + assert list_body["page_size"] == 10 + assert list_body["pages"] == 1 + assert set(list_body["department_options"]) == {"生产一部", "品质部"} + assert len(list_body["items"]) == 1 + assert list_body["items"][0]["employee_id"] == passed_user.employee_id + assert list_body["items"][0]["status"] == "passed" + + stats_res = client.get("/api/admin/training-records/stats", headers=hr_headers) + assert stats_res.status_code == 200 + stats_body = stats_res.get_json() + assert stats_body == { + "total": 3, + "passed": 1, + "failed": 1, + "in_progress": 1, + "pass_rate": 33, + "average_score": 60, + } + + export_res = client.get("/api/admin/training-records/export?department=生产一部", headers=hr_headers) + assert export_res.status_code == 200 + assert export_res.headers["Content-Type"].startswith( + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ) + assert "training_records_" in export_res.headers["Content-Disposition"] + + workbook = load_workbook(BytesIO(export_res.data)) + sheet = workbook.active + rows = list(sheet.iter_rows(values_only=True)) + assert rows[0] == ("入职日期", "完成日期", "部门", "姓名", "工号", "分数", "考试次数", "状态") + assert len(rows) == 3 + assert rows[1][2] == "生产一部" + assert rows[2][2] == "生产一部" + assert {rows[1][7], rows[2][7]} == {"passed", "failed"} + + +def test_training_admin_permission_can_be_granted_by_feature_permission(client, app): + """培训 HR 管理能力应支持通过功能权限显式授予普通用户。""" + with app.app_context(): + granted_user = _create_user( + username="training_perm_user", + role="user", + department="生产一部", + feature_permissions={"training_hr_manage": True}, + ) + db.session.add( + TrainingRecord( + user_id=granted_user.id, + employee_id=granted_user.employee_id, + name=granted_user.real_name, + department=granted_user.department, + join_date=date(2026, 7, 5), + stage="result", + current_question_index=20, + score=90, + passed=True, + attempt_count=1, + answer_details=[], + started_at=datetime(2026, 7, 5, 9, 0, 0), + completion_time=datetime(2026, 7, 5, 10, 0, 0), + ) + ) + db.session.commit() + + res = client.get("/api/admin/training-records", headers=_auth_headers(granted_user)) + assert res.status_code == 200 + body = res.get_json() + assert body["total"] == 1 + assert body["items"][0]["employee_id"] == granted_user.employee_id diff --git a/debug-retry-rpa-no-request.md b/debug-retry-rpa-no-request.md new file mode 100644 index 00000000..48be3cd0 --- /dev/null +++ b/debug-retry-rpa-no-request.md @@ -0,0 +1,25 @@ +# Debug Session: retry-rpa-no-request +- **Status**: [OPEN] +- **Issue**: 点击“重试 RPA”后,界面出现已触发/已重新触发类文案,但怀疑本轮并未真正写出 RPA trigger。 +- **Debug Server**: pending +- **Log File**: .dbg/trae-debug-log-retry-rpa-no-request.ndjson + +## Reproduction Steps +1. 打开发货通知聊天页,定位任务 `SN-20260702-9D76D759`。 +2. 在右侧工作台或聊天气泡中点击“重试 RPA”。 +3. 观察是否出现新的聊天回复、任务卡刷新以及后端 trigger 写入。 + +## Hypotheses & Verification +| ID | Hypothesis | Likelihood | Effort | Evidence | +|----|------------|------------|--------|----------| +| A | 前端点击后没有真正触发 decision 请求 | High | Low | Pending | +| B | 前端提交了 decision,但 `taskId/decision` 参数错误 | High | Low | Pending | +| C | 后端收到了 `retry_rpa`,但没有成功写出 trigger 文件 | High | Medium | Pending | +| D | trigger 已写出,但前端显示的是旧消息/旧状态 | Medium | Medium | Pending | +| E | 当前可见文本并非本轮点击实时产物,而是聊天消息复用 | Medium | Medium | Pending | + +## Log Evidence +- Pending + +## Verification Conclusion +- Pending diff --git a/debug-rpa-trigger-missing.md b/debug-rpa-trigger-missing.md deleted file mode 100644 index 150c41ab..00000000 --- a/debug-rpa-trigger-missing.md +++ /dev/null @@ -1,21 +0,0 @@ -# [OPEN] debug-rpa-trigger-missing - -## 现象 -- 用户点击“重试 RPA”后,界面出现“已重新触发 RPA 库存导出。若长时间无结果,可手动重试,或上传库存 Excel。”之类提示。 -- 但用户怀疑实际并没有真正触发 RPA。 - -## 当前范围 -- 仅收集“重试 RPA”从前端点击到后端写 trigger 的运行时证据。 -- 在拿到证据前,不修改业务逻辑。 - -## 待证伪假设 -- H1:前端按钮点击后没有真正调用 `workspace-action`/`submit-decision`,只是本地 UI 文本更新了。 -- H2:前端请求已经发出,但请求参数里的 `taskNo`/`decision` 不对,导致后端没有走到 `retry_rpa` 分支。 -- H3:后端进入了 `retry_rpa` 分支,但 `write_inventory_export_trigger()` 返回空,实际没有生成 trigger 文件。 -- H4:后端确实写出了 trigger,但工作台刷新拿到的是旧状态或旧消息,造成“看起来没触发”。 -- H5:当前显示的这段文案不是本轮点击实时产生,而是旧消息残留/复用。 - -## 计划 -- 1. 先查看现有前后端运行日志,确认是否已有直接证据。 -- 2. 若证据不足,只增加最小插桩,打通“点击 -> 请求 -> 后端 decision -> trigger 写入”链路。 -- 3. 复现一次并按证据排除假设。 diff --git a/docs/demand.md b/docs/demand.md index 6151d713..e251f46a 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -1,5 +1,14 @@ # 智能HR请假管理需求 +## 设备维保助手补充需求 + +- 查询方式:用户通过 `设备维保助手` 会话查询设备维护/维修记录,系统支持按设备编号、设备名称、故障描述、维修说明、维修人和状态筛选记录。 +- 管理方式:新增维修记录、设备台账配置属于固定管理人员操作,不通过会话消息承载;在聊天输入区底部以按钮进入右侧固定面板,面板顶部可关闭。 +- 台账配置:右侧固定面板包含“设备列表”和“设备配置”两个 Tab,设备字段包含设备编号、设备名称、型号规格、使用部门、安装地点、设备状态、制造厂家、进厂日期、生产日期、启用日期、责任人用户名、维护周期和备注。 +- Excel 导入:设备台账支持下载模板并从 Excel 批量导入,按设备编号判断新增或更新。 +- 责任人规则:`responsible_user` 存储用户名文本,当前阶段不与用户表建立外键关联。 +- 范围裁剪:不提供维修字典配置功能,不在底部按钮中展示该入口。 + ## 1. 项目背景 当前系统已经具备以下基础能力: diff --git a/docs/funclist.md b/docs/funclist.md index 24359a77..a0d73753 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -1,5 +1,19 @@ # 智能HR请假管理功能清单 +## 设备维保助手 + +| 功能项 | 状态 | 说明 | +| --- | --- | --- | +| 会话式维修记录查询 | 后端已实现 | 新增 `/api/maintenance/records` 查询接口,支持按设备编号、设备名称、维修状态筛选,供 Agent 会话查询和前端结果复用 | +| 会话式设备台账卡片 | 已实现 | 明确设备编号/名称查询由 HXOPS 后端本地直答,返回设备台账信息卡片和最近维修记录 | +| Dify 设备维保查询 Tool | 已实现 | 新增 `/api/maintenance/tools/*` 只读 Tool API 与 `/api/maintenance/tools/openapi.json`,供 Dify 处理复杂问法时查询设备台账和维修记录 | +| 维修记录管理 | 已实现 | `设备维保助手` 聊天输入栏底部提供“维修记录”按钮,右侧固定面板支持维修记录查询、新增、编辑、删除 | +| 设备台账配置 | 已实现 | `设备维保助手` 聊天输入栏底部提供“台账配置”按钮,右侧固定面板包含“设备列表 / 设备配置”两个 Tab | +| Excel 导入设备台账 | 已实现 | 支持下载设备台账模板并通过 Excel 批量导入,按设备编号新增或更新 | +| 设备财务字段配置 | 已实现 | 设备台账支持原值、残值和账套字段;账套固定选项为和信、科技、电子、和宏智 | +| 责任人字段 | 已实现 | 设备台账责任人字段使用 `responsible_user` / `responsibleUser` 用户名文本,不关联用户表 | +| 维修字典配置 | 不纳入范围 | 底部按钮和正式功能中不提供“配置维修字典”入口 | + ## 通用意见反馈 | 功能项 | 状态 | 说明 | @@ -12,11 +26,12 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | | Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 | -| Chat 内 HR 管理面板 | 已实现 | 管理角色可在同一聊天页查看真实培训统计、筛选记录并导出 Excel | -| 培训题库前端内置 | 前端已实现 | 内置 20 道新人试卷题目,支持一题一答、即时反馈、未通过重考 | -| 管理端培训模式配置 | 前端已实现 | Agent 管理表单支持显式开启培训工作区,并可一键套用培训默认配置 | +| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;权限支持角色默认值与前端用户配置共同控制 | +| 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 | +| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 | | 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 | | 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 | +| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) | | 培训业务闭环整改清单 | 已文档化 | 见 [docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) | ## 1. 功能总览 @@ -81,6 +96,7 @@ | 固资本地快照查询 | 已实现 | `固资管理` Agent 优先查询 SQLite 最新快照,减少实时 ERP 压力 | | 固资导出文件 | 已实现 | 同步成功后生成 `FixedAssets_latest.xlsx`,供人工核查与留档 | | 固资快照技术方案 | 已文档化 | 见 [docs/features/fixed-assets/technical.md](features/fixed-assets/technical.md) | +| 固资履历查看 | 已实现 | 聊天结果中的 `资产编号` 支持点击后检索共享盘履历文件,并复用现有预览弹窗查看 | ### F-01 本人假期查询 diff --git a/docs/prototype/equipment-maintenance-agent-chat-lofi.html b/docs/prototype/equipment-maintenance-agent-chat-lofi.html new file mode 100644 index 00000000..67c3e237 --- /dev/null +++ b/docs/prototype/equipment-maintenance-agent-chat-lofi.html @@ -0,0 +1,1228 @@ + + + + + + + 设备维保助手 Agent 对话式低保真 + + + +
+ + +
+
+
+

你好,您已进入 设备维保助手 智能体

+

查询通过会话完成;新增、配置等管理操作仅固定管理人员可在底部按钮中打开。

+
+ +
+
+ +
+
+ + +
+ + + + + + 管理操作:仅资产管理员 / 维修主管可用 +
+
+
AI 查询可能会犯错,请核实重要信息。写入类操作只能由固定管理人员在右侧面板中确认提交。
+
+
+ + +
+ + + + + + + + + + + + + + + + + + diff --git a/docs/prototype/equipment-maintenance-agent-lofi.html b/docs/prototype/equipment-maintenance-agent-lofi.html new file mode 100644 index 00000000..db489104 --- /dev/null +++ b/docs/prototype/equipment-maintenance-agent-lofi.html @@ -0,0 +1,1105 @@ + + + + + + + 设备维保 Agent 低保真原型 + + + +
+
+
+ +
+
设备维保 Agent
+

低保真原型 / 设备台账 · 维修查询 · 维修录入

+
+
+
+ 当前用户:16040053 + + +
+
+ + + +
+
+
+
+

维保工作台

+

面向设备维修 Agent 的入口页,聚合待处理、近期记录与快捷操作。

+
+
+ + +
+
+ +
+
待维修3需维修人员补充处理结果
+
本月维修次数18较上月 +4
+
本月维修费用¥2,464含外协与备件费用
+
+ +
+
+

待处理维修

+ + + + + +
设备编号设备名称故障描述状态
+
+
+

Agent 可辅助动作

+
+
自然语言查询:按设备、地点、人员、日期范围检索维修历史。
+
辅助录入:用户口述故障,Agent 转成结构化维修记录。
+
缺失字段追问:设备编号、报修日期、故障描述不完整时先确认。
+
提交前确认:生成表单预览,由用户点击确认后写入。
+
+
+
+
+ +
+
+
+

设备台账

+

先定位设备,再进入该设备维修历史或新增维修记录。

+
+ +
+
+
+ + + + +
+
+ + +
+ + + + + + + +
设备编号设备名称型号规格使用部门安装地点设备状态操作
+
+
+ +
+
+
+

维修记录查询

+

对应旧系统查询页,保留多条件筛选与表格查看能力。

+
+
+ + +
+
+
+
+ + + + + + + + + +
+
+ + +
+ + + + + + + +
设备编号设备名称型号规格报修日期故障描述维修描述修复日期维修人员费用状态
+
+
+ +
+
+
+

新增维修记录

+

左侧带出设备台账信息,右侧录入报修与修复信息。

+
+
+ + +
+
+
+
+

设备信息

+ +
+ +
+
+
+
+

维修记录表单

+
+ + + + + + + + + + + + + +
+
+
+
+ +
+
+
+

配置管理

+

用于管理员配置维修类别、状态字典、默认字段与 Agent 工具开关。

+
+
+
+
+

维修类别字典

+ + + + + + + +
类别启用说明
一般是普通设备故障处理
紧急是影响产线或安全的故障
保养是周期性维护与点检
+
+
+

Agent 工具开关

+ + + + +
+
+
+
+ + +
+ + + + + + diff --git a/docs/tec.md b/docs/tec.md index faa56ca0..8010289f 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -911,3 +911,140 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth; - Web 进程压力下降,系统稳定性提升 - 失败任务可重试,进度展示更清晰 - 整体知识库链路更适合后续扩展为高并发、多批次处理模式 + +--- + +## 19. 新人入职培训 Agent 推荐技术路径 + +### 19.1 推荐结论 + +“新人入职培训 Agent”不建议走纯 Dify 考试编排主链,推荐采用: + +- **主链**:Chat 页面内嵌培训工作区 + 前端受控状态机 + 后端真实记录落库 +- **辅助层**:Dify 承担培训 FAQ、知识点解释、HR 自然语言统计问答(ChatBI) + +该方案更符合培训考试场景对“流程刚性、成绩可信、状态可恢复、结果可审计”的要求。 + +### 19.2 为什么不建议纯 Dify 主导考试 + +- 培训考试需要严格控制“看视频 -> 看总结 -> 一题一答 -> 结算 -> 补考”顺序 +- 题号推进、得分计算、补考次数不适合交给大模型对话变量作为唯一事实源 +- 纯 Dify 方案更适合自然语言问答,不适合作为考试状态机和唯一判卷引擎 +- HR 统计和导出需要稳定的数据事实源,不能依赖对话历史反推 + +### 19.3 推荐架构 + +```text +员工 + -> Chat 页面 + -> 培训工作区(视频 / 总结 / 考试 / 结算) + -> 聊天气泡卡片(视频卡片 / 总结卡片 / 题目卡片 / 结果卡片) + +前端培训工作区 + -> /api/user/training-record + -> /api/user/training-record/progress + +后端 training 域 + -> TrainingRecord 表 + -> training_service + -> HR 列表 / 统计 / Excel 导出 + +Dify + -> 培训 FAQ + -> 知识点解释 + -> HR ChatBI +``` + +### 19.4 培训权限模型 + +- 学员端默认面向所有已登录员工开放,允许查看视频、知识点复盘、考试与个人成绩回显。 +- `HR 管理` 视图与 `/api/admin/training-records*` 接口统一走 `training_hr_manage` 功能权限判断。 +- 权限来源采用“**角色默认值 + 用户显式配置覆盖**”: + - `admin`、`hr` 角色默认拥有 `training_hr_manage` + - 管理后台用户编辑表单可对单个用户显式授予或关闭该权限 +- 前端只根据登录态里的 `feature_permissions.training_hr_manage` 决定是否展示 `HR 管理` 标签;后端仍做强校验,避免仅靠前端隐藏导致越权。 + +### 19.5 培训资料维护 + +- 后台继续复用 `AgentGuide` 资料模型承载培训素材,不单独新建一套上传体系。 +- `guide_usage` 用于标识资料用途: + - `general`:普通应用指南 + - `training_video`:员工培训视频 + - `training_exam_pdf`:员工培训试题 PDF +- 员工培训工作区读取顺序: + 1. 优先读取 `training_video` 指南作为培训视频 + 2. 若未配置,再回退到 Agent `extra_config.training_video_url` + 3. 仍未配置时使用默认演示视频 +- “查看试题 PDF”入口只读取 `training_exam_pdf`,避免把普通指南 PDF 误识别成考试资料。 + +### 19.6 培训内容后台化 + +- 培训工作区的结构化内容统一收敛到 `Agent.extra_config.training_config`,避免继续把题库、复盘要点散落在前端静态文案里。 +- 当前约定字段: + - `pass_score`:及格线,按百分制判定是否通过 + - `summary_points`:知识点复盘数组 + - `summary_checklist`:考前必知数组 + - `question_bank`:结构化题库(`id/type/prompt/answer/explanation/options`) +- 员工培训工作区读取顺序: + 1. 优先读取 `extra_config.training_config` + 2. 若某项未配置,则仅该项回退到前端默认值,保证旧 Agent 不因缺字段而失效 +- 题库题量改为后台可配后,前端分数计算改为“按当前题量折算百分制”,不再硬编码每题 5 分。 +- 管理端支持从已上传并标记为 `training_exam_pdf` 的指南 PDF 解析题库: + 1. 后端按 `guide_id` 读取 PDF 文本 + 2. 若 PDF 原生文本缺失或错位,则回退到 `loader_pdf + rapidocr` 识别扫描件页面 + 3. 识别题号、选项、答案与解析,生成 `question_bank` + 4. 解析结果先回填 Agent 表单,由 HR 复核后再保存,避免误解析直接落库 +- 扫描件 PDF 的 OCR 回退依赖 `backend/requirements-ocr.txt` 中的 rapidocr / onnxruntime 栈;若环境未安装,接口会返回带 `ocr_warnings` 的诊断信息,提示先补齐 OCR 依赖。 + +### 19.4 Dify 职责边界 + +#### 建议由 Dify 负责 + +- 培训制度问答 +- 培训知识点解释 +- 培训 FAQ +- HR 自然语言统计和导出问答 + +#### 不建议由 Dify 负责 + +- 当前题号推进 +- 当前分数累计 +- 最终是否通过的唯一判定 +- 补考次数控制 +- 培训考试记录事实落库 + +### 19.5 推荐实施顺序 + +#### P0 + +- 保留现有培训工作区主链 +- 完善 training 接口测试与前端回归测试 +- 确保培训记录、统计、导出全链路稳定 + +#### P1 + +- 题库、知识点、通过线、欢迎语后台配置化 +- 培训视频素材正式配置化 +- 题库版本化与记录快照化 + +#### P2 + +- 接入 Dify 作为培训 FAQ / HR ChatBI 的辅助层 +- 对外形成“Chat 化体验 + 受控考试主链”的最终形态 + +详细说明见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md)。 +# 设备维保助手技术设计补充 + +## 数据模型 + +- `maintenance_devices`:设备台账主表,保存设备基础信息、进厂日期、生产日期、启用日期、责任人、原值、残值、账套等字段。 +- `maintenance_records`:设备维修记录表,保存报修日期、维修状态、故障描述、维修人、维修费用、维修工时等字段;新增记录时按设备编号快照设备名称、型号和安装地点。 +- `maintenance_audit_logs`:台账和维修记录写操作审计表,记录对象类型、操作类型、操作前后快照、操作人和请求 ID。 + +## 接口与前端 + +- 后端新增 `backend/app/api/maintenance.py`,统一挂载在 `/api/maintenance`。 +- 台账接口:`/api/maintenance/ledger/devices`、`/api/maintenance/ledger/import-template`、`/api/maintenance/ledger/import`。 +- 维修记录接口:`/api/maintenance/records`,支持查询详情、分页查询和新增。 +- 前端新增 `features/maintenance` 业务域,包含台账 API、维修记录 API、类型定义和右侧固定面板组件。 +- 聊天页仅当当前 Agent 名称为 `设备维保助手` 时显示底部管理按钮;查询继续走会话,配置类操作进入右侧固定面板。 diff --git a/docs/新人入职培训Agent_产品设计文档.md b/docs/新人入职培训Agent_产品设计文档.md new file mode 100644 index 00000000..45d9c6cf --- /dev/null +++ b/docs/新人入职培训Agent_产品设计文档.md @@ -0,0 +1,143 @@ +# 员工入职培训 Agent (对话式考核与管理) 产品设计与落地文档 + +## 一、 背景与业务目标 + +### 1.1 业务背景 + +人事部门(HR)提出新需求,需要对入职员工进行在线培训与考核。 +核心诉求包括: + +1. **学习闭环**:要求员工先观看培训视频,然后总结知识点最后进行答题。 +2. **交互式测试**:通过逐题一问一答的方式进行测试(共20题,每题5分,满分100分)。 +3. **即时反馈机制**:答对继续;答错必须即时显示正确答案及解析,以强化记忆。 +4. **通过标准**:90分及格,未通过者必须重新考试直至通过。 +5. **数据统计与导出**:HR 需要统计考试结果,并能够导出包含“入职日期、完成日期、部门、姓名、工号、分数”的表格。 + +
+ +效益整理 + +### 1.2 产品定位 + +基于 HXOPS 平台(Enterprise AI Gateway)的 Agentic 理念,我们将该需求设计为 **“对话式交互 (Chat UI) + Dify Agent + HXOPS 后端 Tool API”** 的整体解决方案。 +该方案摒弃了传统的“前端答题表单 + 后台管理看板”模式,将员工的“在线培训考核”与 HR 的“数据查询及导出”功能,全部融合在自然语言对话页面(Chat)中,实现极简的用户体验。 + +*** + +## 二、 对话交互流程设计 (User Journey) + +### 2.1 员工端:沉浸式导学与考核 + +整个流程在 HXOPS 的 Chat 界面中闭环,分为四个状态阶段: + +#### 阶段 1:破冰与视频导学 (Onboarding) + +- **Agent**: "👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。" +- **Agent**: "▶️ 请先点击观看 \[入职培训视频链接]。观看完毕后,请回复【已看完】。" +- **User**: "已看完" + +#### 阶段 2:知识点串讲 (Knowledge Summary) + +- **Agent**: "太棒了!结合刚才的视频,我为你提炼了以下核心知识点(必考哦): + > 1. **薪酬考勤**:每月15号发工资;打卡、请假必须走 OA 系统。 + > 2. **日常行政**:中米新订餐系统订餐;灭火器需站在上风口。 + > 3. **体系与安全**:QC080000 是有害物质管理标准;5S 是整理、整顿、清扫、清洁、素养。 + > 准备好接受挑战了吗?请回复【开始考试】。" + +#### 阶段 3:互动测试 (Interactive QA) - 循环20次 + +- **User**: "开始考试" +- **Agent**: "📝 **第 1 题 / 共 20 题(单选题)**:工资每月几号发放? + A. 8号 B. 9号 C. 15号 D. 27号 + 请直接回复选项或内容。" +- **User**: "C" +- **Agent**: "✅ **回答正确!** 当前得分:5分。 + 📝 **第 2 题 / 共 20 题(判断题)**:发生火灾、爆炸事故时,应立即拨打“119”。(请回复对或错)" +- **User**: "错" +- **Agent**: "❌ **回答错误。** 正确答案是:【对】。 + *解析:生命安全第一,发生火灾必须立即拨打119。* + 当前得分:5分。 + 📝 **第 3 题 / 共 20 题...**" + +#### 阶段 4:结算与归档 (Settlement) + +- *(如果 < 90 分)* + **Agent**: "📊 **考试结束!** 您的最终得分是 **85 分**。及格线为 90 分。请回复【重新考试】再次挑战!" +- *(如果 >= 90 分)* + **Agent**: "🎉 **恭喜!** 您的最终得分是 **95 分**,已顺利通过新人考核!您的成绩已自动同步至人事部门。" + +### 2.2 HR 管理端:对话式数据管家 (ChatBI) + +无需额外开发后台管理页面,HR 直接通过自然语言与 Agent 对话,完成数据统计与报表导出。 + +#### 场景 1:日常数据速查 (ChatBI) + +- **HR**: "帮我查一下这个月有多少人完成了新人培训?通过率怎么样?" +- **Agent (思考中...)**: *(调用工具* *`query_training_stats`)* +- **Agent**: "📊 **本月新人培训速报**:参训 15 人,通过 12 人,未通过 3 人,整体通过率 80%。" + +#### 场景 2:报表一键导出 (Chat 导出 Excel) + +- **HR**: "把本月通过的员工名单导出成 Excel。" +- **Agent (思考中...)**: *(调用工具* *`export_training_records`)* +- **Agent**: "✅ 已为您生成本月的培训成绩报表,包含入职日期、部门、姓名、工号和最终分数。 + 📁 **点击下载文件**:\[本月新人培训合格名单.xlsx]" + +*** + +## 三、 系统架构与技术实现方案 + +架构核心:**将复杂的 UI 交互转化为 Dify Agent 的大模型逻辑与 HXOPS 的 OpenAPI 工具调用。** 前端几乎零开发,主要工作在 Dify 画布编排与后端数据层。 + +### 3.1 Dify Chatflow 编排设计 (大脑) + +在 Dify 侧创建一个 Chatflow 应用,作为整个交互的中枢控制: + +- **全局对话变量 (Variables)**: + - `question_index` (Integer) 默认 0:记录当前题号。 + - `score` (Integer) 默认 0:记录当前总分。 + - `questions_json` (String):系统预置变量,存放试卷的标准化 JSON 数据。 +- **核心节点逻辑**: + 1. **意图识别与权限校验**:判断用户是员工在答题,还是 HR 在查数据(结合环境变量 `{{is_hr}}` 进行权限隔离)。 + 2. **LLM 判卷节点**:提取 `questions_json[question_index]` 的标准答案,与用户的自然语言输入(如选 C、回复“对”等)交给 LLM 进行语义比对与判定。 + 3. **条件分支流转**:控制计分逻辑,答错则附加输出正确答案与解析。 + 4. **HTTP Tool 调用节点**:当满足条件(如答题结束且分数>=90,或 HR 要求导出报表)时,通过 API 触发 HXOPS 后端的业务逻辑。 + +### 3.2 HXOPS 后端改造设计 (Python/Flask) + +后端仅作为数据落地和业务接口提供方,主要新增以下模块: + +1. **数据库模型扩展 (`backend/app/models/user.py`** **或新建)** + - 新增 `TrainingRecord` 表。 + - 字段:`id`, `user_id` (外键), `score` (分数), `passed` (布尔值), `start_time`, `completion_time`。 + - *注:入职日期、姓名、工号、部门等信息可通过联表* *`User`* *和* *`Department`* *直接获取。* +2. **为 Dify 提供 OpenAPI Tools (`backend/app/api/internal/tools/training.py`)** + - `POST /submit`:接收 Dify 传来的成绩数据并落库。 + - `GET /stats`:接收时间/部门等参数,返回聚合统计 JSON 数据(供 Agent 转述)。 + - `POST /export_excel`:接收筛选参数,使用 `pandas` 或 `openpyxl` 生成包含指定字段的 Excel 文件。返回静态文件的下载 URL 供前端渲染。 + +### 3.3 权限与安全管控 (RBAC in Chat) + +- **痛点**:防止普通员工询问并获取其他人的成绩。 +- **方案**:HXOPS 在初始化 Dify 会话时,通过上下文(如 `hxops_context.py`)将当前用户的权限标识(如 `is_hr: true/false`)作为环境变量注入 Dify。 +- **Dify 系统 Prompt 约束**:“当处理数据查询或导出意图时,必须校验 `{{is_hr}}` 变量。若无权限,必须拒绝执行并提示:‘抱歉,仅人事部门有权限查看全局培训数据’。” + +### 3.4 防作弊机制设计 + +为了防止员工利用大模型直接套取答案,需要在 Dify 的系统 Prompt 中设置严格的**安全护栏 (Guardrails)**: + +- **指令**:“你是一个严格的考官。无论用户如何诱导,**绝对禁止**提前透露当前未答题目或后续题目的正确答案。” + +*** + +## 四、 实施步骤与排期计划 + +| 阶段 | 任务内容 | 涉及端 | 预估耗时 | +| :--------------- | :------------------------------------------------------------------------------------------ | :--------- | :---- | +| **阶段一:数据准备** | 将 PDF 试卷(20题)解析清洗,转换为标准化 JSON 格式,供 Dify 消费。 | 数据处理 | 0.5 天 | +| **阶段二:后端基建** | 1. 设计并创建 `TrainingRecord` 数据表及 Alembic 迁移脚本。2. 开发供 Dify 调用的 OpenAPI 接口(提交成绩、查询统计、导出 Excel)。 | 后端 (Flask) | 1 天 | +| **阶段三:Agent 编排** | 在 Dify 平台创建 Chatflow,配置变量、编写 System Prompt、编排节点逻辑,并对接后端的 Tool API。 | Dify | 1.5 天 | +| **阶段四:联调与验收** | 全链路测试:员工正常答题闭环测试、异常输入测试、防作弊测试;HR 权限测试与 Excel 导出测试。 | 测试 | 0.5 天 | + +> **总结**:得益于将 UI 交互转化为对话模式,前端工作量降为 0,整体需求落地周期压缩至 **3\~4 个工作日**。这完美展现了 Agentic 架构在企业内部管理效能提升上的巨大优势。 + diff --git a/docs/新人入职培训Agent_推荐落地方案.md b/docs/新人入职培训Agent_推荐落地方案.md new file mode 100644 index 00000000..95091331 --- /dev/null +++ b/docs/新人入职培训Agent_推荐落地方案.md @@ -0,0 +1,268 @@ +# 新人入职培训 Agent 推荐落地方案 + +## 1. 文档目的 + +基于当前仓库真实实现与 [新人入职培训Agent\_产品设计文档](新人入职培训Agent_产品设计文档.md) 的目标方案,对“新人入职培训 Agent”给出更适合 HXOPS 当前阶段的落地建议,明确: + +- 员工培训主链应采用哪种实现方式 +- Dify 在培训场景中的合理职责边界 +- 现有实现与目标方案的差异 +- 推荐的 P0 / P1 演进顺序 + +## 2. 结论 + +结论先行: + +- **员工培训主流程**:推荐采用“Chat 页面内嵌受控工作区 + 后端真实记录”的方案作为主线。 +- **Dify**:推荐承担培训知识问答、知识点解释、HR 自然语言统计问答等辅助能力,不建议承担考试状态推进和最终判卷主逻辑。 +- **最终推荐架构**:采用“**受控考试主链 + Dify 辅助问答/ChatBI**”的混合方案,而不是纯前端工作区或纯 Dify 编排二选一。 + +## 3. 为什么不建议纯 Dify 驱动考试主链 + +产品设计文档中的理想形态是: + +`Chat UI + Dify Agent + HXOPS 后端 Tool API` + +该方案适合自然语言问答,但不适合承担“培训考试主链”的核心控制,主要原因如下: + +### 3.1 流程刚性不足 + +培训考试的核心约束是: + +- 必须先看视频,再看总结,再考试 +- 必须一题一答,不能跳题 +- 答错必须即时给出正确答案与解析 +- 未通过必须重考 + +这类规则更适合由前端状态机和后端记录共同保证,不适合交给 LLM 根据上下文和 Prompt 自由推进。 + +### 3.2 可测试性和可审计性不足 + +考试场景需要稳定复现: + +- 第几题 +- 选了什么 +- 当前分数 +- 是否通过 +- 补考次数 +- 完成时间 + +如果主逻辑依赖 Dify 会话变量和模型语义判断,测试成本和审计成本都会显著提高。 + +### 3.3 防作弊成本高 + +纯 Dify 方案需要依赖 Prompt Guardrails 防止: + +- 提前索要答案 +- 诱导泄露题库 +- 绕过考试步骤 + +Prompt 约束可以作为辅助,但不应作为培训考试的唯一硬约束。 + +## 4. 为什么当前“受控工作区 + 后端落库”更适合主流程 + +当前仓库已经具备一条可运行的受控培训主链: + +- Chat 页面顶部挂载培训工作区 +- 学员端按 `video -> summary -> exam -> result` 推进 +- 题目一题一答并即时反馈 +- 培训进度、答题明细、分数、补考次数写入后端 +- HR 可读取真实记录、统计并导出 Excel + +这套方案更适合培训主链,原因如下: + +### 4.1 状态推进可控 + +前端工作区明确掌控阶段推进、选项点击、下一题、补考入口,行为确定性强,便于验收和回归。 + +### 4.2 数据真实落库 + +后端 `TrainingRecord` 可作为培训事实源,承担: + +- 当前培训阶段 +- 当前题号 +- 分数 +- 是否通过 +- 补考次数 +- 答题明细 +- 开始时间 / 完成时间 + +### 4.3 HR 视角天然闭环 + +员工培训过程与 HR 统计、导出直接共用同一张事实表,避免“前端考试一套、HR 统计另一套”的双轨状态漂移。 + +## 5. 推荐目标架构 + +```text +员工 + -> Chat 页 + -> 培训工作区(受控状态机) + -> 视频学习 + -> 知识点复盘 + -> 一题一答 + -> 结果结算 / 补考 + -> 本地聊天消息区(展示视频卡片/总结卡片/题目卡片/结果卡片) + +前端培训工作区 + -> 调用 HXOPS Training API + -> 读取个人进度 + -> 保存阶段推进 + -> 保存答题明细 + -> 保存结算结果 + +后端 Training API / Service + -> PostgreSQL TrainingRecord + -> HR 列表 / 统计 / Excel 导出 + +Dify(辅助能力) + -> 培训 FAQ / 知识点解释 + -> HR 自然语言查数(ChatBI) + -> 培训流程说明 / 制度问答 +``` + +## 6. Dify 的推荐职责边界 + +### 6.1 建议由 Dify 承担 + +- 培训规则、制度、知识点的自然语言解释 +- 视频观看后的补充问答 +- 员工关于培训内容的 FAQ +- HR 自然语言统计问答,例如: + - “这个月多少人完成培训?” + - “通过率是多少?” + - “帮我导出生产部未通过名单” + +### 6.2 不建议由 Dify 承担 + +- 当前题号推进 +- 当前总分计算 +- 最终是否通过的唯一判定 +- 答题记录的事实落库 +- 补考次数的唯一来源 + +这些能力应仍由 HXOPS 前后端控制,Dify 只读或只做辅助解释。 + +## 7. 对当前实现的判断 + +### 7.1 已经具备的能力 + +- 培训 Agent 的 Chat 入口识别 +- Chat 顶部培训工作区 +- 视频 -> 总结 -> 答题 -> 结果 的前端交互链 +- 后端培训记录落库 +- HR 列表 / 统计 / Excel 导出 +- 页面刷新后恢复培训进度 + +### 7.2 当前不足 + +- 题库、知识点、欢迎语、通过线仍主要固化在前端 +- 视频仍可配置但未形成正式素材管理闭环 +- Dify 尚未作为培训 FAQ / HR ChatBI 的正式辅助层接入 +- 自动化测试不足 +- 培训配置后台化不足 + +## 8. 推荐实施顺序 + +### P0:先把“受控考试主链”做扎实 + +1. 保留当前培训工作区主链,不回退为纯 Dify 考试流 +2. 完善后端培训记录接口测试 +3. 补齐前端回归测试: + - 视频完成 + - 开始考试 + - 连续答题 + - 结算 + - 补考 + - 刷新恢复 +4. 补齐 HR 权限和导出验收 + +### P1:把培训内容改成可配置 + +1. 题库从前端资源迁到后端配置或 Agent 配置 +2. 知识点、欢迎语、通过线可配置 +3. 培训视频改成正式素材配置 +4. 增加题库版本号与配置快照 + +### P2:引入 Dify 做辅助能力 + +1. 培训 FAQ 与知识点解释走 Dify +2. HR 自然语言统计与导出走 Dify + Tool API +3. 对外形成“看起来像 Chat,底层仍受控”的最终体验 + +
+ +## 9、 对话交互流程设计 (User Journey) + +### 2.1 员工端:沉浸式导学与考核 + +整个流程在 HXOPS 的 Chat 界面中闭环,分为四个状态阶段: + +#### 阶段 1:破冰与视频导学 (Onboarding):(展示条件:考试未通过员工每次进入该agent页面都自动展示该阶段信息,考试通过后不再展示) + +- **Agent**: "👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。" +- **Agent**: "▶️ 请先点击观看 \[入职培训视频链接]。观看完毕后,开始**知识点复盘**。" + +#### 阶段 2:**知识点复盘** (Knowledge Summary) + +- **Agent**: "太棒了!结合刚才的视频,我为你提炼了以下核心知识点(必考哦): + > 1. **薪酬考勤**:每月15号发工资;打卡、请假必须走 OA 系统。 + > 2. **日常行政**:中米新订餐系统订餐;灭火器需站在上风口。 + > 3. **体系与安全**:QC080000 是有害物质管理标准;5S 是整理、整顿、清扫、清洁、素养。 + > 准备好接受挑战了吗?直接点击**【开始考试】**或Chat中请回复**【开始考试】**。" + +#### 阶段 3:互动测试 (Interactive QA) - 循环20次 + +- **User**: "开始考试" +- **Agent**: "📝 **第 1 题 / 共 20 题(单选题)**:工资每月几号发放? + A. 8号 B. 9号 C. 15号 D. 27号 + 请直接回复选项或内容。" +- **User**: "C" +- **Agent**: "✅ **回答正确!** 当前得分:5分。 + 📝 **第 2 题 / 共 20 题(判断题)**:发生火灾、爆炸事故时,应立即拨打“119”。(请回复对或错)" +- **User**: "错" +- **Agent**: "❌ **回答错误。** 正确答案是:【对】。 + *解析:生命安全第一,发生火灾必须立即拨打119。* + 当前得分:5分。 + 📝 **第 3 题 / 共 20 题...**" + +#### 阶段 4:结算与归档 (Settlement) + +- *(如果 < 90 分)* + **Agent**: "📊 **考试结束!** 您的最终得分是 **85 分**。及格线为 90 分。请回复【重新考试】再次挑战!" +- *(如果 >= 90 分)* + **Agent**: "🎉 **恭喜!** 您的最终得分是 **95 分**,已顺利通过新人考核!您的成绩已自动同步至人事部门。" + +### 2.2 HR 管理端:对话式数据管家 (ChatBI) + +无需额外开发后台管理页面,HR 直接通过自然语言与 Agent 对话,完成数据统计与报表导出。 + +#### 场景 1:日常数据速查 (ChatBI) + +- **HR**: "帮我查一下这个月有多少人完成了新人培训?通过率怎么样?" +- **Agent (思考中...)**: *(调用工具* *`query_training_stats`)* +- **Agent**: "📊 **本月新人培训速报**:参训 15 人,通过 12 人,未通过 3 人,整体通过率 80%。" + +#### 场景 2:报表一键导出 (Chat 导出 Excel) + +- **HR**: "把本月通过的员工名单导出成 Excel。" +- **Agent (思考中...)**: *(调用工具* *`export_training_records`)* +- **Agent**: "✅ 已为您生成本月的培训成绩报表,包含入职日期、部门、姓名、工号和最终分数。 + 📁 **点击下载文件**:\[本月新人培训合格名单.xlsx]" + +## 10. 最终建议 + +对于“员工培训 Agent”,当前阶段最合适的技术路线是: + +- **主链**:继续采用当前 `Chat 化展示 + 受控工作区 + 后端真实落库` +- **增强层**:再逐步接入 Dify 做 FAQ、解释和 HR ChatBI + +不建议将考试主链整体改造成纯 Dify 编排,否则会显著增加: + +- 流程漂移风险 +- 防作弊成本 +- 测试成本 +- 审计成本 + +## 11. 一句话结论 + +**员工培训考试主链要“稳、准、可审计”,就让 HXOPS 前后端控制;Dify 更适合做问答增强和 HR 自然语言数据助手。** diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index ea80710b..564c6463 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -1,4 +1,4 @@ -/** +/** * features/admin/api/admin.api.ts * 管理后台 HTTP API:用户、部门、Agent、权限、报表、企业微信、公告等。 */ @@ -131,6 +131,27 @@ export const uploadAdminAgentGuideFile = async (file: File) => { } return response.json(); }; +export const importAdminAgentTrainingQuestionBankFromPdf = (agentId: number, payload: { guide_id?: number | null }) => + requestJson<{ + guide_id: number; + guide_file_name: string; + parsed_count: number; + skipped_question_numbers: number[]; + extraction_mode?: 'pdf_text' | 'ocr' | 'ocr_fallback'; + extraction_warnings?: string[]; + question_bank: Array<{ + id: string; + type: 'single' | 'boolean'; + prompt: string; + answer: string; + explanation: string; + options?: Array<{ id: string; label: string }>; + }>; + }>(`/api/admin/agents/${agentId}/training-question-bank/import-pdf`, { + method: 'POST', + ...jsonAuth(), + body: JSON.stringify(payload), + }); export const testAdminAgent = (id: number) => requestJson(`/api/admin/agents/${id}/test`, { method: 'POST', ...auth() }); export const saveAdminAgentPermissions = (agentId: number, userIds: number[]) => diff --git a/frontend/src/features/admin/modules/agents/AgentsPage.vue b/frontend/src/features/admin/modules/agents/AgentsPage.vue index 9d15a4f9..3e5bb403 100644 --- a/frontend/src/features/admin/modules/agents/AgentsPage.vue +++ b/frontend/src/features/admin/modules/agents/AgentsPage.vue @@ -1,4 +1,4 @@ -/** +/** * features/admin/modules/agents/AgentsPage.vue * * 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。 @@ -29,9 +29,11 @@ const { t } = useI18n(); const { agents, scheduleTasks, + trainingExamPdfGuides, activeUsers, isLoading, isSaving, + isImportingTrainingPdf, isEditing, selectedAgentId, form, @@ -50,6 +52,11 @@ const { submitAgent, addSuggestedQuestion, removeSuggestedQuestion, + addTrainingQuestion, + removeTrainingQuestion, + addTrainingOption, + removeTrainingOption, + importTrainingQuestionBankFromPdf, deleteAgent, openTestModal, runAgentTest, @@ -229,12 +236,19 @@ onMounted(() => { :visible="showFormDialog" :is-editing="isEditing" :is-saving="isSaving" + :is-importing-training-pdf="isImportingTrainingPdf" :form="form" :schedule-tasks="scheduleTasks" + :training-exam-pdf-guides="trainingExamPdfGuides" @close="showFormDialog = false" @save="saveAgentForm" @add-suggested-question="addSuggestedQuestion" @remove-suggested-question="removeSuggestedQuestion" + @add-training-question="addTrainingQuestion" + @remove-training-question="removeTrainingQuestion" + @add-training-option="addTrainingOption" + @remove-training-option="removeTrainingOption" + @import-training-pdf="importTrainingQuestionBankFromPdf" /> -import { Plus, Trash2, X } from 'lucide-vue-next'; +import { FileDown, Plus, Trash2, X } from 'lucide-vue-next'; import { useI18n } from 'vue-i18n'; -import type { AgentFormState } from '@/features/admin/types/agent.types'; +import type { AgentFormState, AgentGuideSummary } from '@/features/admin/types/agent.types'; import type { ScheduleTask } from '@/shared/types/schedule.types'; import AgentToolRunProgressConfig from './AgentToolRunProgressConfig.vue'; @@ -17,8 +17,10 @@ defineProps<{ visible: boolean; isEditing: boolean; isSaving: boolean; + isImportingTrainingPdf: boolean; form: AgentFormState; scheduleTasks: ScheduleTask[]; + trainingExamPdfGuides: AgentGuideSummary[]; }>(); const emit = defineEmits<{ @@ -26,9 +28,40 @@ const emit = defineEmits<{ save: []; addSuggestedQuestion: []; removeSuggestedQuestion: [index: number]; + addTrainingQuestion: []; + removeTrainingQuestion: [index: number]; + addTrainingOption: [questionIndex: number]; + removeTrainingOption: [questionIndex: number, optionIndex: number]; + importTrainingPdf: [guideId?: number | null]; }>(); const { t } = useI18n(); +const optionLabels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); + +/** + * 切换培训题型时同步修正表单结构。 + * 核心逻辑:判断题固定使用 true/false;单选题至少保留两个选项,并把答案回落到首个可用选项。 + */ +const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) => { + const question = form.training_question_bank[index]; + if (!question) return; + if (question.type === 'boolean') { + question.options = []; + question.answer = question.answer === 'false' ? 'false' : 'true'; + return; + } + if (!Array.isArray(question.options)) { + question.options = ['', '']; + } + while (question.options.length < 2) { + question.options.push(''); + } + const validAnswerIds = question.options + .map((item) => String(item || '').trim()) + .filter(Boolean) + .map((_, optionIndex) => String.fromCharCode(97 + optionIndex)); + question.answer = validAnswerIds.includes(question.answer) ? question.answer : (validAnswerIds[0] || 'a'); +};