Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	.env.dev
#	.env.test
#	backend/app/api/__init__.py
#	docs/funclist.md
#	frontend/src/features/chat/composables/useChatPage.ts
This commit is contained in:
hugo committed 2026-07-06 08:35:40 +08:00
commit f72c1c9f0e
101 files changed
+11163 -334

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
DEBUG_SERVER_URL=http://127.0.0.1:7778/event
DEBUG_SESSION_ID=retry-rpa-no-request
+1 -1
View File
@@ -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
+4 -1
View File
@@ -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')
+16
View File
@@ -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/<int:id>/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
+1
View File
@@ -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,
+127 -2
View File
@@ -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:
+176
View File
@@ -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/<int:device_id>', 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/<int:device_id>', 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/<int:record_id>', 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/<int:record_id>', 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/<int:record_id>', 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)))
+149
View File
@@ -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),
})
+1
View File
@@ -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']
+9
View File
@@ -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
+7 -2
View File
@@ -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
+14 -5
View File
@@ -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():
+15 -1
View File
@@ -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
+4
View File
@@ -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'),
+4
View File
@@ -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',
]
+1
View File
@@ -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)
+101
View File
@@ -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)
+52
View File
@@ -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)
@@ -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)
+33 -1
View File
@@ -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()
@@ -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
@@ -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:
+325
View File
@@ -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]}"
@@ -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)
@@ -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 [],
}
@@ -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}
@@ -0,0 +1,8 @@
"""
backend/app/services/maintenance_tools/__init__.py
用途:设备维保 Dify Tool 服务包入口。
依赖:openapi_spec 等子模块。
逻辑:api/maintenance_tools.py 通过本包导入 OpenAPI 构建能力,后续可继续扩展工具编排。
"""
@@ -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": []}],
}
+19
View File
@@ -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)
@@ -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')
@@ -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')
@@ -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')
@@ -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'
+318
View File
@@ -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
+25
View File
@@ -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
-21
View File
@@ -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. 复现一次并按证据排除假设。
+9
View File
@@ -1,5 +1,14 @@
# 智能HR请假管理需求
## 设备维保助手补充需求
- 查询方式:用户通过 `设备维保助手` 会话查询设备维护/维修记录,系统支持按设备编号、设备名称、故障描述、维修说明、维修人和状态筛选记录。
- 管理方式:新增维修记录、设备台账配置属于固定管理人员操作,不通过会话消息承载;在聊天输入区底部以按钮进入右侧固定面板,面板顶部可关闭。
- 台账配置:右侧固定面板包含“设备列表”和“设备配置”两个 Tab,设备字段包含设备编号、设备名称、型号规格、使用部门、安装地点、设备状态、制造厂家、进厂日期、生产日期、启用日期、责任人用户名、维护周期和备注。
- Excel 导入:设备台账支持下载模板并从 Excel 批量导入,按设备编号判断新增或更新。
- 责任人规则:`responsible_user` 存储用户名文本,当前阶段不与用户表建立外键关联。
- 范围裁剪:不提供维修字典配置功能,不在底部按钮中展示该入口。
## 1. 项目背景
当前系统已经具备以下基础能力:
+19 -3
View File
@@ -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 本人假期查询
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+137
View File
@@ -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 名称为 `设备维保助手` 时显示底部管理按钮;查询继续走会话,配置类操作进入右侧固定面板。
@@ -0,0 +1,143 @@
# 员工入职培训 Agent (对话式考核与管理) 产品设计与落地文档
## 一、 背景与业务目标
### 1.1 业务背景
人事部门(HR)提出新需求,需要对入职员工进行在线培训与考核。
核心诉求包括:
1. **学习闭环**:要求员工先观看培训视频,然后总结知识点最后进行答题。
2. **交互式测试**:通过逐题一问一答的方式进行测试(共20题,每题5分,满分100分)。
3. **即时反馈机制**:答对继续;答错必须即时显示正确答案及解析,以强化记忆。
4. **通过标准**:90分及格,未通过者必须重新考试直至通过。
5. **数据统计与导出**:HR 需要统计考试结果,并能够导出包含“入职日期、完成日期、部门、姓名、工号、分数”的表格。
<br />
效益整理
### 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 架构在企业内部管理效能提升上的巨大优势。
@@ -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,底层仍受控”的最终体验
<br />
## 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 自然语言数据助手。**
+22 -1
View File
@@ -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<any>(`/api/admin/agents/${id}/test`, { method: 'POST', ...auth() });
export const saveAdminAgentPermissions = (agentId: number, userIds: number[]) =>
@@ -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"
/>
<AgentPermissionModal
@@ -7,9 +7,9 @@
*/
<script setup lang="ts">
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');
};
</script>
<template>
@@ -202,6 +235,218 @@ const { t } = useI18n();
</div>
</div>
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
<div>
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('admin.agent.training.title') }}</div>
<p class="mt-1 text-sm leading-6 text-secondary">{{ t('admin.agent.training.subtitle') }}</p>
</div>
<label class="inline-flex items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary">
<input v-model="form.training_workspace_enabled" type="checkbox" class="accent-brand-600" />
<span>{{ t('admin.agent.training.enable') }}</span>
</label>
</div>
<p class="mt-3 text-xs leading-5 text-muted">
{{ form.training_workspace_enabled ? t('admin.agent.training.enableHint') : t('admin.agent.training.disabledHint') }}
</p>
<div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-3">
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.passScore') }}</label>
<input
v-model.number="form.training_pass_score"
type="number"
min="0"
max="100"
step="1"
class="w-full input-field text-sm"
/>
<p class="text-xs leading-5 text-muted">{{ t('admin.agent.training.passScoreHint') }}</p>
</div>
<div class="space-y-2 md:col-span-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.summaryPoints') }}</label>
<textarea
v-model="form.training_summary_points_text"
rows="5"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.training.summaryPointsPlaceholder')"
/>
</div>
<div class="space-y-2 md:col-span-3">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.summaryChecklist') }}</label>
<textarea
v-model="form.training_summary_checklist_text"
rows="4"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.training.summaryChecklistPlaceholder')"
/>
</div>
</div>
<div class="mt-5 space-y-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<div class="text-sm font-semibold text-primary">{{ t('admin.agent.training.questionBank') }}</div>
<p class="mt-1 text-xs leading-5 text-muted">{{ t('admin.agent.training.questionHint') }}</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
:disabled="!isEditing || trainingExamPdfGuides.length === 0 || isImportingTrainingPdf"
@click="emit('importTrainingPdf', trainingExamPdfGuides[0]?.id || null)"
>
<FileDown class="h-4 w-4" />
{{ isImportingTrainingPdf ? t('admin.agent.training.importingPdf') : t('admin.agent.training.importFromPdf') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="emit('addTrainingQuestion')"
>
<Plus class="h-4 w-4" />
{{ t('admin.agent.training.addQuestion') }}
</button>
</div>
</div>
<p class="text-xs leading-5 text-muted">
{{
!isEditing
? t('admin.agent.training.importPdfCreateFirst')
: trainingExamPdfGuides.length > 0
? t('admin.agent.training.importPdfHint', { fileName: trainingExamPdfGuides[0]?.file_name || '--' })
: t('admin.agent.training.importPdfMissing')
}}
</p>
<div v-if="form.training_question_bank.length === 0" class="rounded-xl border border-dashed border-default bg-white px-4 py-5 text-sm text-muted">
{{ t('admin.agent.training.emptyQuestionBank') }}
</div>
<div v-else class="space-y-4">
<div
v-for="(question, questionIndex) in form.training_question_bank"
:key="questionIndex"
class="rounded-2xl border border-default bg-white p-4"
>
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div class="text-sm font-semibold text-primary">
{{ t('admin.agent.training.questionCardTitle', { index: questionIndex + 1 }) }}
</div>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs font-medium text-red-600 transition-colors hover:bg-red-100"
@click="emit('removeTrainingQuestion', questionIndex)"
>
<Trash2 class="h-4 w-4" />
{{ t('admin.agent.training.removeQuestion') }}
</button>
</div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionId') }}</label>
<input
v-model="question.id"
type="text"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.training.questionIdPlaceholder')"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionType') }}</label>
<select
v-model="question.type"
class="w-full input-field text-sm"
@change="handleTrainingQuestionTypeChange(form, questionIndex)"
>
<option value="single">{{ t('admin.agent.training.single') }}</option>
<option value="boolean">{{ t('admin.agent.training.boolean') }}</option>
</select>
</div>
<div class="space-y-2">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.correctAnswer') }}</label>
<select v-model="question.answer" class="w-full input-field text-sm">
<template v-if="question.type === 'boolean'">
<option value="true">{{ t('admin.agent.training.booleanTrue') }}</option>
<option value="false">{{ t('admin.agent.training.booleanFalse') }}</option>
</template>
<template v-else>
<option
v-for="(_, optionIndex) in question.options.filter((item) => String(item || '').trim())"
:key="`${questionIndex}-${optionIndex}`"
:value="String.fromCharCode(97 + optionIndex)"
>
{{ t('admin.agent.training.optionLabel', { label: optionLabels[optionIndex] || optionIndex + 1 }) }}
</option>
</template>
</select>
</div>
<div class="space-y-2 md:col-span-3">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionPrompt') }}</label>
<textarea
v-model="question.prompt"
rows="3"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.training.questionPromptPlaceholder')"
/>
</div>
<div class="space-y-2 md:col-span-3">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionExplanation') }}</label>
<textarea
v-model="question.explanation"
rows="3"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.training.questionExplanationPlaceholder')"
/>
</div>
<div v-if="question.type === 'single'" class="space-y-3 md:col-span-3">
<div class="flex flex-wrap items-center justify-between gap-3">
<label class="text-xs font-semibold text-secondary">{{ t('admin.agent.training.questionOptions') }}</label>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default bg-surface-soft px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-slate-100"
@click="emit('addTrainingOption', questionIndex)"
>
<Plus class="h-4 w-4" />
{{ t('admin.agent.training.addOption') }}
</button>
</div>
<div class="grid gap-3 md:grid-cols-2">
<div
v-for="(_, optionIndex) in question.options"
:key="`${questionIndex}-option-${optionIndex}`"
class="flex items-center gap-2 rounded-xl border border-default bg-surface-soft/40 p-3"
>
<span class="min-w-6 text-xs font-semibold text-muted">{{ optionLabels[optionIndex] || optionIndex + 1 }}.</span>
<input
v-model="question.options[optionIndex]"
type="text"
class="w-full input-field text-sm"
:placeholder="t('admin.agent.training.optionPlaceholder')"
/>
<button
type="button"
class="inline-flex h-10 w-10 items-center justify-center rounded-lg border border-red-200 bg-red-50 text-red-600 transition-colors hover:bg-red-100"
@click="emit('removeTrainingOption', questionIndex, optionIndex)"
>
<Trash2 class="h-4 w-4" />
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<AgentToolRunProgressConfig
v-if="form.type === 'api' && form.dify_app_type !== 'workflow'"
:form="form"
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/agents/composables/useAgentsAdmin.ts
*
* Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。
@@ -10,6 +10,8 @@ import { useI18n } from 'vue-i18n';
import {
createAdminAgent,
deleteAdminAgent,
importAdminAgentTrainingQuestionBankFromPdf,
listAdminAgentGuides,
listAdminAgents,
listAdminUsers,
saveAdminAgentPermissions,
@@ -19,10 +21,19 @@ import {
import { listAdminSchedules } from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentFormState, AgentRow, AgentSuggestedQuestionItem, AgentTestResult } from '@/features/admin/types/agent.types';
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
import type {
AgentFormState,
AgentRow,
AgentSuggestedQuestionItem,
AgentTestResult,
AgentTrainingQuestionFormItem,
AgentGuideSummary,
} from '@/features/admin/types/agent.types';
import { createEmptyAgentForm, createEmptyTrainingQuestionForm } from '@/features/admin/types/agent.types';
import type { ScheduleTask } from '@/shared/types/schedule.types';
const TRAINING_OPTION_IDS = 'abcdefghijklmnopqrstuvwxyz'.split('');
const normalizeSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
return value
@@ -39,6 +50,169 @@ const normalizeSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem
.filter((item): item is AgentSuggestedQuestionItem => !!item);
};
const asRecord = (value: unknown): Record<string, unknown> => (
value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: {}
);
const toMultilineText = (value: unknown) => (
Array.isArray(value)
? value.map((item) => String(item || '').trim()).filter(Boolean).join('\n')
: ''
);
const splitMultilineText = (value: string): string[] => value
.split(/\r?\n/)
.map((item) => item.trim())
.filter(Boolean);
type TrainingImportPayload = Awaited<ReturnType<typeof importAdminAgentTrainingQuestionBankFromPdf>>;
/**
* 从 Agent extra_config 解析员工培训配置表单字段。
* 核心逻辑:优先读取 extra_config.training_config,兼容历史顶层字段;单选题选项统一收敛成纯文本数组,便于后台表单维护。
*/
const parseTrainingConfigFromExtra = (extra: Record<string, unknown> | undefined) => {
const trainingConfig = asRecord(extra?.training_config);
const merged = {
...asRecord(extra),
...trainingConfig,
};
const rawQuestionBank: unknown[] = Array.isArray(merged.question_bank ?? merged.questionBank)
? (merged.question_bank ?? merged.questionBank) as unknown[]
: [];
const questionBank: AgentTrainingQuestionFormItem[] = rawQuestionBank
.map((item: unknown, index: number): AgentTrainingQuestionFormItem => {
const raw = asRecord(item);
const type: AgentTrainingQuestionFormItem['type'] = raw.type === 'boolean' ? 'boolean' : 'single';
const rawOptions: unknown[] = Array.isArray(raw.options) ? raw.options : [];
const optionLabels = type === 'single'
? rawOptions
.map((option: unknown) => {
if (typeof option === 'string') return option.trim();
return String(asRecord(option).label || '').trim();
})
.filter(Boolean)
: [];
while (type === 'single' && optionLabels.length < 2) {
optionLabels.push('');
}
return {
id: String(raw.id || '').trim() || `q${index + 1}`,
type,
prompt: String(raw.prompt || '').trim(),
explanation: String(raw.explanation || '').trim(),
options: optionLabels,
answer: type === 'boolean'
? (String(raw.answer || '').trim() === 'false' ? 'false' : 'true')
: (() => {
const answer = String(raw.answer || '').trim();
const optionIds = optionLabels.map((_, optionIndex) => TRAINING_OPTION_IDS[optionIndex]).filter(Boolean);
return optionIds.includes(answer) ? answer : (optionIds[0] || 'a');
})(),
};
})
.filter((item) => Boolean(item.prompt || item.id || item.options.length));
const hasTrainingContent = questionBank.length > 0
|| Boolean(toMultilineText(merged.summary_points ?? merged.summaryPoints))
|| Boolean(toMultilineText(merged.summary_checklist ?? merged.summaryChecklist));
return {
training_workspace_enabled:
extra?.training_workspace_enabled === true
|| extra?.training_workspace_enabled === 'true'
|| extra?.training_mode === true
|| extra?.training_mode === 'true'
|| extra?.training_agent === true
|| extra?.training_agent === 'true'
|| hasTrainingContent,
training_pass_score: Number.isFinite(Number(merged.pass_score ?? merged.passScore))
? Math.max(0, Math.min(100, Math.round(Number(merged.pass_score ?? merged.passScore))))
: 90,
training_summary_points_text: toMultilineText(merged.summary_points ?? merged.summaryPoints),
training_summary_checklist_text: toMultilineText(merged.summary_checklist ?? merged.summaryChecklist),
training_question_bank: questionBank,
};
};
const buildTrainingQuestionPayload = (question: AgentTrainingQuestionFormItem, index: number) => {
const id = String(question.id || '').trim() || `q${index + 1}`;
const prompt = String(question.prompt || '').trim();
const explanation = String(question.explanation || '').trim();
if (question.type === 'boolean') {
return {
id,
type: 'boolean' as const,
prompt,
answer: question.answer === 'false' ? 'false' : 'true',
explanation,
};
}
const normalizedOptions = question.options
.map((label) => String(label || '').trim())
.filter(Boolean)
.map((label, optionIndex) => ({
id: TRAINING_OPTION_IDS[optionIndex] || `option_${optionIndex + 1}`,
label,
}));
const optionIds = normalizedOptions.map((item) => item.id);
return {
id,
type: 'single' as const,
prompt,
answer: optionIds.includes(question.answer) ? question.answer : (optionIds[0] || 'a'),
explanation,
options: normalizedOptions,
};
};
const hasTrainingConfigContent = (form: AgentFormState) => (
form.training_workspace_enabled
|| Boolean(form.training_summary_points_text.trim())
|| Boolean(form.training_summary_checklist_text.trim())
|| form.training_question_bank.length > 0
);
/**
* 生成培训试题 PDF 导入完成后的反馈文案。
* 核心逻辑:先反馈题库导入结果,再补充 OCR 回退与诊断提示,避免 HR 误以为扫描件导入结果可直接信任。
*/
const buildTrainingPdfImportMessages = (
payload: TrainingImportPayload,
t: ReturnType<typeof useI18n>['t'],
): { primary: string; notices: string[] } => {
const skipped = Array.isArray(payload.skipped_question_numbers) ? payload.skipped_question_numbers : [];
const extractionWarnings = Array.isArray(payload.extraction_warnings)
? payload.extraction_warnings.map((item) => String(item || '').trim()).filter(Boolean)
: [];
const primary = skipped.length
? t('admin.agent.training.importPdfPartialSuccess', {
count: payload.parsed_count,
skipped: skipped.join('、'),
})
: t('admin.agent.training.importPdfSuccess', {
count: payload.parsed_count,
fileName: payload.guide_file_name,
});
const notices: string[] = [];
if (payload.extraction_mode === 'ocr') {
notices.push(t('admin.agent.training.importPdfOcrUsed'));
} else if (payload.extraction_mode === 'ocr_fallback') {
notices.push(t('admin.agent.training.importPdfOcrFallback'));
}
if (extractionWarnings.length) {
notices.push(t('admin.agent.training.importPdfWarnings', {
warnings: extractionWarnings.join(';'),
}));
}
return { primary, notices };
};
/**
* 从 Agent extra_config 解析 tool_run_progress 表单字段。
* 核心逻辑:capabilities 含 tool_run_progress 时视为启用;task_id 与 schedule_task_id 等价。
@@ -120,8 +294,10 @@ export function useAgentsAdmin() {
const agents = ref<AgentRow[]>([]);
const users = ref<AdminUserRow[]>([]);
const scheduleTasks = ref<ScheduleTask[]>([]);
const trainingExamPdfGuides = ref<AgentGuideSummary[]>([]);
const isLoading = ref(true);
const isSaving = ref(false);
const isImportingTrainingPdf = ref(false);
const isEditing = ref(false);
const selectedAgentId = ref<number | null>(null);
const form = ref<AgentFormState>(createEmptyAgentForm());
@@ -168,6 +344,22 @@ export function useAgentsAdmin() {
}
};
const loadTrainingExamPdfGuides = async (agentId: number | null | undefined): Promise<void> => {
if (!agentId) {
trainingExamPdfGuides.value = [];
return;
}
try {
const guides = await listAdminAgentGuides(agentId);
trainingExamPdfGuides.value = (Array.isArray(guides) ? guides : []).filter((guide) => (
guide?.file_type === 'pdf' && guide?.guide_usage === 'training_exam_pdf'
));
} catch (e) {
console.error('Error loading training exam PDF guides:', e);
trainingExamPdfGuides.value = [];
}
};
const loadAll = async (): Promise<void> => {
isLoading.value = true;
await Promise.all([loadAgents(), loadUsers(), loadScheduleTasks()]);
@@ -177,6 +369,7 @@ export function useAgentsAdmin() {
const resetForm = (): void => {
selectedAgentId.value = null;
form.value = createEmptyAgentForm();
trainingExamPdfGuides.value = [];
isEditing.value = false;
};
@@ -185,6 +378,7 @@ export function useAgentsAdmin() {
? agent.extra_config
: {};
const toolRunProgress = parseToolRunProgressFromExtra(extra);
const trainingConfig = parseTrainingConfigFromExtra(extra);
selectedAgentId.value = agent.id;
form.value = {
id: agent.id,
@@ -205,8 +399,10 @@ export function useAgentsAdmin() {
? Math.floor(Number(extra.sort_order))
: 0,
...toolRunProgress,
...trainingConfig,
};
isEditing.value = true;
void loadTrainingExamPdfGuides(agent.id);
};
const openDeleteConfirm = (
@@ -242,6 +438,32 @@ export function useAgentsAdmin() {
msg.warning(t('admin.dept.msg.nameRequired'));
return false;
}
if (form.value.training_workspace_enabled) {
if (form.value.training_question_bank.length === 0) {
msg.warning(t('admin.agent.training.validation.questionRequired'));
return false;
}
for (let index = 0; index < form.value.training_question_bank.length; index += 1) {
const question = form.value.training_question_bank[index];
if (!question) continue;
if (!String(question.prompt || '').trim()) {
msg.warning(t('admin.agent.training.validation.questionPromptRequired', { index: index + 1 }));
return false;
}
if (question.type === 'single') {
const validOptions = question.options.map((item) => String(item || '').trim()).filter(Boolean);
if (validOptions.length < 2) {
msg.warning(t('admin.agent.training.validation.questionSingleOptions', { index: index + 1 }));
return false;
}
const validAnswerIds = validOptions.map((_, optionIndex) => TRAINING_OPTION_IDS[optionIndex]).filter(Boolean);
if (!validAnswerIds.includes(question.answer)) {
msg.warning(t('admin.agent.training.validation.questionAnswerRequired', { index: index + 1 }));
return false;
}
}
}
}
const supportsToolRunProgress = form.value.type === 'api' && form.value.dify_app_type !== 'workflow';
if (supportsToolRunProgress && form.value.tool_run_progress_enabled && !form.value.schedule_task_id) {
msg.warning(t('admin.agent.toolRunProgress.scheduleTaskRequired'));
@@ -280,6 +502,17 @@ export function useAgentsAdmin() {
applyToolRunProgressToExtra(extra_config, { ...form.value, tool_run_progress_enabled: false });
}
applyAgentCategoryToExtra(extra_config, form.value);
extra_config.training_workspace_enabled = Boolean(form.value.training_workspace_enabled);
if (hasTrainingConfigContent(form.value)) {
extra_config.training_config = {
pass_score: Math.max(0, Math.min(100, Math.round(Number(form.value.training_pass_score) || 90))),
summary_points: splitMultilineText(form.value.training_summary_points_text),
summary_checklist: splitMultilineText(form.value.training_summary_checklist_text),
question_bank: form.value.training_question_bank.map((question, index) => buildTrainingQuestionPayload(question, index)),
};
} else {
delete extra_config.training_config;
}
try {
const editingId = isEditing.value ? Number(form.value.id) : null;
@@ -336,6 +569,70 @@ export function useAgentsAdmin() {
form.value.suggested_questions.splice(index, 1);
};
const addTrainingQuestion = (): void => {
form.value.training_question_bank.push(createEmptyTrainingQuestionForm());
};
const removeTrainingQuestion = (index: number): void => {
form.value.training_question_bank.splice(index, 1);
};
const addTrainingOption = (questionIndex: number): void => {
const question = form.value.training_question_bank[questionIndex];
if (!question || question.type !== 'single') return;
question.options.push('');
};
const removeTrainingOption = (questionIndex: number, optionIndex: number): void => {
const question = form.value.training_question_bank[questionIndex];
if (!question || question.type !== 'single') return;
question.options.splice(optionIndex, 1);
if (question.options.length < 2) {
question.options.push('');
}
const validAnswerIds = question.options
.map((item) => String(item || '').trim())
.filter(Boolean)
.map((_, normalizedIndex) => TRAINING_OPTION_IDS[normalizedIndex])
.filter(Boolean);
question.answer = validAnswerIds.includes(question.answer) ? question.answer : (validAnswerIds[0] || 'a');
};
/**
* 从已上传的培训试题 PDF 导入题库到当前 Agent 表单。
* 核心逻辑:解析结果只回填当前表单,不直接保存数据库,确保 HR 可以先检查题干、选项和答案后再提交。
*/
const importTrainingQuestionBankFromPdf = async (guideId?: number | null): Promise<void> => {
const agentId = Number(form.value.id);
if (!agentId) {
msg.warning(t('admin.agent.training.importPdfAgentRequired'));
return;
}
isImportingTrainingPdf.value = true;
try {
const payload = await importAdminAgentTrainingQuestionBankFromPdf(agentId, { guide_id: guideId ?? null });
form.value.training_question_bank = (payload.question_bank || []).map((question, index) => ({
id: String(question.id || '').trim() || `q${index + 1}`,
type: question.type === 'boolean' ? 'boolean' : 'single',
prompt: String(question.prompt || '').trim(),
explanation: String(question.explanation || '').trim(),
options: question.type === 'boolean'
? []
: (question.options || []).map((option) => String(option.label || '').replace(/^[A-D]\.\s*/i, '').trim()),
answer: String(question.answer || '').trim() || (question.type === 'boolean' ? 'true' : 'a'),
}));
form.value.training_workspace_enabled = true;
const importMessages = buildTrainingPdfImportMessages(payload, t);
msg.success(importMessages.primary);
importMessages.notices.forEach((notice) => msg.warning(notice));
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed'));
} finally {
isImportingTrainingPdf.value = false;
}
};
const deleteAgent = async (id: number): Promise<void> => {
openDeleteConfirm(t('admin.agent.confirmDelete'), async () => {
try {
@@ -436,9 +733,11 @@ export function useAgentsAdmin() {
agents,
users,
scheduleTasks,
trainingExamPdfGuides,
activeUsers,
isLoading,
isSaving,
isImportingTrainingPdf,
isEditing,
selectedAgentId,
form,
@@ -457,6 +756,11 @@ export function useAgentsAdmin() {
submitAgent,
addSuggestedQuestion,
removeSuggestedQuestion,
addTrainingQuestion,
removeTrainingQuestion,
addTrainingOption,
removeTrainingOption,
importTrainingQuestionBankFromPdf,
deleteAgent,
openTestModal,
runAgentTest,
@@ -97,6 +97,7 @@ onMounted(() => {
<select v-model="permissionFilters.role" class="admin-table-filter-input w-32">
<option value="">{{ t('admin.perm.allRoles') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="hr">{{ t('admin.role.hr') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
@@ -19,6 +19,7 @@ const form = ref({
file_name: '',
file_path: '',
file_type: 'pdf',
guide_usage: 'general',
file_size: 0,
remark: '',
sort_order: 0,
@@ -68,6 +69,7 @@ const openCreateModal = () => {
file_name: '',
file_path: '',
file_type: 'pdf',
guide_usage: 'general',
file_size: 0,
remark: '',
sort_order: 0,
@@ -84,6 +86,7 @@ const openEditModal = (guide: any) => {
file_name: guide.file_name,
file_path: guide.file_path,
file_type: guide.file_type,
guide_usage: guide.guide_usage || 'general',
file_size: guide.file_size,
remark: guide.remark,
sort_order: guide.sort_order,
@@ -105,6 +108,12 @@ const handleFileUpload = async (event: Event) => {
form.value.file_path = res.file_path;
form.value.file_type = res.file_type;
form.value.file_size = res.file_size;
if (form.value.guide_usage === 'training_video' && res.file_type !== 'video') {
form.value.guide_usage = 'general';
}
if (form.value.guide_usage === 'training_exam_pdf' && res.file_type !== 'pdf') {
form.value.guide_usage = 'general';
}
if (!form.value.file_name) {
form.value.file_name = res.file_name;
}
@@ -215,6 +224,7 @@ const getIcon = (type: string) => {
<tr>
<th class="px-6 py-4">类型</th>
<th class="px-6 py-4">资料名称</th>
<th class="px-6 py-4">{{ t('admin.platformApps.guideUsage') }}</th>
<th class="px-6 py-4">Agent应用</th>
<th class="px-6 py-4">文件大小</th>
<th class="px-6 py-4">排序</th>
@@ -231,6 +241,11 @@ const getIcon = (type: string) => {
<div class="font-medium text-default">{{ guide.file_name }}</div>
<div class="text-xs text-muted mt-1 truncate max-w-[200px]">{{ guide.remark }}</div>
</td>
<td class="px-6 py-4 text-muted">
<span v-if="guide.guide_usage === 'training_video'">{{ t('admin.platformApps.trainingVideo') }}</span>
<span v-else-if="guide.guide_usage === 'training_exam_pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</span>
<span v-else>{{ t('admin.platformApps.generalGuide') }}</span>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-brand-50 text-brand-700 border border-brand-100">
{{ currentAgentName }}
@@ -296,6 +311,15 @@ const getIcon = (type: string) => {
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<label class="text-sm font-medium text-default">{{ t('admin.platformApps.guideUsage') }}</label>
<select v-model="form.guide_usage" class="input-field w-full">
<option value="general">{{ t('admin.platformApps.generalGuide') }}</option>
<option value="training_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingVideo') }}</option>
<option value="training_exam_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</option>
</select>
<p class="text-xs text-muted">{{ t('admin.platformApps.guideUsageHint') }}</p>
</div>
<div class="space-y-2">
<label class="text-sm font-medium text-default">排序权重</label>
<input v-model.number="form.sort_order" type="number" class="input-field w-full" />
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/users/UsersPage.vue
* 用途:用户管理独立页面(服务端筛选分页、批量操作)。
* 依赖:useUsersAdmin、PaginationBar、用户相关 Modal。
@@ -189,10 +189,19 @@ onMounted(() => {
<td class="px-6 py-4">
<span
class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
:class="user.role === 'admin' ? 'bg-purple-50 text-purple-700 border-purple-100' : 'bg-blue-50 text-blue-700 border-blue-100'"
:class="user.role === 'admin'
? 'bg-purple-50 text-purple-700 border-purple-100'
: user.role === 'hr'
? 'bg-emerald-50 text-emerald-700 border-emerald-100'
: 'bg-blue-50 text-blue-700 border-blue-100'"
>
{{ t('admin.role.' + user.role) }}
</span>
<div v-if="user.feature_permissions?.training_hr_manage" class="mt-2">
<span class="inline-flex rounded-full border border-brand-100 bg-brand-50 px-2.5 py-0.5 text-xs font-medium text-brand-700">
{{ t('admin.user.fields.trainingHrManage') }}
</span>
</div>
</td>
<td class="px-6 py-4 text-right">
<button
@@ -39,6 +39,7 @@ const { t } = useI18n();
<select v-model="form.role" class="input-field text-sm">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="hr">{{ t('admin.role.hr') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
@@ -87,9 +87,24 @@ const { t } = useI18n();
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">{{ t('admin.user.fields.role') }}</label>
<select v-model="form.role" class="w-full border-default rounded-xl px-4 py-3 text-sm">
<option value="user">{{ t('admin.role.user') }}</option>
<option value="hr">{{ t('admin.role.hr') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="space-y-2 rounded-2xl border border-default bg-surface px-4 py-4">
<div class="text-xs font-semibold uppercase tracking-wider text-muted">{{ t('admin.user.fields.featurePermissions') }}</div>
<label class="flex items-start gap-3 rounded-xl border border-default bg-white px-4 py-3">
<input
v-model="form.feature_permissions.training_hr_manage"
type="checkbox"
class="mt-0.5 h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
<span class="space-y-1">
<span class="block text-sm font-medium text-primary">{{ t('admin.user.fields.trainingHrManage') }}</span>
<span class="block text-xs leading-5 text-muted">{{ t('admin.user.fields.trainingHrManageHint') }}</span>
</span>
</label>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-muted uppercase tracking-wider">
<span v-if="!form.id" class="text-red-500 mr-0.5">*</span>{{ t('admin.user.fields.password') }}
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/users/composables/useUsersAdmin.ts
@@ -386,6 +386,10 @@ export function useUsersAdmin() {
phone_number: user.phone_number || '',
feature_permissions: {
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
},
agent_ids: user.agent_ids || [],
};
@@ -508,6 +512,8 @@ export function useUsersAdmin() {
phone_number: editingUser.value.phone_number,
feature_permissions: editingUser.value.feature_permissions,
agent_ids: editingUser.value.agent_ids,
});
@@ -532,6 +538,8 @@ export function useUsersAdmin() {
phone_number: editingUser.value.phone_number,
feature_permissions: editingUser.value.feature_permissions,
agent_ids: editingUser.value.agent_ids,
});
@@ -37,6 +37,9 @@ export interface AdminUserRow {
real_name?: string;
employee_id?: string;
phone_number?: string;
feature_permissions?: {
training_hr_manage?: boolean;
};
agent_ids: number[];
}
@@ -3,6 +3,7 @@
*
* Agent 管理模块专用类型,供 AgentsPage 与相关 composable / 组件使用。
*/
import type { TrainingQuestionType } from '@/features/chat/training/training.types';
export interface AgentRow {
id: number;
@@ -24,6 +25,23 @@ export interface AgentSuggestedQuestionItem {
group: string;
}
export interface AgentTrainingQuestionFormItem {
id: string;
type: TrainingQuestionType;
prompt: string;
explanation: string;
options: string[];
answer: string;
}
export interface AgentGuideSummary {
id: number;
file_name: string;
file_type?: string;
guide_usage?: string;
status?: number;
}
export interface AgentTestResult {
success: boolean;
request_url: string;
@@ -58,8 +76,22 @@ export interface AgentFormState {
schedule_task_id: number | null;
poll_interval_seconds: number;
lock_input_when_running: boolean;
training_workspace_enabled: boolean;
training_pass_score: number;
training_summary_points_text: string;
training_summary_checklist_text: string;
training_question_bank: AgentTrainingQuestionFormItem[];
}
export const createEmptyTrainingQuestionForm = (): AgentTrainingQuestionFormItem => ({
id: '',
type: 'single',
prompt: '',
explanation: '',
options: ['', ''],
answer: 'a',
});
export const createEmptyAgentForm = (): AgentFormState => ({
name: '',
dify_app_id: '',
@@ -79,4 +111,9 @@ export const createEmptyAgentForm = (): AgentFormState => ({
schedule_task_id: null,
poll_interval_seconds: 2,
lock_input_when_running: true,
training_workspace_enabled: false,
training_pass_score: 90,
training_summary_points_text: '',
training_summary_checklist_text: '',
training_question_bank: [],
});
@@ -13,6 +13,9 @@ export interface UserFormState {
real_name: string;
employee_id: string;
phone_number: string;
feature_permissions: {
training_hr_manage: boolean;
};
agent_ids: number[];
}
@@ -48,6 +51,9 @@ export const createEmptyUserForm = (): UserFormState => ({
real_name: '',
employee_id: '',
phone_number: '',
feature_permissions: {
training_hr_manage: false,
},
agent_ids: [],
});
@@ -1,4 +1,4 @@
/**
/**
* features/auth/stores/auth.store.ts
* 认证全局状态;Phase 0 仍委托 utils/auth 读写 storage。
*/
@@ -19,6 +19,10 @@ export interface AuthUser {
real_name?: string;
employee_id?: string;
role?: string;
feature_permissions?: {
training_hr_manage?: boolean;
[key: string]: boolean | undefined;
};
token?: string;
access_token?: string;
refresh_token?: string;
+15 -1
View File
@@ -1,10 +1,11 @@
/**
/**
* features/chat/api/chat.api.ts
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
import type {
AssetHistorySearchResult,
ChatCrossAgentHistoryItem,
ChatMessage,
ChatQueryPreviewPage,
@@ -90,4 +91,17 @@ export const getChatQueryPreviewPage = (
return requestJson<ChatQueryPreviewPage>(`/api/chat/query-preview/${chatLogId}?${qs.toString()}`, auth());
};
export const searchAssetHistoryFiles = (
agentId: number,
query: { asset_id?: string; asset_name?: string; limit?: number },
) => {
const qs = new URLSearchParams({
agent_id: String(agentId),
});
if (query.asset_id) qs.set('asset_id', query.asset_id);
if (query.asset_name) qs.set('asset_name', query.asset_name);
if (query.limit) qs.set('limit', String(query.limit));
return requestJson<AssetHistorySearchResult>(`/api/chat/asset-history/search?${qs.toString()}`, auth());
};
export type { ChatSessionItem, ChatCrossAgentHistoryItem };
@@ -0,0 +1,91 @@
<script setup lang="ts">
/**
* features/chat/components/ChatAssetHistoryDialog.vue
* 用途:展示固定资产履历候选文件列表,并复用既有文件预览弹窗打开具体履历。
* 依赖:聊天页 useChatPage 提供的查询状态与打开预览回调。
* 逻辑:用户点击资产编号后打开;先显示检索状态,再列出共享盘匹配文件,点击单条文件进入预览。
*/
import { computed } from 'vue';
import { ExternalLink, FileText, Loader2, X } from 'lucide-vue-next';
import type { AssetHistoryFileItem } from '../types/chat.types';
const open = defineModel<boolean>('open', { required: true });
const props = defineProps<{
loading: boolean;
error: string;
assetId: string;
assetName: string;
items: AssetHistoryFileItem[];
}>();
const emit = defineEmits<{
close: [];
openPreview: [item: AssetHistoryFileItem];
}>();
const titleText = computed(() => props.assetId || props.assetName || '资产履历');
</script>
<template>
<div
v-if="open"
class="dialog-overlay z-[120] items-center"
@click.self="emit('close')"
>
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,900px)] max-w-[900px] flex-col">
<div class="dialog-header">
<div>
<h3 class="section-title">资产履历</h3>
<p class="section-desc mt-1">当前资产:{{ titleText }}</p>
</div>
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="emit('close')">
<X class="h-5 w-5" />
</button>
</div>
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
<div v-if="loading" class="flex h-56 items-center justify-center text-sm text-muted">
<Loader2 class="mr-2 h-5 w-5 animate-spin text-brand-500" />
正在检索共享盘履历文件...
</div>
<div v-else-if="error" class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
{{ error }}
</div>
<div
v-else-if="items.length === 0"
class="flex h-56 items-center justify-center rounded-2xl border border-dashed border-default bg-surface-soft text-sm text-muted"
>
未找到匹配的履历文件
</div>
<div v-else class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
<div
v-for="item in items"
:key="item.path"
class="flex items-start justify-between gap-3 border-b border-default px-4 py-4 last:border-b-0"
>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2 text-sm font-semibold text-primary">
<FileText class="h-4 w-4 shrink-0 text-brand-500" />
<span class="truncate">{{ item.name }}</span>
</div>
<div class="mt-1 break-all text-xs text-secondary">{{ item.relative_path }}</div>
<div class="mt-2 flex flex-wrap gap-3 text-xs text-muted">
<span v-if="item.modified_at">修改时间:{{ item.modified_at }}</span>
<span v-if="item.size_bytes">大小:{{ Math.max(1, Math.round(item.size_bytes / 1024)) }} KB</span>
<span v-if="item.match_reason">匹配方式:{{ item.match_reason }}</span>
</div>
</div>
<button
type="button"
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-default px-3 py-2 text-sm font-medium text-brand-600 transition hover:bg-brand-50"
@click="emit('openPreview', item)"
>
<ExternalLink class="h-4 w-4" />
查看履历
</button>
</div>
</div>
</div>
</div>
</div>
</template>
@@ -39,6 +39,7 @@ const props = defineProps<{
isUploadingAttachments: boolean;
canSendMessage: boolean;
isShippingNoticeAgent: boolean;
isMaintenanceAgent?: boolean;
shippingSuggestedPrompt: string;
shippingFocusTaskNo?: string;
shippingFocusReason?: string;
@@ -56,6 +57,8 @@ const emit = defineEmits<{
'add-remote-url': [url: string];
'shipping-inventory-selected': [event: Event];
'use-shipping-suggested-prompt': [];
'maintenance-ledger-config': [];
'maintenance-create-record': [];
'clear-shipping-focus': [];
}>();
@@ -253,6 +256,27 @@ watch(
<span>点发送开始处理</span>
</div>
<div
v-if="isMaintenanceAgent"
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
>
<button
type="button"
class="rounded-full border border-default bg-surface-soft px-3 py-1 font-medium text-secondary transition-colors hover:bg-surface-soft/70"
@click="emit('maintenance-create-record')"
>
{{ $t('maintenance.panel.recordTitle') }}
</button>
<button
type="button"
class="rounded-full border border-brand-200 bg-brand-50 px-3 py-1 font-medium text-brand-700 transition-colors hover:bg-brand-100"
@click="emit('maintenance-ledger-config')"
>
▦ {{ $t('maintenance.panel.ledgerTitle') }}
</button>
<span>{{ $t('maintenance.panel.adminOnly') }}</span>
</div>
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
<div class="flex items-center gap-3">
<button
@@ -70,6 +70,20 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|| (typeof msg.chat_log_id === 'number' ? `chat-log:${msg.chat_log_id}` : '')
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
);
/**
* 标记“当前消息后面是否还存在新的 assistant 消息”。
* 核心逻辑:培训题卡属于“最新一张 assistant 题卡”才能继续交互;
* 用户作答后虽然会追加一条 user 消息,但这不应让上一张题卡立刻失活。
*/
const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
const current = items[index];
if (!current || current.role !== 'assistant') return false;
for (let i = items.length - 1; i > index; i -= 1) {
if (items[i]?.role === 'assistant') return false;
}
return true;
};
</script>
<template>
@@ -98,6 +112,7 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
:show-chat-rating="showChatRating"
:copied-index="copiedIndex"
:is-shipping-notice-agent="isShippingNoticeAgent"
:is-latest-assistant-message="isLatestAssistantMessage(messages, index)"
:handlers="handlers"
:leave-handlers="leaveHandlers"
:shipping-handlers="shippingHandlers"
@@ -18,11 +18,29 @@ const props = defineProps<{
const emit = defineEmits<{
close: [];
'change-page': [delta: number];
'open-asset-history': [payload: { assetId: string; assetName: string }];
}>();
const totalPages = computed(() =>
Math.max(1, Math.ceil((props.state.total || 0) / (props.state.pageSize || 100))),
);
const assetIdColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产编号'));
const assetNameColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产名称'));
function normalizeCellText(cell: unknown): string {
return String(cell ?? '').trim();
}
function canOpenAssetHistory(row: unknown[], cellIndex: number): boolean {
return cellIndex === assetIdColumnIndex.value && !!normalizeCellText(row[cellIndex]);
}
function emitAssetHistory(row: unknown[]): void {
const assetId = normalizeCellText(row[assetIdColumnIndex.value]);
const assetName = assetNameColumnIndex.value >= 0 ? normalizeCellText(row[assetNameColumnIndex.value]) : '';
if (!assetId) return;
emit('open-asset-history', { assetId, assetName });
}
</script>
<template>
@@ -96,7 +114,15 @@ const totalPages = computed(() =>
:key="`query-preview-cell-${rowIndex}-${cellIndex}`"
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
>
<div class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
<button
v-if="canOpenAssetHistory(row, cellIndex)"
type="button"
class="whitespace-pre-wrap break-all text-left font-medium text-brand-600 underline-offset-2 transition hover:underline"
@click="emitAssetHistory(row)"
>
{{ cell ?? '-' }}
</button>
<div v-else class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
</td>
</tr>
</tbody>
@@ -6,7 +6,7 @@
*/
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { Loader2 } from 'lucide-vue-next';
import { Maximize2, Minimize2, Loader2 } from 'lucide-vue-next';
import ChatShell from '@/shared/layouts/ChatShell.vue';
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
@@ -16,17 +16,63 @@ import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
import ShippingBatchWorkspaceDrawer from '@/features/chat/components/ShippingBatchWorkspaceDrawer.vue';
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/composables/useTrainingWorkspace';
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
const page = useChatPageContext();
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
const isMaintenanceAgentPage = computed(() => {
const name = String(page.currentAgent?.name || '').trim();
return name === '设备维保助手' || (name.includes('设备维保') && name.includes('助手'));
});
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
const isTrainingWorkspaceExpanded = ref(false);
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
const maintenancePanelWidth = ref(560);
const isMaintenancePanelFullscreen = ref(false);
const isMaintenancePanelResizing = ref(false);
const maintenancePanelStyle = computed(() => {
if (isMaintenancePanelFullscreen.value) {
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
}
return {
width: `${maintenancePanelWidth.value}px`,
minWidth: '420px',
maxWidth: '82vw',
};
});
/**
* 开始拖拽设备维保右侧面板左边缘,允许管理员按表格内容临时调宽。
* @param event - 鼠标按下事件。
*/
const startMaintenancePanelResize = (event: MouseEvent): void => {
if (isMaintenancePanelFullscreen.value) return;
event.preventDefault();
isMaintenancePanelResizing.value = true;
const startX = event.clientX;
const startWidth = maintenancePanelWidth.value;
const handleMove = (moveEvent: MouseEvent) => {
const nextWidth = startWidth + (startX - moveEvent.clientX);
const maxWidth = Math.max(420, Math.floor(window.innerWidth * 0.82));
maintenancePanelWidth.value = Math.min(maxWidth, Math.max(420, nextWidth));
};
const stopResize = () => {
isMaintenancePanelResizing.value = false;
window.removeEventListener('mousemove', handleMove);
window.removeEventListener('mouseup', stopResize);
};
window.addEventListener('mousemove', handleMove);
window.addEventListener('mouseup', stopResize);
};
// 切换 Agent 时,重置工作区展开状态,确保每次进入都是收起状态(聊天优先)
watch(() => page.currentAgentId, () => {
isTrainingWorkspaceExpanded.value = false;
maintenancePanel.value = null;
isMaintenancePanelFullscreen.value = false;
});
</script>
@@ -100,8 +146,11 @@ watch(() => page.currentAgentId, () => {
<TrainingWorkspacePanel
:current-agent="page.currentAgent"
:current-user="page.currentUser"
:agent-guides="page.agentGuides"
:has-messages="page.messages.length > 0"
:new-session-tick="page.viewId"
:training="page.training"
@open-guide="page.openGuideModal"
@send-chat-prompt="page.handleSend($event)"
@push-local-assistant-message="page.pushLocalAssistantMessage($event)"
@update:expanded="isTrainingWorkspaceExpanded = $event"
@@ -170,6 +219,7 @@ watch(() => page.currentAgentId, () => {
:is-uploading-attachments="page.isUploadingAttachments"
:can-send-message="page.canSendMessage"
:is-shipping-notice-agent="page.isShippingNoticeAgent"
:is-maintenance-agent="isMaintenanceAgentPage"
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
:shipping-focus-task-no="page.focusedShippingTaskNo"
:shipping-focus-reason="page.shippingFocusReason"
@@ -183,10 +233,63 @@ watch(() => page.currentAgentId, () => {
@add-remote-url="page.addRemoteUrlAttachment"
@shipping-inventory-selected="page.handleShippingInventorySelected"
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
@maintenance-ledger-config="maintenancePanel = 'ledger'"
@maintenance-create-record="maintenancePanel = 'record'"
@clear-shipping-focus="page.clearShippingFocus"
/>
</div>
<aside
v-if="isMaintenanceAgentPage && maintenancePanel"
class="relative flex flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.06)]"
:class="[
isMaintenancePanelFullscreen ? 'absolute inset-y-0 right-0 z-30' : '',
isMaintenancePanelResizing ? 'select-none' : '',
]"
:style="maintenancePanelStyle"
>
<button
v-if="!isMaintenancePanelFullscreen"
type="button"
class="absolute inset-y-0 left-[-4px] z-10 w-2 cursor-col-resize bg-transparent hover:bg-brand-200/60"
:title="$t('maintenance.panel.resizeTitle')"
@mousedown="startMaintenancePanelResize"
/>
<div class="flex items-start justify-between gap-3 border-b border-default px-4 py-3">
<div>
<h2 class="text-base font-semibold text-primary">
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerTitle') : $t('maintenance.panel.recordTitle') }}
</h2>
<p class="mt-1 text-xs text-secondary">
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerSubtitle') : $t('maintenance.panel.recordSubtitle') }}
</p>
</div>
<div class="flex items-center gap-2">
<button
type="button"
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-secondary hover:bg-surface-soft"
:title="isMaintenancePanelFullscreen ? $t('maintenance.panel.exitFullscreen') : $t('maintenance.panel.fullscreen')"
@click="isMaintenancePanelFullscreen = !isMaintenancePanelFullscreen"
>
<Minimize2 v-if="isMaintenancePanelFullscreen" class="h-4 w-4" />
<Maximize2 v-else class="h-4 w-4" />
</button>
<button
type="button"
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-sm text-secondary hover:bg-surface-soft"
:title="$t('maintenance.panel.close')"
@click="maintenancePanel = null"
>
×
</button>
</div>
</div>
<div class="min-h-0 flex-1 overflow-auto p-4">
<LedgerConfigPanel v-if="maintenancePanel === 'ledger'" />
<MaintenanceRecordManagerPanel v-else />
</div>
</aside>
<ChatBrowserPanel
v-model:open="page.browserPanelOpen"
v-model:draft-url="page.browserDraftUrl"
@@ -1,6 +1,6 @@
/**
/**
* features/chat/components/ChatViewOverlays.vue
* 对话页全局弹窗:文件预览、反馈、查询预览、请假 OA、删除确认、学习之窗。
* 对话页全局弹窗与浮层:文件预览、反馈、查询预览、履历检索提示、请假 OA、删除确认、学习之窗。
*/
<script setup lang="ts">
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
@@ -10,6 +10,7 @@ import ChatQueryPreviewDialog from '@/features/chat/components/ChatQueryPreviewD
import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialog.vue';
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
import { Loader2 } from 'lucide-vue-next';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { getAuthHeaders } from '@/shared/utils/auth';
@@ -45,7 +46,17 @@ function onFeedbackSubmitted() {
:state="page.queryPreviewState"
@close="page.queryPreview.close"
@change-page="page.queryPreview.changePage"
@open-asset-history="({ assetId, assetName }) => page.assetHistory.openHistory(assetId, assetName)"
/>
<div
v-if="page.assetHistory.loading"
class="pointer-events-none fixed inset-x-0 top-20 z-[145] flex justify-center px-4"
>
<div class="flex items-center gap-2 rounded-full border border-brand-200 bg-white/95 px-4 py-2 text-sm text-brand-700 shadow-lg backdrop-blur">
<Loader2 class="h-4 w-4 animate-spin text-brand-500" />
<span>正在搜索该资产的履历资料,请耐心等待...</span>
</div>
</div>
<ChatLeaveAgentDialog
v-model:open="page.showLeaveAgentDialog"
v-model:keyword="page.leaveAgentKeyword"
@@ -8,7 +8,6 @@
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
import { useI18n } from 'vue-i18n';
import {
BarChart3,
BookOpen,
CheckCircle2,
ChevronDown,
@@ -17,24 +16,26 @@ import {
Download,
PlayCircle,
RefreshCcw,
Send,
ShieldCheck,
Target,
Users,
XCircle,
} from 'lucide-vue-next';
import { useTrainingWorkspace } from '@/features/chat/composables/useTrainingWorkspace';
import { resolveTrainingExamPdfGuide, type TrainingGuideLike } from '@/features/chat/training/trainingWorkspace.utils';
const props = defineProps<{
currentAgent: Record<string, unknown> | null;
currentUser: Record<string, unknown> | null;
agentGuides: TrainingGuideLike[];
hasMessages: boolean;
newSessionTick: number;
training: ShallowUnwrapRef<ReturnType<typeof useTrainingWorkspace>>;
}>();
const emit = defineEmits<{
'send-chat-prompt': [prompt: string];
'push-local-assistant-message': [content: string];
'open-guide': [guideId?: number];
'update:expanded': [expanded: boolean];
}>();
@@ -94,23 +95,25 @@ const setWorkspaceExpanded = (expanded: boolean, manual = false) => {
}
};
const sendPrompt = (prompt: string) => {
setWorkspaceExpanded(false);
emit('send-chat-prompt', prompt);
};
const currentAnswerLabel = computed(() => {
const question = workspace.currentQuestion;
if (!question) return '';
return question.options?.find((item) => item.id === workspace.selectedOptionId)?.label || '';
});
const trainingExamPdfGuide = computed(() => resolveTrainingExamPdfGuide(props.agentGuides));
// 默认进入 Chat 聊天页面(即收起工作区状态)
const workspaceExpanded = ref(false);
const autoSyncInitialPrompt = () => {
if (workspace.isTrainingAgent && workspace.isHydrated && !props.hasMessages) {
emit('push-local-assistant-message', workspace.learnerChatPrompt);
if (
workspace.isTrainingAgent
&& workspace.isHydrated
&& !props.hasMessages
&& workspace.shouldShowNewSessionReminder
) {
emit('push-local-assistant-message', workspace.newSessionReminderMessage);
}
};
@@ -142,6 +145,14 @@ watch(
},
);
watch(
() => props.newSessionTick,
(tick, prevTick) => {
if (!tick || tick === prevTick) return;
autoSyncInitialPrompt();
},
);
const isCompactMode = computed(() => !workspaceExpanded.value);
const compactSummary = computed(() => {
@@ -158,6 +169,14 @@ const compactSummary = computed(() => {
}
return workspace.isPassed ? t('chat.training.result.passTitle') : t('chat.training.result.failTitle');
});
const trainingTitle = computed(() => String(t('chat.training.title') || '').trim());
const ruleItems = computed(() => ([
t('chat.training.rules.rule1', { total: workspace.totalQuestionCount }),
t('chat.training.rules.rule2'),
t('chat.training.rules.rule3', { passScore: workspace.passScore }),
t('chat.training.rules.rule4'),
]));
</script>
<template>
@@ -177,8 +196,8 @@ const compactSummary = computed(() => {
<BookOpen class="h-3.5 w-3.5" />
{{ $t('chat.training.badge') }}
</div>
<div class="text-sm font-semibold text-primary md:text-base">
{{ $t('chat.training.title') }}
<div v-if="trainingTitle" class="text-sm font-semibold text-primary md:text-base">
{{ trainingTitle }}
</div>
</div>
<div class="mt-1.5 flex flex-wrap gap-2">
@@ -203,6 +222,15 @@ const compactSummary = computed(() => {
</div>
<div class="flex flex-wrap items-center justify-end gap-2">
<button
v-if="trainingExamPdfGuide"
type="button"
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
>
<BookOpen class="h-4 w-4 shrink-0" />
<span class="leading-none">{{ $t('chat.training.actions.viewExamPdf') }}</span>
</button>
<button
v-if="workspace.stage === 'video'"
type="button"
@@ -212,23 +240,6 @@ const compactSummary = computed(() => {
<PlayCircle class="h-4 w-4" />
{{ $t('chat.training.steps.video') }}
</button>
<button
type="button"
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-xs font-medium text-secondary transition hover:bg-surface-soft"
@click="sendPrompt(workspace.learnerChatPrompt)"
>
<Send class="h-4 w-4" />
{{ $t('chat.training.actions.syncLearnerToChat') }}
</button>
<button
v-if="workspace.isAdminViewer"
type="button"
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
@click="sendPrompt(workspace.managementChatPrompt)"
>
<BarChart3 class="h-4 w-4" />
{{ $t('chat.training.actions.syncHrToChat') }}
</button>
<button
type="button"
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
@@ -276,8 +287,8 @@ const compactSummary = computed(() => {
<BookOpen class="h-3.5 w-3.5" />
{{ $t('chat.training.badge') }}
</div>
<div class="text-sm font-semibold text-primary md:text-base">
{{ $t('chat.training.title') }}
<div v-if="trainingTitle" class="text-sm font-semibold text-primary md:text-base">
{{ trainingTitle }}
</div>
</div>
@@ -304,21 +315,13 @@ const compactSummary = computed(() => {
<div class="flex flex-wrap items-center justify-end gap-2">
<button
v-if="trainingExamPdfGuide"
type="button"
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-xs font-medium text-secondary transition hover:bg-surface-soft"
@click="sendPrompt(workspace.learnerChatPrompt)"
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
>
<Send class="h-4 w-4" />
{{ $t('chat.training.actions.syncLearnerToChat') }}
</button>
<button
v-if="workspace.isAdminViewer"
type="button"
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
@click="sendPrompt(workspace.managementChatPrompt)"
>
<BarChart3 class="h-4 w-4" />
{{ $t('chat.training.actions.syncHrToChat') }}
<BookOpen class="h-4 w-4 shrink-0" />
<span class="leading-none">{{ $t('chat.training.actions.viewExamPdf') }}</span>
</button>
<button
type="button"
@@ -409,6 +412,15 @@ const compactSummary = computed(() => {
<h3 class="text-base font-semibold text-primary md:text-lg">{{ $t('chat.training.video.title') }}</h3>
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.video.description') }}</p>
</div>
<button
v-if="trainingExamPdfGuide"
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
>
<BookOpen class="h-4 w-4" />
{{ $t('chat.training.actions.viewExamPdf') }}
</button>
</div>
<div class="mt-3 relative group cursor-pointer overflow-hidden rounded-2xl border border-default bg-slate-900 shadow-lg aspect-video flex items-center justify-center" @click="showVideoModal = true">
<img src="https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=Professional%20corporate%20training%20video%20cover%2C%20high-quality%2C%20modern%20office%20background%2C%20play%20button%20overlay&image_size=landscape_16_9" class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:scale-105 transition-transform duration-500" />
@@ -427,14 +439,25 @@ const compactSummary = computed(() => {
<h3 class="text-base font-semibold text-primary md:text-lg">{{ $t('chat.training.summary.title') }}</h3>
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.summary.description') }}</p>
</div>
<button
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
@click="workspace.startExam"
>
<Target class="h-4 w-4" />
{{ $t('chat.training.summary.startExam') }}
</button>
<div class="flex flex-wrap gap-2">
<button
v-if="trainingExamPdfGuide"
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
>
<BookOpen class="h-4 w-4" />
{{ $t('chat.training.actions.viewExamPdf') }}
</button>
<button
type="button"
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
@click="workspace.startExam"
>
<Target class="h-4 w-4" />
{{ $t('chat.training.summary.startExam') }}
</button>
</div>
</div>
<div class="mt-3 grid gap-3 md:grid-cols-2">
@@ -475,7 +498,7 @@ const compactSummary = computed(() => {
{{ $t('chat.training.exam.currentScore', { score: workspace.score }) }}
</div>
<div class="rounded-xl bg-surface-soft px-3 py-1.5">
{{ $t('chat.training.exam.passLine') }}
{{ $t('chat.training.exam.passLine', { passScore: workspace.passScore }) }}
</div>
</div>
</div>
@@ -565,7 +588,7 @@ const compactSummary = computed(() => {
{{ workspace.isPassed ? $t('chat.training.result.passTitle') : $t('chat.training.result.failTitle') }}
</h3>
<p class="mt-2 text-sm leading-6 text-secondary">
{{ workspace.isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription') }}
{{ workspace.isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription', { passScore: workspace.passScore }) }}
</p>
</div>
@@ -606,14 +629,6 @@ const compactSummary = computed(() => {
<RefreshCcw class="h-4 w-4" />
{{ $t('chat.training.result.retryExam') }}
</button>
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
@click="sendPrompt(workspace.learnerChatPrompt)"
>
<Send class="h-4 w-4" />
{{ $t('chat.training.result.sendToChat') }}
</button>
</div>
</div>
</div>
@@ -643,21 +658,9 @@ const compactSummary = computed(() => {
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.rules.title') }}</div>
<ul class="mt-2 grid gap-1 text-xs leading-5 text-secondary">
<li class="flex gap-2">
<li v-for="rule in ruleItems" :key="rule" class="flex gap-2">
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
<span>{{ $t('chat.training.rules.rule1') }}</span>
</li>
<li class="flex gap-2">
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
<span>{{ $t('chat.training.rules.rule2') }}</span>
</li>
<li class="flex gap-2">
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
<span>{{ $t('chat.training.rules.rule3') }}</span>
</li>
<li class="flex gap-2">
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
<span>{{ $t('chat.training.rules.rule4') }}</span>
<span>{{ rule }}</span>
</li>
</ul>
</div>
@@ -667,32 +670,41 @@ const compactSummary = computed(() => {
<div v-else-if="!isCompactMode" class="space-y-4 p-4 md:p-5">
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.total') }}</div>
<div class="mt-1.5 text-xl font-semibold text-primary">{{ workspace.stats.total }}</div>
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.total') }}</div>
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.total }}</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.passed') }}</div>
<div class="mt-1.5 text-xl font-semibold text-emerald-600">{{ workspace.stats.passed }}</div>
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passed') }}</div>
<div class="text-2xl font-semibold text-emerald-600">{{ workspace.stats.passed }}</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.failed') }}</div>
<div class="mt-1.5 text-xl font-semibold text-amber-600">{{ workspace.stats.failed }}</div>
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.failed') }}</div>
<div class="text-2xl font-semibold text-amber-600">{{ workspace.stats.failed }}</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.inProgress') }}</div>
<div class="mt-1.5 text-xl font-semibold text-blue-600">{{ workspace.stats.inProgress }}</div>
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.inProgress') }}</div>
<div class="text-2xl font-semibold text-blue-600">{{ workspace.stats.inProgress }}</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.passRate') }}</div>
<div class="mt-1.5 text-xl font-semibold text-primary">{{ workspace.stats.passRate }}%</div>
<div class="flex items-center justify-center gap-2 text-center">
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passRate') }}</div>
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.passRate }}%</div>
</div>
</div>
</div>
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3">
<div class="grid gap-3 xl:grid-cols-3">
<label class="space-y-1.5">
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.keywordLabel') }}</span>
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
<label>
<input
v-model="workspace.hrKeyword"
type="text"
@@ -700,8 +712,7 @@ const compactSummary = computed(() => {
:placeholder="$t('chat.training.hr.filters.keywordPlaceholder')"
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.statusLabel') }}</span>
<label>
<select
v-model="workspace.hrStatusFilter"
class="w-full rounded-xl border border-default bg-surface px-3 py-2.5 text-sm text-primary outline-none transition focus:border-brand-300"
@@ -712,8 +723,7 @@ const compactSummary = computed(() => {
<option value="in_progress">{{ $t('chat.training.hr.status.in_progress') }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.departmentLabel') }}</span>
<label>
<select
v-model="workspace.hrDepartmentFilter"
class="w-full rounded-xl border border-default bg-surface px-3 py-2.5 text-sm text-primary outline-none transition focus:border-brand-300"
@@ -724,17 +734,7 @@ const compactSummary = computed(() => {
</option>
</select>
</label>
</div>
<div class="flex flex-wrap items-center justify-end gap-2">
<button
type="button"
class="inline-flex h-10 items-center gap-2 rounded-xl border border-default bg-white px-4 text-xs font-medium text-secondary transition hover:bg-surface-soft sm:text-sm"
@click="sendPrompt(workspace.managementChatPrompt)"
>
<Send class="h-4 w-4" />
{{ $t('chat.training.hr.actions.askAgent') }}
</button>
<div class="flex justify-center xl:justify-end">
<button
type="button"
class="inline-flex h-10 items-center gap-2 rounded-xl bg-brand-600 px-4 text-xs font-medium text-white transition hover:bg-brand-700 sm:text-sm"
@@ -743,6 +743,7 @@ const compactSummary = computed(() => {
<Download class="h-4 w-4" />
{{ $t('chat.training.hr.actions.export') }}
</button>
</div>
</div>
</div>
@@ -8,6 +8,7 @@
import { computed, ref, watch } from 'vue';
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
@@ -21,6 +22,7 @@ import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload }
export interface ChatMessageBubbleHandlers {
renderMarkdown: (text: string) => string;
onMarkdownClick: (event: MouseEvent) => void;
openAssetHistory: (assetId: string, assetName?: string) => void;
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
downloadInlineFile: (file: InlineDownloadFile) => void;
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
@@ -47,6 +49,7 @@ const {
showChatRating,
copiedIndex,
isShippingNoticeAgent,
isLatestAssistantMessage,
handlers,
leaveHandlers,
shippingHandlers,
@@ -58,6 +61,7 @@ const {
showChatRating: boolean;
copiedIndex: number | null;
isShippingNoticeAgent: boolean;
isLatestAssistantMessage: boolean;
handlers: ChatMessageBubbleHandlers;
leaveHandlers: LeaveMessageHandlers;
shippingHandlers: ShippingMappingHandlers;
@@ -91,20 +95,35 @@ const isTrainingVideoMessage = computed(() => {
if (message.role !== 'assistant') return false;
// 只要包含特定引导文案,就显示视频占位符,不限于最后一条消息
const content = message.content || '';
return content.includes('专属入职培训助手') || (content.includes('看视频') && content.includes('已看完'));
return content.includes('专属入职培训助手')
|| content.includes('onboarding training assistant')
|| content.includes('ผู้ช่วยอบรมพนักงานใหม่')
|| content.includes('入职培训视频')
|| content.includes('training video');
});
const isTrainingSummaryMessage = computed(() => {
if (message.role !== 'assistant') return false;
const content = message.content || '';
return content.includes('完成视频学习') || content.includes('复盘重点知识') || content.includes('复盘知识点') || content.includes('总结重点知识');
return content.includes('完成视频学习')
|| content.includes('复盘重点知识')
|| content.includes('复盘知识点')
|| content.includes('总结重点知识')
|| content.includes('核心知识点')
|| content.includes('key knowledge points')
|| content.includes('ประเด็นสำคัญ');
});
const isTrainingResultMessage = computed(() => {
if (message.role !== 'assistant') return false;
// 只要是结果文案,就显示结算卡片,不限于最后一条消息
const content = message.content || '';
return content.includes('考试结束') || content.includes('顺利通过新人考核');
return content.includes('考试结束')
|| content.includes('顺利通过新人考核')
|| content.includes('Exam finished')
|| content.includes('passed the onboarding assessment')
|| content.includes('สอบเสร็จแล้ว')
|| content.includes('ผ่านการประเมินพนักงานใหม่');
});
const retrieverResources = computed(() => handlers.getDisplayRetrieverResources(message));
@@ -123,7 +142,7 @@ const showShippingActionsPanel = computed(() =>
&& !!message.shipping_actions?.length
&& message.type !== 'shipping-match-result',
);
const isLastMessage = computed(() => index === messageCount - 1);
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
const isCopied = computed(() => copiedIndex === index);
const renderedMarkdown = computed(() => (
message.role === 'assistant' ? handlers.renderMarkdown(message.content) : ''
@@ -431,10 +450,11 @@ const inlineDialogPage = ref(1);
const activeInlineFilterIndexes = computed(() => {
const table = activeInlineDialogEntry.value?.table;
if (!table) {
return { assetId: -1, custodianPerson: -1, custodianDept: -1 };
return { assetId: -1, assetName: -1, custodianPerson: -1, custodianDept: -1 };
}
return {
assetId: findInlineTableHeaderIndex(table.rawHeaders, ['asset_id', 'asset_no']),
assetName: findInlineTableHeaderIndex(table.rawHeaders, ['asset_name']),
custodianPerson: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_person', 'custodian_name']),
custodianDept: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_dept', 'department_name']),
};
@@ -521,6 +541,19 @@ function changeInlineDialogPage(nextPage: number): void {
inlineDialogPage.value = Math.min(Math.max(1, nextPage), activeInlineTotalPages.value);
}
function canOpenInlineAssetHistory(cellIndex: number, cellValue: string): boolean {
const normalizedValue = String(cellValue || '').trim();
return cellIndex === activeInlineFilterIndexes.value.assetId && !!normalizedValue && normalizedValue !== '-';
}
function openInlineAssetHistory(row: string[]): void {
const indexes = activeInlineFilterIndexes.value;
const assetId = indexes.assetId >= 0 ? String(row[indexes.assetId] || '').trim() : '';
const assetName = indexes.assetName >= 0 ? String(row[indexes.assetName] || '').trim() : '';
if (!assetId || assetId === '-') return;
handlers.openAssetHistory(assetId, assetName === '-' ? '' : assetName);
}
/**
* 响应聊天消息里的内嵌文件下载按钮点击。
* 核心逻辑:复用页面层 handlers 生成 Blob 下载,组件层只负责把当前文件对象回传出去。
@@ -588,25 +621,32 @@ function handleInlineDownload(file: InlineDownloadFile): void {
:action-button-class="handlers.shippingActionButtonClass"
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
/>
<MaintenanceDeviceResultCard
v-else-if="message.type === 'maintenance-device-result'"
:message="message"
/>
<TrainingExamQuestionMessage
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
:question="trainingHandlers.getQuestion()!"
:current-question-index="trainingHandlers.getCurrentQuestionIndex()"
:answered-count="trainingHandlers.getAnsweredCount()"
:total-count="trainingHandlers.getTotalCount()"
:pass-score="trainingHandlers.getPassScore()"
:score="trainingHandlers.getScore()"
:selected-option-id="trainingHandlers.getSelectedOptionId()"
:answer-locked="trainingHandlers.getAnswerLocked()"
:feedback-correct="trainingHandlers.getFeedbackCorrect()"
:answer-label="trainingHandlers.getAnswerLabel()"
:latest-exam-feedback="trainingHandlers.getLatestExamFeedback()"
:is-thinking="isThinking"
@select="trainingHandlers.onSelect"
@next="trainingHandlers.onNext"
/>
<TrainingResultCard
v-else-if="isTrainingResultMessage"
:score="trainingHandlers.getScore()"
:is-passed="trainingHandlers.getScore() >= 90"
:score="trainingHandlers.getResultScore()"
:is-passed="trainingHandlers.getResultPassed()"
:pass-score="trainingHandlers.getPassScore()"
:correct-count="trainingHandlers.getCorrectCount()"
:wrong-count="trainingHandlers.getWrongCount()"
:is-thinking="isThinking"
@@ -617,6 +657,7 @@ function handleInlineDownload(file: InlineDownloadFile): void {
v-else-if="renderedMarkdown"
ref="markdownContainer"
class="markdown-body chat-markdown min-w-0 break-words text-sm leading-relaxed"
@click="handlers.onMarkdownClick"
v-html="renderedMarkdown"
/>
@@ -885,7 +926,15 @@ function handleInlineDownload(file: InlineDownloadFile): void {
:key="`${activeInlineDialogEntry.file.name}-dialog-cell-${rowIndex}-${cellIndex}`"
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
>
<div class="whitespace-pre-wrap break-all">{{ cell || '-' }}</div>
<button
v-if="canOpenInlineAssetHistory(cellIndex, cell)"
type="button"
class="whitespace-pre-wrap break-all text-left font-medium text-brand-600 underline-offset-2 transition hover:underline"
@click="openInlineAssetHistory(row)"
>
{{ cell || '-' }}
</button>
<div v-else class="whitespace-pre-wrap break-all">{{ cell || '-' }}</div>
</td>
</tr>
</tbody>
@@ -0,0 +1,122 @@
/**
* features/chat/components/messages/MaintenanceDeviceResultCard.vue
* 用途:设备维保助手会话中的设备台账查询结果卡片。
* 依赖:chat.types、ledger/record 类型、vue-i18n。
* 逻辑:后端返回 maintenance-device-result payload 后,本组件按原型展示设备基础信息、匹配状态和快捷操作。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ChatMessage } from '../../types/chat.types';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
interface MaintenanceDeviceResultPayload {
matched?: boolean;
device?: MaintenanceDevice;
records?: MaintenanceRecord[];
actions?: Array<{ id: string; label: string }>;
}
const props = defineProps<{
message: ChatMessage;
}>();
const { t } = useI18n();
const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
const raw = props.message.payload;
if (!raw || typeof raw !== 'object') return null;
return raw as MaintenanceDeviceResultPayload;
});
const device = computed(() => payload.value?.device || null);
const records = computed(() => payload.value?.records || []);
const statusLabel = computed(() => {
const status = device.value?.deviceStatus;
if (status === 'in_use') return t('maintenance.ledger.status.inUse');
if (status === 'disabled') return t('maintenance.ledger.status.disabled');
if (status === 'scrapped') return t('maintenance.ledger.status.scrapped');
if (status === 'sold') return t('maintenance.ledger.status.sold');
return status || '-';
});
const rows = computed(() => {
const item = device.value;
if (!item) return [];
return [
[
{ label: t('maintenance.ledger.fields.deviceCode'), value: item.deviceCode },
{ label: t('maintenance.ledger.fields.deviceName'), value: item.deviceName },
],
[
{ label: t('maintenance.ledger.fields.modelSpec'), value: item.modelSpec },
{ label: t('maintenance.ledger.fields.department'), value: item.department },
],
[
{ label: t('maintenance.ledger.fields.devicePosition'), value: item.installLocation },
{ label: t('maintenance.ledger.fields.deviceStatus'), value: statusLabel.value },
],
[
{ label: t('maintenance.ledger.fields.manufacturer'), value: item.manufacturer },
{ label: t('maintenance.ledger.fields.startDate'), value: item.startDate },
],
];
});
</script>
<template>
<section v-if="device" class="mt-3 rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-800 shadow-sm">
<div class="flex items-center justify-between gap-3 rounded-t-lg border border-slate-200 bg-slate-50 px-3 py-2">
<h3 class="font-semibold">{{ t('maintenance.chat.deviceLedgerInfo') }}</h3>
<span class="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-semibold text-emerald-700">
{{ t('maintenance.chat.matched') }}
</span>
</div>
<div class="overflow-hidden border-x border-b border-slate-200">
<table class="w-full table-fixed text-sm">
<tbody>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex" class="border-t border-slate-200 first:border-t-0">
<template v-for="cell in row" :key="cell.label">
<th class="w-[16%] bg-slate-100 px-3 py-2 text-left font-semibold text-slate-700">{{ cell.label }}</th>
<td class="w-[34%] px-3 py-2 text-slate-800">{{ cell.value || '-' }}</td>
</template>
</tr>
</tbody>
</table>
</div>
<div v-if="records.length" class="mt-3 overflow-hidden rounded-lg border border-slate-200">
<div class="bg-slate-50 px-3 py-2 text-xs font-semibold text-slate-600">
{{ t('maintenance.chat.recentRecords', { count: records.length }) }}
</div>
<table class="w-full text-left text-xs">
<thead class="bg-slate-50 text-slate-500">
<tr>
<th class="px-3 py-2">{{ t('maintenance.record.fields.reportDate') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.fields.faultDescription') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairer') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="record in records.slice(0, 3)" :key="record.id" class="border-t border-slate-200">
<td class="px-3 py-2">{{ record.reportDate || '-' }}</td>
<td class="max-w-[260px] truncate px-3 py-2">{{ record.faultDescription || '-' }}</td>
<td class="px-3 py-2">{{ record.repairer || '-' }}</td>
</tr>
</tbody>
</table>
</div>
<div class="mt-3 flex flex-wrap gap-2">
<button type="button" class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white">
{{ t('maintenance.chat.viewRepairHistory') }}
</button>
<button type="button" class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700">
{{ t('maintenance.chat.addRepairRecord') }}
</button>
</div>
</section>
</template>
@@ -5,23 +5,27 @@
*/
<script setup lang="ts">
import { CheckCircle2, XCircle, ClipboardCheck } from 'lucide-vue-next';
import type { TrainingQuestion } from '@/features/chat/training/training.types';
import type { TrainingExamTransitionFeedback, TrainingQuestion } from '@/features/chat/training/training.types';
export interface TrainingHandlers {
getQuestion: () => TrainingQuestion | null;
getCurrentQuestionIndex: () => number;
getAnsweredCount: () => number;
getTotalCount: () => number;
getPassScore: () => number;
getScore: () => number;
getSelectedOptionId: () => string;
getAnswerLocked: () => boolean;
getFeedbackCorrect: () => boolean;
getAnswerLabel: () => string;
getLatestExamFeedback: () => TrainingExamTransitionFeedback | null;
onSelect: (optionId: string) => void;
onNext: () => void;
onPlayVideo: () => void;
onStartExam: () => void;
onRestartExam: () => void;
getResultScore: () => number;
getResultPassed: () => boolean;
getCorrectCount: () => number;
getWrongCount: () => number;
getSummaryPoints: () => string[];
@@ -33,11 +37,13 @@ const props = defineProps<{
currentQuestionIndex: number;
answeredCount: number;
totalCount: number;
passScore: number;
score: number;
selectedOptionId: string;
answerLocked: boolean;
feedbackCorrect: boolean;
answerLabel: string;
latestExamFeedback: TrainingExamTransitionFeedback | null;
isThinking: boolean;
}>();
@@ -46,7 +52,6 @@ const emit = defineEmits<{
next: [];
}>();
const passLine = 90;
</script>
<template>
@@ -68,7 +73,42 @@ const passLine = 90;
</div>
<div class="rounded-lg bg-slate-50 px-3 py-1.5 font-medium text-slate-600 border border-slate-100 flex items-center gap-2">
<span>及格线:</span>
<span class="text-slate-800 font-bold">{{ passLine }} 分</span>
<span class="text-slate-800 font-bold">{{ passScore }} 分</span>
</div>
</div>
</div>
<!-- 上一题反馈摘要:自动推进到下一题后,仍需把对错、解析和分数留在同一张题卡顶部 -->
<div
v-if="latestExamFeedback"
class="rounded-2xl border p-4"
:class="latestExamFeedback.correct ? 'border-emerald-100 bg-emerald-50/60' : 'border-red-100 bg-red-50/60'"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-2 text-sm font-bold" :class="latestExamFeedback.correct ? 'text-emerald-700' : 'text-red-700'">
<CheckCircle2 v-if="latestExamFeedback.correct" class="h-4 w-4" />
<XCircle v-else class="h-4 w-4" />
{{ latestExamFeedback.correct ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
</div>
<div class="rounded-lg bg-white/70 px-3 py-1 text-xs font-semibold text-slate-600">
{{ $t('chat.training.exam.currentScore', { score: latestExamFeedback.scoreAfterAnswer }) }}
</div>
</div>
<div class="mt-3 space-y-2 text-[13px] leading-6 text-slate-600">
<div class="text-slate-500">{{ latestExamFeedback.questionPrompt }}</div>
<div class="flex gap-2">
<span class="font-medium" :class="latestExamFeedback.correct ? 'text-emerald-600' : 'text-red-600'">
{{ $t('chat.training.exam.selectedAnswer', { answer: latestExamFeedback.selectedAnswerLabel || '--' }) }}
</span>
</div>
<div v-if="!latestExamFeedback.correct" class="flex gap-2">
<span class="text-emerald-600 font-medium">
{{ $t('chat.training.exam.correctAnswer', { answer: latestExamFeedback.correctAnswerLabel || '--' }) }}
</span>
</div>
<div class="pl-2 border-l-2 border-slate-200/60 text-slate-500/90">
{{ latestExamFeedback.explanation }}
</div>
</div>
</div>
@@ -8,6 +8,7 @@ import { ShieldCheck, XCircle, RotateCcw, CheckCircle2 } from 'lucide-vue-next';
defineProps<{
score: number;
isPassed: boolean;
passScore: number;
correctCount: number;
wrongCount: number;
isThinking: boolean;
@@ -65,7 +66,7 @@ const emit = defineEmits<{
<!-- 描述语 -->
<div class="text-sm leading-relaxed text-slate-600">
{{ isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription') }}
{{ isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription', { passScore }) }}
</div>
<!-- 操作 -->
@@ -650,6 +650,7 @@ export function useChat() {
messages,
isThinking,
conversationId,
viewId,
runs,
activeRunId,
activateRun,
@@ -0,0 +1,106 @@
/**
* features/chat/composables/useChatAssetHistory.ts
* 用途:管理固定资产履历检索、友好提示与文件预览跳转。
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
* 逻辑:页面层统一持有“打开履历”动作,消息气泡/查询预览弹窗复用该入口;
* 点击资产编号后先进入“检索中”状态,命中履历文件则直接打开最佳候选预览,未命中时仅提示用户。
*/
import { ref } from 'vue';
import { searchAssetHistoryFiles } from '../api/chat.api';
import type { AssetHistoryFileItem, SourceFileLink } from '../types/chat.types';
import type { ComputedRef } from 'vue';
interface UseChatAssetHistoryOptions {
agentId: ComputedRef<number>;
openPreview: (file: SourceFileLink) => Promise<void>;
warn: (message: string) => void;
}
export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
const open = ref(false);
const loading = ref(false);
const error = ref('');
const assetId = ref('');
const assetName = ref('');
const items = ref<AssetHistoryFileItem[]>([]);
const close = () => {
open.value = false;
loading.value = false;
error.value = '';
items.value = [];
};
/**
* 检索资产履历并直接打开最佳预览结果。
* AI 触发时机:当用户点击聊天表格中的“资产编号”,希望直接查看该资产履历时调用。
* 核心逻辑:点击后先切入“检索中”状态,再按“资产编号 + 资产名称”查询共享盘候选文件,命中后默认取排序最优的第一条直接预览;
* 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表。
* 参数约束:至少要提供资产编号或资产名称之一;候选文件排序由后端负责,本方法默认信任第一条结果。
*/
const openHistory = async (nextAssetId: string, nextAssetName = '') => {
const normalizedAssetId = String(nextAssetId || '').trim();
const normalizedAssetName = String(nextAssetName || '').trim();
if (loading.value) {
return;
}
if (!normalizedAssetId && !normalizedAssetName) {
options.warn('当前资产缺少可用于检索履历的编号或名称');
return;
}
assetId.value = normalizedAssetId;
assetName.value = normalizedAssetName;
open.value = false;
loading.value = true;
error.value = '';
items.value = [];
try {
const result = await searchAssetHistoryFiles(options.agentId.value, {
asset_id: normalizedAssetId,
asset_name: normalizedAssetName,
});
items.value = Array.isArray(result?.items) ? result.items : [];
const bestMatch = items.value[0];
if (!bestMatch) {
const displayName = normalizedAssetId || normalizedAssetName;
options.warn(`未找到资产 ${displayName} 的履历文件,如确认应有履历,请联系管理员补充。`);
return;
}
await openHistoryFilePreview(bestMatch);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '检索资产履历失败';
error.value = message;
options.warn(`履历查询失败:${message}`);
} finally {
loading.value = false;
}
};
/**
* 打开履历文件预览。
* AI 触发时机:当用户在“资产履历”列表里点击某一条“查看履历”时调用。
* 核心逻辑:先关闭履历候选列表弹窗,避免与文件预览弹窗叠层冲突,再交给聊天页通用预览器处理。
* 参数约束:必须传入带有 name/url 的有效履历文件项,url 必须是后端允许代理的共享盘路径。
*/
const openHistoryFilePreview = async (item: AssetHistoryFileItem) => {
close();
await options.openPreview({
name: item.name,
url: item.url,
actualExt: item.actual_ext,
});
};
return {
open,
loading,
error,
assetId,
assetName,
items,
close,
openHistory,
openHistoryFilePreview,
};
}
@@ -9,6 +9,7 @@ export interface AgentGuide {
id: number;
file_name: string;
file_type?: string;
guide_usage?: string;
file_url?: string;
file_path?: string;
remark?: string;
@@ -42,8 +43,9 @@ export function useChatGuides(options: UseChatGuidesOptions) {
guides.value = [];
};
const openModal = () => {
const first = guides.value[0];
const openModal = (guideId?: number | null) => {
const preferred = guideId ? guides.value.find((g) => g.id === guideId) : null;
const first = preferred || guides.value[0];
if (!first) return;
activeGuideId.value = first.id;
showModal.value = true;
@@ -25,8 +25,10 @@ import { useChatScroll } from './useChatScroll';
import { useChatSessions } from './useChatSessions';
import { useChatShipping } from './useChatShipping';
import { useChatSourceFiles } from './useChatSourceFiles';
import { useChatAssetHistory } from './useChatAssetHistory';
import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace, matchesTrainingAgent } from './useTrainingWorkspace';
import { useTrainingWorkspace } from './useTrainingWorkspace';
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
import {
createChatPageConversationApi,
@@ -106,6 +108,7 @@ export function useChatPage() {
messages,
isThinking,
conversationId,
viewId,
runs,
activeRunId,
activateRun,
@@ -164,6 +167,11 @@ export function useChatPage() {
openPreview,
parsePlmPreviewLink,
} = sourceFiles;
const assetHistory = useChatAssetHistory({
agentId: currentAgentId,
openPreview,
warn: (text) => msg.warning(text),
});
watch(currentAgentId, (id) => {
chatStore.setCurrentAgentId(id > 0 ? id : null);
@@ -342,6 +350,7 @@ export function useChatPage() {
const training = useTrainingWorkspace({
currentAgent: computed(() => agent.currentAgent.value),
currentUser: computed(() => currentUser.value),
currentGuides: computed(() => chatGuides.guides.value),
pushLocalAssistantMessage,
pushLocalUserMessage,
});
@@ -353,6 +362,7 @@ export function useChatPage() {
handleLeaveMarkdownClick: leave.handleLeaveMarkdownClick,
parsePlmPreviewLink,
openPreview,
openAssetHistory: assetHistory.openHistory,
getMessageLinks,
getDisplayRetrieverResources,
getSourceLinks,
@@ -479,6 +489,7 @@ export function useChatPage() {
isThinking,
shippingActionBusy,
conversationId,
viewId,
input,
browser,
queryPreview,
@@ -492,6 +503,7 @@ export function useChatPage() {
queryPreviewLoading: queryPreview.loading,
queryPreviewError: queryPreview.error,
queryPreviewState: queryPreview.state,
assetHistory,
...agent,
agentGuides: chatGuides.guides,
showGuideModal: chatGuides.showModal,
@@ -1,11 +1,13 @@
/**
* features/chat/composables/useTrainingWorkspace.ts
* 用途:封装新人培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
* 依赖:Vue reactivity、vue-i18n、training.api,以及 training.types。
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端。
*/
import { computed, ref, watch, type ComputedRef } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
exportTrainingRecords,
getMyTrainingProgress,
@@ -15,6 +17,8 @@ import {
} from '@/features/chat/api/training.api';
import type {
TrainingAnswerRecord,
TrainingContentConfig,
TrainingExamTransitionFeedback,
TrainingQuestion,
TrainingQuestionOption,
TrainingProgressRecord,
@@ -24,6 +28,13 @@ import type {
TrainingStats,
TrainingWorkspaceView,
} from '@/features/chat/training/training.types';
import {
matchesTrainingAgent,
resolveTrainingContentConfig,
resolveTrainingVideoGuide,
resolveTrainingVideoUrl,
type TrainingGuideLike,
} from '@/features/chat/training/trainingWorkspace.utils';
type TrainingAgentLike = {
name?: string | null;
@@ -36,44 +47,41 @@ type TrainingUserLike = {
real_name?: string | null;
employee_id?: string | null;
department?: string | null;
feature_permissions?: {
training_hr_manage?: boolean;
} | null;
} | null | undefined;
export interface UseTrainingWorkspaceOptions {
currentAgent: ComputedRef<TrainingAgentLike>;
currentUser: ComputedRef<TrainingUserLike>;
currentGuides: ComputedRef<TrainingGuideLike[]>;
pushLocalAssistantMessage?: (content: string) => Promise<void>;
pushLocalUserMessage?: (content: string) => Promise<void>;
}
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
/**
* 判断当前 Agent 是否应启用“培训工作区”。
* AI 触发时机:当需要把培训 UI 只挂在指定 Agent 上时使用,优先读 extra_config 显式开关,避免误伤其他聊天场景。
*/
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
const extraConfig = agent?.extra_config || {};
const explicitFlags = [
extraConfig.training_workspace_enabled,
extraConfig.training_mode,
extraConfig.training_agent,
];
if (explicitFlags.some((value) => value === true || value === 'true')) {
return true;
}
const name = String(agent?.name || '').trim();
return TRAINING_AGENT_NAME_PATTERN.test(name);
}
const DEFAULT_PASS_SCORE = 90;
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
/**
* 按百分制计算当前答题得分。
* AI 触发时机:当题库题量改为后台可配置后,不能再假定“每题固定 5 分”,因此每次答题都要按当前题量重新折算分数。
*/
const calculateTrainingScore = (correctAnswerCount: number, totalQuestionCount: number) => {
if (totalQuestionCount <= 0) return 0;
return Math.round((correctAnswerCount / totalQuestionCount) * 100);
};
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const { currentAgent, currentUser, pushLocalAssistantMessage, pushLocalUserMessage } = options;
const { currentAgent, currentUser, currentGuides, pushLocalAssistantMessage, pushLocalUserMessage } = options;
const { t, tm } = useI18n();
const msg = useMessage();
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
const isAdminViewer = computed(() => ['admin', 'hr'].includes(String(currentUser.value?.role || '')));
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
const activeView = ref<TrainingWorkspaceView>('learner');
const stage = ref<TrainingStage>('video');
@@ -83,10 +91,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const selectedOptionId = ref('');
const answerLocked = ref(false);
const currentFeedbackCorrect = ref(false);
const latestExamFeedback = ref<TrainingExamTransitionFeedback | null>(null);
const latestSettledResult = ref<{
score: number;
correctCount: number;
wrongCount: number;
isPassed: boolean;
} | null>(null);
const answerRecords = ref<TrainingAnswerRecord[]>([]);
const completionDate = ref<string | null>(null);
const currentJoinDate = ref<string | null>(null);
const isHydrated = ref(false);
const hasWarnedPersistFailure = ref(false);
const hasWarnedLoadFailure = ref(false);
const hrKeyword = ref('');
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
@@ -110,12 +127,12 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
});
const summaryPoints = computed(() => {
const defaultSummaryPoints = computed(() => {
const raw = tm('chat.training.summaryPoints');
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
});
const summaryChecklist = computed(() => {
const defaultSummaryChecklist = computed(() => {
const raw = tm('chat.training.summaryChecklist');
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
});
@@ -134,7 +151,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}));
});
const questionBank = computed<TrainingQuestion[]>(() => rawQuestionBank.value.map((item) => {
const mapLocaleQuestionBank = (questionSource: Array<Record<string, unknown>>): TrainingQuestion[] => questionSource.map((item) => {
const type = String(item.type || 'single') as TrainingQuestion['type'];
const rawOptions = Array.isArray(item.options) ? item.options : [];
const options = type === 'boolean'
@@ -152,14 +169,32 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
explanation: String(item.explanation || ''),
options,
};
}));
});
const defaultQuestionBank = computed<TrainingQuestion[]>(() => mapLocaleQuestionBank(rawQuestionBank.value));
const trainingContent = computed<TrainingContentConfig>(() => resolveTrainingContentConfig(
currentAgent.value,
{
passScore: DEFAULT_PASS_SCORE,
summaryPoints: defaultSummaryPoints.value,
summaryChecklist: defaultSummaryChecklist.value,
questionBank: defaultQuestionBank.value,
},
booleanOptions.value,
));
const summaryPoints = computed(() => trainingContent.value.summaryPoints);
const summaryChecklist = computed(() => trainingContent.value.summaryChecklist);
const questionBank = computed<TrainingQuestion[]>(() => trainingContent.value.questionBank);
const passScore = computed(() => trainingContent.value.passScore);
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
const totalQuestionCount = computed(() => questionBank.value.length);
const answeredCount = computed(() => answerRecords.value.length);
const correctCount = computed(() => answerRecords.value.filter((item) => item.correct).length);
const wrongCount = computed(() => answerRecords.value.filter((item) => !item.correct).length);
const isPassed = computed(() => score.value >= 90);
const isPassed = computed(() => score.value >= passScore.value);
const learnerProgressPercent = computed(() => {
if (stage.value === 'video') return 25;
@@ -191,10 +226,67 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
selectedOptionId.value = '';
answerLocked.value = false;
currentFeedbackCorrect.value = false;
latestExamFeedback.value = null;
answerRecords.value = [];
completionDate.value = null;
};
/**
* 读取题目选项展示文案,避免在聊天反馈里直接暴露内部 option id。
* AI 触发时机:当培训聊天流需要把上一题答题结果翻译成员工可读文案时使用。
*/
const getQuestionOptionLabel = (question: TrainingQuestion | null, optionId: string) => {
if (!question) return optionId;
return question.options?.find((item) => item.id === optionId)?.label || optionId;
};
/**
* 生成“上一题即时反馈”摘要,供聊天题卡在自动推进到下一题后继续展示。
* AI 触发时机:当员工刚答完一道题、或刷新页面后要恢复“反馈 + 下一题”联动体验时使用。
*/
const buildExamFeedback = (
question: TrainingQuestion | null,
answerRecord: TrainingAnswerRecord | null | undefined,
scoreAfterAnswer: number,
): TrainingExamTransitionFeedback | null => {
if (!question || !answerRecord) return null;
return {
questionId: question.id,
questionPrompt: question.prompt,
selectedAnswerLabel: getQuestionOptionLabel(question, answerRecord.selectedOptionId),
correctAnswerLabel: getQuestionOptionLabel(question, question.answer),
explanation: question.explanation,
correct: Boolean(answerRecord.correct),
scoreAfterAnswer,
};
};
const getQuestionTypeLabel = (question: TrainingQuestion | null) => (
question?.type === 'boolean'
? t('chat.training.chatPrompts.assistantQuestionBooleanType')
: t('chat.training.chatPrompts.assistantQuestionSingleType')
);
const buildExamQuestionMessage = (question: TrainingQuestion | null, questionIndex: number) => {
if (!question) return '';
const optionLines = (question.options || []).map((option) => option.label).join('\n');
return [
`📝 **${t('chat.training.exam.questionCounter', { current: questionIndex + 1, total: totalQuestionCount.value })}(${getQuestionTypeLabel(question)})**:${question.prompt}`,
optionLines,
t('chat.training.chatPrompts.assistantQuestionReplyHint'),
].filter(Boolean).join('\n');
};
const buildSummaryAssistantMessage = () => {
const summaryLines = summaryPoints.value.map((point, index) => `${index + 1}. ${point}`).join('\n');
return [
t('chat.training.chatPrompts.assistantSummaryIntro'),
summaryLines,
'',
t('chat.training.chatPrompts.assistantSummaryReady'),
].join('\n');
};
const syncAnswerStateForCurrentQuestion = () => {
const questionId = currentQuestion.value?.id;
const currentAnswer = questionId
@@ -210,6 +302,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
stage.value = 'video';
resetExamState();
currentJoinDate.value = null;
latestSettledResult.value = null;
return;
}
stage.value = record.stage;
@@ -219,6 +312,22 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
answerRecords.value = Array.isArray(record.answerDetails) ? record.answerDetails : [];
completionDate.value = record.completionDate;
currentJoinDate.value = record.joinDate || null;
latestExamFeedback.value = null;
if (record.stage === 'result') {
latestSettledResult.value = {
score: Number(record.score || 0),
correctCount: answerRecords.value.filter((item) => item.correct).length,
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
isPassed: Boolean(record.passed || Number(record.score || 0) >= passScore.value),
};
}
if (record.stage === 'exam' && record.currentQuestionIndex > 0) {
const previousQuestion = questionBank.value[record.currentQuestionIndex - 1] || null;
const previousAnswer = previousQuestion
? answerRecords.value.find((item) => item.questionId === previousQuestion.id)
: null;
latestExamFeedback.value = buildExamFeedback(previousQuestion, previousAnswer, Number(record.score || 0));
}
syncAnswerStateForCurrentQuestion();
};
@@ -237,13 +346,23 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
persistQueue = persistQueue.catch(() => undefined).then(async () => {
try {
const saved = await saveMyTrainingProgress(buildProgressPayload());
hasWarnedPersistFailure.value = false;
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
completionDate.value = saved.completionDate;
if (isAdminViewer.value) {
void loadAdminRecords();
}
} catch {
// 保持本地培训流程可继续,避免接口波动阻断考试进行。
} catch (error) {
if (!hasWarnedPersistFailure.value) {
hasWarnedPersistFailure.value = true;
const message = error instanceof BusinessError
? error.message
: t('errors.generic');
msg.error({
title: t('chat.training.errors.persistTitle'),
message: `${t('chat.training.errors.persistBody')}:${message}`,
});
}
}
});
await persistQueue;
@@ -251,10 +370,33 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const loadTrainingProgress = async () => {
if (!isTrainingAgent.value) return;
if (!hasAuthenticatedUser.value) {
hasWarnedLoadFailure.value = false;
applyProgressRecord(null);
isHydrated.value = true;
return;
}
try {
const record = await getMyTrainingProgress();
hasWarnedLoadFailure.value = false;
applyProgressRecord(record);
} catch {
} catch (error) {
// 退出登录或登录态失效时,培训页可能尚未卸载;这里静默清空状态,避免把正常 401 提示成“读取失败”。
if (error instanceof BusinessError && error.status === 401) {
hasWarnedLoadFailure.value = false;
applyProgressRecord(null);
return;
}
if (!hasWarnedLoadFailure.value) {
hasWarnedLoadFailure.value = true;
const message = error instanceof BusinessError
? error.message
: t('errors.generic');
msg.warning({
title: t('chat.training.errors.loadTitle'),
message: `${t('chat.training.errors.loadBody')}:${message}`,
});
}
applyProgressRecord(null);
} finally {
isHydrated.value = true;
@@ -290,26 +432,49 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
};
watch(currentAgent, (agent) => {
if (!matchesTrainingAgent(agent)) {
records.value = [];
departmentOptions.value = [];
stats.value = {
total: 0,
passed: 0,
failed: 0,
inProgress: 0,
passRate: 0,
averageScore: 0,
};
return;
}
isHydrated.value = false;
void loadTrainingProgress();
}, { immediate: true });
watch(
[
currentAgent,
hasAuthenticatedUser,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
],
([agent, loggedIn]) => {
if (!matchesTrainingAgent(agent)) {
records.value = [];
departmentOptions.value = [];
stats.value = {
total: 0,
passed: 0,
failed: 0,
inProgress: 0,
passRate: 0,
averageScore: 0,
};
return;
}
if (!loggedIn) {
hasWarnedLoadFailure.value = false;
applyProgressRecord(null);
isHydrated.value = true;
return;
}
isHydrated.value = false;
void loadTrainingProgress();
},
{ immediate: true },
);
watch(
[isTrainingAgent, isAdminViewer, hrKeyword, hrStatusFilter, hrDepartmentFilter],
[
isTrainingAgent,
isAdminViewer,
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
],
([enabled, canView]) => {
if (!enabled || !canView) return;
void loadAdminRecords();
@@ -320,37 +485,66 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const markVideoCompleted = () => {
stage.value = 'summary';
// 立即推入本地助手消息(复盘卡片)
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
void persistProgress();
};
const startExam = () => {
if (totalQuestionCount.value <= 0) {
msg.warning(t('chat.training.errors.questionBankEmpty'));
return;
}
stage.value = 'exam';
attemptCount.value += 1;
resetExamState();
void pushLocalUserMessage?.(t('chat.training.chatPrompts.startExamCommand'));
// 立即推入第一题的消息引导
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
void persistProgress();
};
const selectAnswer = (optionId: string) => {
if (answerLocked.value || !currentQuestion.value) return;
const answeredQuestion = currentQuestion.value;
selectedOptionId.value = optionId;
const isCorrect = optionId === currentQuestion.value.answer;
const isCorrect = optionId === answeredQuestion.answer;
currentFeedbackCorrect.value = isCorrect;
if (isCorrect) {
score.value += 5;
}
answerRecords.value.push({
questionId: currentQuestion.value.id,
const nextCorrectAnswerCount = correctCount.value + (isCorrect ? 1 : 0);
const nextScore = calculateTrainingScore(nextCorrectAnswerCount, totalQuestionCount.value);
score.value = nextScore;
const answerRecord: TrainingAnswerRecord = {
questionId: answeredQuestion.id,
selectedOptionId: optionId,
correct: isCorrect,
});
answerLocked.value = true;
};
answerRecords.value.push(answerRecord);
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
// 推入用户选择的答案到聊天流
const label = currentQuestion.value.options?.find(o => o.id === optionId)?.label || optionId;
const label = getQuestionOptionLabel(answeredQuestion, optionId);
void pushLocalUserMessage?.(label);
// [STEP 1] 最后一题直接进入结算,对齐文档里的“答完即公布最终成绩”。
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
stage.value = 'result';
completionDate.value = formatDate(new Date());
latestSettledResult.value = {
score: nextScore,
correctCount: answerRecords.value.filter((item) => item.correct).length,
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
isPassed: nextScore >= passScore.value,
};
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
void persistProgress();
return;
}
// [STEP 2] 非最后一题则在聊天流里自动反馈上一题,并紧接着展示下一题。
currentQuestionIndex.value += 1;
selectedOptionId.value = '';
answerLocked.value = false;
currentFeedbackCorrect.value = false;
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
void persistProgress();
};
@@ -364,7 +558,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
stage.value = 'result';
completionDate.value = formatDate(new Date());
// 推入结果消息
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
void persistProgress();
return;
}
@@ -372,17 +566,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
selectedOptionId.value = '';
answerLocked.value = false;
currentFeedbackCorrect.value = false;
latestExamFeedback.value = null;
// 推入下一题消息
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
void persistProgress();
};
const restartExam = () => {
stage.value = 'summary';
stage.value = 'video';
resetExamState();
// 重新推回复盘卡片
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void persistProgress();
void pushLocalUserMessage?.(t('chat.training.chatPrompts.restartExamCommand'));
// 重新推回视频导学,强制补考再次完整经过“视频 -> 复盘 -> 开考”链路。
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
};
const exportRecords = async () => {
@@ -405,21 +601,14 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
const learnerChatPrompt = computed(() => {
// 阶段 1:破冰与视频导学
if (stage.value === 'video') {
return `👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。\n\n▶️ 请先点击观看 [入职培训视频]。观看完毕后,请回复【已看完】。`;
}
// 阶段 2:知识点串讲
if (stage.value === 'summary') {
return `${t('chat.training.chatPrompts.afterVideo')}\n\n参考知识点:\n${summaryPoints.value.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
}
// 阶段 4:结算
// 发送给 Agent 的“用户侧”提示语,用于同步当前培训上下文到正式聊天链路。
if (stage.value === 'video') return t('chat.training.chatPrompts.afterVideo');
if (stage.value === 'summary') return t('chat.training.chatPrompts.afterSummary');
if (stage.value === 'result') {
return isPassed.value
? t('chat.training.chatPrompts.afterPass', { score: score.value })
: t('chat.training.chatPrompts.afterFail', { score: score.value });
}
// 阶段 3:互动测试
return t('chat.training.chatPrompts.examInProgress', {
index: currentQuestionIndex.value + 1,
total: totalQuestionCount.value,
@@ -427,11 +616,36 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
});
/**
* 新建培训聊天会话时使用的统一提醒文案。
* AI 触发时机:当员工进入培训 Agent 的空白新会话,且当前考试尚未通过时,必须像首次进入一样重新提醒培训要求。
*/
const newSessionReminderMessage = computed(() => t('chat.training.chatPrompts.assistantVideoIntro', {
passScore: passScore.value,
}));
const shouldShowNewSessionReminder = computed(() => !isPassed.value);
const learnerAssistantMessage = computed(() => {
// 发送到本地聊天框的“助手侧”文案,对齐培训设计文档中的四阶段话术。
if (stage.value === 'video') {
return t('chat.training.chatPrompts.assistantVideoIntro', { passScore: passScore.value });
}
if (stage.value === 'summary') {
return buildSummaryAssistantMessage();
}
if (stage.value === 'result') {
return isPassed.value
? t('chat.training.chatPrompts.assistantResultPass', { score: score.value })
: t('chat.training.chatPrompts.assistantResultFail', { score: score.value, passScore: passScore.value });
}
return buildExamQuestionMessage(currentQuestion.value, currentQuestionIndex.value);
});
const showVideoModal = ref(false);
const videoUrl = computed(() => {
const extraConfig = currentAgent.value?.extra_config || {};
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
return customUrl || DEFAULT_TRAINING_VIDEO_URL;
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
});
return {
@@ -443,12 +657,15 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
currentQuestionIndex,
currentQuestion,
totalQuestionCount,
passScore,
answeredCount,
score,
attemptCount,
selectedOptionId,
answerLocked,
currentFeedbackCorrect,
latestExamFeedback,
latestSettledResult,
answerRecords,
completionDate,
summaryPoints,
@@ -467,6 +684,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
filteredRecords,
stats,
learnerChatPrompt,
newSessionReminderMessage,
shouldShowNewSessionReminder,
learnerAssistantMessage,
managementChatPrompt,
markVideoCompleted,
startExam,
@@ -92,6 +92,7 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
getCurrentQuestionIndex: () => workspace.currentQuestionIndex.value,
getAnsweredCount: () => workspace.answeredCount.value,
getTotalCount: () => workspace.totalQuestionCount.value,
getPassScore: () => workspace.passScore.value,
getScore: () => workspace.score.value,
getSelectedOptionId: () => workspace.selectedOptionId.value,
getAnswerLocked: () => workspace.answerLocked.value,
@@ -101,6 +102,7 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
if (!q) return '';
return q.options?.find((o) => o.id === workspace.selectedOptionId.value)?.label || '';
},
getLatestExamFeedback: () => workspace.latestExamFeedback.value,
onSelect: workspace.selectAnswer,
onNext: workspace.moveToNextQuestion,
onPlayVideo: () => {
@@ -110,8 +112,10 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
},
onStartExam: workspace.startExam,
onRestartExam: workspace.restartExam,
getCorrectCount: () => workspace.correctCount.value,
getWrongCount: () => workspace.wrongCount.value,
getCorrectCount: () => workspace.latestSettledResult.value?.correctCount ?? workspace.correctCount.value,
getWrongCount: () => workspace.latestSettledResult.value?.wrongCount ?? workspace.wrongCount.value,
getResultScore: () => workspace.latestSettledResult.value?.score ?? workspace.score.value,
getResultPassed: () => workspace.latestSettledResult.value?.isPassed ?? workspace.isPassed.value,
getSummaryPoints: () => workspace.summaryPoints.value,
getSummaryChecklist: () => workspace.summaryChecklist.value,
};
@@ -64,6 +64,7 @@ export interface ChatPageMarkdownContext {
handleLeaveMarkdownClick: (event: MouseEvent) => void;
parsePlmPreviewLink: (href: string) => SourceFileLink | null;
openPreview: (file: SourceFileLink) => Promise<void>;
openAssetHistory: (assetId: string, assetName?: string) => void;
getMessageLinks: (message: Record<string, unknown>) => SourceFileLink[];
getDisplayRetrieverResources: (msgItem: Record<string, unknown>) => Record<string, unknown>[];
getSourceLinks: (resources?: unknown[]) => SourceFileLink[];
@@ -178,6 +179,47 @@ function downloadInlineFile(file: InlineDownloadFile): void {
URL.revokeObjectURL(objectUrl);
}
function normalizeAssetHistoryText(value: string): string {
const normalized = String(value || '').trim();
if (!normalized || normalized === '-' || normalized === '无') return '';
return normalized;
}
/**
* 把聊天结果表格里的“资产编号”列增强为可点击入口。
* 核心逻辑:只处理包含“资产编号”表头的表格,并从同行“资产名称”列一并带出检索关键词,避免误伤其他普通 Markdown 表格。
*/
function enhanceAssetHistoryTableLinks(html: string): string {
if (!html || typeof document === 'undefined' || !html.includes('<table')) return html;
const container = document.createElement('div');
container.innerHTML = html;
const tables = Array.from(container.querySelectorAll('table'));
tables.forEach((table) => {
const headerCells = Array.from(table.querySelectorAll('thead th'));
if (headerCells.length === 0) return;
const headerLabels = headerCells.map((cell) => normalizeAssetHistoryText(cell.textContent || ''));
const assetIdIndex = headerLabels.findIndex((label) => label === '资产编号');
if (assetIdIndex < 0) return;
const assetNameIndex = headerLabels.findIndex((label) => label === '资产名称');
const rows = Array.from(table.querySelectorAll('tbody tr'));
rows.forEach((row) => {
const cells = Array.from(row.querySelectorAll('td'));
const assetIdCell = cells[assetIdIndex];
if (!assetIdCell) return;
const assetId = normalizeAssetHistoryText(assetIdCell.textContent || '');
if (!assetId) return;
const assetName = assetNameIndex >= 0 ? normalizeAssetHistoryText(cells[assetNameIndex]?.textContent || '') : '';
const link = document.createElement('a');
link.href = `#asset-history?asset_id=${encodeURIComponent(assetId)}&asset_name=${encodeURIComponent(assetName)}`;
link.className = 'chat-asset-history-link';
link.textContent = assetId;
assetIdCell.innerHTML = '';
assetIdCell.appendChild(link);
});
});
return container.innerHTML;
}
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
@@ -226,7 +268,34 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const handleChatMarkdownClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
const preview = ctx.parsePlmPreviewLink(anchor?.getAttribute('href') || '');
const rawHref = anchor?.getAttribute('href') || '';
// #region debug-point A:asset-history-anchor-click
if (rawHref.startsWith('#asset-history?')) {
fetch('http://127.0.0.1:7777/event', {
method: 'POST',
body: JSON.stringify({
sessionId: 'asset-history-click',
runId: 'pre-fix',
hypothesisId: 'A',
location: 'frontend/useChatPageMarkdown.ts',
msg: '[DEBUG] asset history anchor clicked',
data: {
href: rawHref,
tagName: target?.tagName || '',
anchorText: String(anchor?.textContent || '').trim(),
},
ts: Date.now(),
}),
}).catch(() => {});
}
// #endregion
if (rawHref.startsWith('#asset-history?')) {
event.preventDefault();
const params = new URLSearchParams(rawHref.slice('#asset-history?'.length));
ctx.openAssetHistory((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim());
return;
}
const preview = ctx.parsePlmPreviewLink(rawHref);
if (preview) {
event.preventDefault();
void ctx.openPreview(preview);
@@ -248,7 +317,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
try {
const rendered = marked.parse(displayText);
const html = typeof rendered === 'string' ? rendered : displayText;
return html
return enhanceAssetHistoryTableLinks(html)
.replace(/<(td|th)\b([^>]*)>(?:\s|&nbsp;|<br\s*\/?>)*<\/\1>/gi, (_match, tagName: string, attrs: string) => (
`<${tagName}${attrs}>无</${tagName}>`
))
@@ -263,6 +332,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
renderMarkdown,
onMarkdownClick: handleChatMarkdownClick,
openAssetHistory: ctx.openAssetHistory,
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
downloadInlineFile,
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
@@ -25,12 +25,29 @@ export interface TrainingQuestion {
options?: TrainingQuestionOption[];
}
export interface TrainingContentConfig {
passScore: number;
summaryPoints: string[];
summaryChecklist: string[];
questionBank: TrainingQuestion[];
}
export interface TrainingAnswerRecord {
questionId: string;
selectedOptionId: string;
correct: boolean;
}
export interface TrainingExamTransitionFeedback {
questionId: string;
questionPrompt: string;
selectedAnswerLabel: string;
correctAnswerLabel: string;
explanation: string;
correct: boolean;
scoreAfterAnswer: number;
}
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
export interface TrainingRecord {
@@ -0,0 +1,185 @@
/**
* features/chat/training/trainingWorkspace.utils.ts
* 用途:沉淀新人培训工作区的纯函数规则,便于前端复用与单测。
* 依赖:无运行时副作用,仅依赖 Agent extra_config 普通对象与 training.types。
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库与复盘配置。
*/
import type { TrainingContentConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
type TrainingAgentLike = {
name?: string | null;
extra_config?: Record<string, unknown> | null;
} | null | undefined;
export type TrainingGuideLike = {
id?: number | null;
file_type?: string | null;
guide_usage?: string | null;
file_url?: string | null;
file_path?: string | null;
} | null | undefined;
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
const DEFAULT_PASS_SCORE = 90;
const asRecord = (value: unknown): Record<string, unknown> => (
value && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: {}
);
const normalizeStringList = (value: unknown): string[] => {
if (!Array.isArray(value)) return [];
return value
.map((item) => String(item || '').trim())
.filter(Boolean);
};
const normalizePassScore = (value: unknown, fallback: number): number => {
const parsed = Number(value);
if (!Number.isFinite(parsed)) return fallback;
return Math.max(0, Math.min(100, Math.round(parsed)));
};
const normalizeQuestionOptionList = (value: unknown): TrainingQuestionOption[] => {
if (!Array.isArray(value)) return [];
return value
.map((item, index) => {
if (typeof item === 'string') {
const label = item.trim();
if (!label) return null;
return {
id: String.fromCharCode(97 + index),
label,
};
}
const raw = asRecord(item);
const id = String(raw.id || '').trim() || String.fromCharCode(97 + index);
const label = String(raw.label || '').trim();
if (!label) return null;
return { id, label };
})
.filter((item): item is TrainingQuestionOption => Boolean(item));
};
const normalizeQuestionBank = (
value: unknown,
booleanOptions: TrainingQuestionOption[],
): TrainingQuestion[] => {
if (!Array.isArray(value)) return [];
return value
.map((item, index): TrainingQuestion | null => {
const raw = asRecord(item);
const type: TrainingQuestion['type'] = raw.type === 'boolean' ? 'boolean' : 'single';
const prompt = String(raw.prompt || '').trim();
if (!prompt) return null;
const options = type === 'boolean'
? booleanOptions
: normalizeQuestionOptionList(raw.options);
if (type === 'single' && options.length < 2) return null;
const fallbackAnswer = type === 'boolean'
? 'true'
: String(options[0]?.id || '').trim();
const answer = String(raw.answer || '').trim();
const optionIds = options.map((option) => option.id);
return {
id: String(raw.id || '').trim() || `q${index + 1}`,
type,
prompt,
answer: optionIds.includes(answer) ? answer : fallbackAnswer,
explanation: String(raw.explanation || '').trim(),
options,
};
})
.filter((item): item is TrainingQuestion => Boolean(item));
};
/**
* 判断当前 Agent 是否应启用培训工作区。
* AI 触发时机:当聊天页需要决定是否渲染“视频 -> 总结 -> 答题”培训主链时使用,优先读取显式配置,避免误伤普通 Agent。
*/
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
const extraConfig = agent?.extra_config || {};
if (extraConfig.training_workspace_enabled === false || extraConfig.training_workspace_enabled === 'false') {
return false;
}
const explicitFlags = [
extraConfig.training_workspace_enabled,
extraConfig.training_mode,
extraConfig.training_agent,
];
if (explicitFlags.some((value) => value === true || value === 'true')) {
return true;
}
const name = String(agent?.name || '').trim();
return TRAINING_AGENT_NAME_PATTERN.test(name);
}
/**
* 解析培训视频地址。
* AI 触发时机:当培训工作区需要决定播放哪个培训视频时使用,若 Agent 未配置专属视频,则回退到默认地址。
*/
export function resolveTrainingVideoUrl(agent: TrainingAgentLike, fallbackUrl: string): string {
const extraConfig = agent?.extra_config || {};
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
return customUrl || fallbackUrl;
}
/**
* 查找培训工作区优先使用的视频指南。
* AI 触发时机:当培训工作区需要从后台上传资料中挑选正式培训视频时使用,优先选显式标记为 training_video 的文件。
*/
export function resolveTrainingVideoGuide(guides: TrainingGuideLike[] | null | undefined): TrainingGuideLike {
const normalized = Array.isArray(guides) ? guides : [];
return (
normalized.find((guide) => guide?.guide_usage === 'training_video' && guide?.file_type === 'video')
|| normalized.find((guide) => guide?.file_type === 'video')
|| null
);
}
/**
* 查找培训工作区优先使用的试题 PDF。
* AI 触发时机:当员工培训页需要为学员提供“查看试题 PDF”入口时使用,避免把普通指南 PDF 错当成考试资料。
*/
export function resolveTrainingExamPdfGuide(guides: TrainingGuideLike[] | null | undefined): TrainingGuideLike {
const normalized = Array.isArray(guides) ? guides : [];
return (
normalized.find((guide) => guide?.guide_usage === 'training_exam_pdf' && guide?.file_type === 'pdf')
|| null
);
}
/**
* 解析培训工作区的后台配置。
* AI 触发时机:当培训工作区需要优先消费 Agent extra_config 中的题库、复盘要点和及格线时使用;若后台未配置,则逐项回退到前端默认值。
*/
export function resolveTrainingContentConfig(
agent: TrainingAgentLike,
fallback: TrainingContentConfig,
booleanOptions: TrainingQuestionOption[],
): TrainingContentConfig {
const extraConfig = asRecord(agent?.extra_config);
const trainingConfig = asRecord(extraConfig.training_config);
const mergedConfig = {
...extraConfig,
...trainingConfig,
};
const summaryPoints = normalizeStringList(mergedConfig.summary_points ?? mergedConfig.summaryPoints);
const summaryChecklist = normalizeStringList(mergedConfig.summary_checklist ?? mergedConfig.summaryChecklist);
const questionBank = normalizeQuestionBank(
mergedConfig.question_bank ?? mergedConfig.questionBank,
booleanOptions,
);
return {
passScore: normalizePassScore(
mergedConfig.pass_score ?? mergedConfig.passScore,
fallback.passScore || DEFAULT_PASS_SCORE,
),
summaryPoints: summaryPoints.length ? summaryPoints : fallback.summaryPoints,
summaryChecklist: summaryChecklist.length ? summaryChecklist : fallback.summaryChecklist,
questionBank: questionBank.length ? questionBank : fallback.questionBank,
};
}
+19 -1
View File
@@ -21,7 +21,7 @@ export interface RetrieverResource {
export interface ChatMessage {
role: 'user' | 'assistant';
content: string;
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result';
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
@@ -99,6 +99,24 @@ export interface ChatSourceFileResult {
source_ext?: string;
}
export interface AssetHistoryFileItem {
name: string;
path: string;
relative_path: string;
url: string;
actual_ext?: string;
size_bytes?: number;
modified_at?: string;
match_reason?: string;
}
export interface AssetHistorySearchResult {
asset_id?: string;
asset_name?: string;
total: number;
items: AssetHistoryFileItem[];
}
export interface ChatUploadResult {
id: string;
name?: string;
@@ -0,0 +1,74 @@
/**
* features/maintenance/api/maintenanceLedger.api.ts
* 用途:设备维保台账配置 HTTP API 封装。
* 依赖:shared/api/client、shared/utils/auth、ledger.types。
* 逻辑:右侧固定面板通过本模块加载列表、保存设备、下载模板和导入 Excel。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
MaintenanceDevice,
MaintenanceDeviceImportResult,
MaintenanceDeviceListResult,
MaintenanceDevicePayload,
} from '@/features/maintenance/types/ledger.types';
const API_BASE = '/api/maintenance/ledger';
export interface ListMaintenanceDevicesParams {
keyword?: string;
status?: string;
page?: number;
pageSize?: number;
}
const jsonHeaders = () => ({
...getAuthHeaders(),
'Content-Type': 'application/json',
});
export const listMaintenanceDevices = (params: ListMaintenanceDevicesParams = {}) => {
const sp = new URLSearchParams();
if (params.keyword) sp.set('keyword', params.keyword);
if (params.status) sp.set('status', params.status);
if (params.page) sp.set('page', String(params.page));
if (params.pageSize) sp.set('page_size', String(params.pageSize));
const qs = sp.toString();
return requestJson<MaintenanceDeviceListResult>(`${API_BASE}/devices${qs ? `?${qs}` : ''}`, {
headers: getAuthHeaders(),
});
};
export const getMaintenanceDevice = (id: number) => {
return requestJson<MaintenanceDevice>(`${API_BASE}/devices/${id}`, {
headers: getAuthHeaders(),
});
};
export const createMaintenanceDevice = (payload: MaintenanceDevicePayload) => {
return requestJson<MaintenanceDevice>(`${API_BASE}/devices`, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify(payload),
});
};
export const updateMaintenanceDevice = (id: number, payload: MaintenanceDevicePayload) => {
return requestJson<MaintenanceDevice>(`${API_BASE}/devices/${id}`, {
method: 'PUT',
headers: jsonHeaders(),
body: JSON.stringify(payload),
});
};
export const maintenanceLedgerImportTemplateUrl = `${API_BASE}/import-template`;
export const importMaintenanceDevices = (file: File) => {
const form = new FormData();
form.append('file', file);
return requestJson<MaintenanceDeviceImportResult>(`${API_BASE}/import`, {
method: 'POST',
headers: getAuthHeaders(),
body: form,
});
};
@@ -0,0 +1,85 @@
/**
* features/maintenance/api/maintenanceRecord.api.ts
* 用途:设备维修记录 HTTP API 封装。
* 依赖:shared/api/client、shared/utils/auth、record.types。
* 逻辑:右侧固定面板通过本模块新增记录和查询最近记录;会话查询也可复用同一后端接口。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
MaintenanceRecord,
MaintenanceRecordListResult,
MaintenanceRecordPayload,
} from '@/features/maintenance/types/record.types';
const API_BASE = '/api/maintenance/records';
export interface ListMaintenanceRecordsParams {
keyword?: string;
deviceCode?: string;
status?: string;
page?: number;
pageSize?: number;
}
const jsonHeaders = () => ({
...getAuthHeaders(),
'Content-Type': 'application/json',
});
export const listMaintenanceRecords = (params: ListMaintenanceRecordsParams = {}) => {
const sp = new URLSearchParams();
if (params.keyword) sp.set('keyword', params.keyword);
if (params.deviceCode) sp.set('deviceCode', params.deviceCode);
if (params.status) sp.set('status', params.status);
if (params.page) sp.set('page', String(params.page));
if (params.pageSize) sp.set('page_size', String(params.pageSize));
const qs = sp.toString();
return requestJson<MaintenanceRecordListResult>(`${API_BASE}${qs ? `?${qs}` : ''}`, {
headers: getAuthHeaders(),
});
};
export const getMaintenanceRecord = (id: number) => {
return requestJson<MaintenanceRecord>(`${API_BASE}/${id}`, {
headers: getAuthHeaders(),
});
};
export const createMaintenanceRecord = (payload: MaintenanceRecordPayload) => {
return requestJson<MaintenanceRecord>(API_BASE, {
method: 'POST',
headers: jsonHeaders(),
body: JSON.stringify(payload),
});
};
export const updateMaintenanceRecord = (id: number, payload: MaintenanceRecordPayload) => {
return requestJson<MaintenanceRecord>(`${API_BASE}/${id}`, {
method: 'PUT',
headers: jsonHeaders(),
body: JSON.stringify(payload),
});
};
export const deleteMaintenanceRecord = (id: number) => {
return requestJson<{ deleted: boolean; id: number }>(`${API_BASE}/${id}`, {
method: 'DELETE',
headers: getAuthHeaders(),
});
};
export const exportMaintenanceRecords = async (params: ListMaintenanceRecordsParams = {}) => {
const sp = new URLSearchParams();
if (params.keyword) sp.set('keyword', params.keyword);
if (params.deviceCode) sp.set('deviceCode', params.deviceCode);
if (params.status) sp.set('status', params.status);
const qs = sp.toString();
const response = await fetch(`${API_BASE}/export${qs ? `?${qs}` : ''}`, {
headers: getAuthHeaders(),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.blob();
};
@@ -0,0 +1,459 @@
<script setup lang="ts">
/**
* features/maintenance/components/LedgerConfigPanel.vue
* 用途:设备维保助手右侧固定面板中的“台账配置”页面,包含设备列表与设备配置两个 Tab。
* 依赖:maintenanceLedger.api、PaginationBar、useMessage。
* 逻辑:列表 Tab 负责查询/导入/选择设备;配置 Tab 负责新增或编辑设备台账,保存后刷新列表。
*/
import { computed, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import {
createMaintenanceDevice,
importMaintenanceDevices,
listMaintenanceDevices,
maintenanceLedgerImportTemplateUrl,
updateMaintenanceDevice,
} from '@/features/maintenance/api/maintenanceLedger.api';
import type {
MaintenanceDevice,
MaintenanceDeviceImportResult,
MaintenanceDevicePayload,
MaintenanceDeviceStatus,
} from '@/features/maintenance/types/ledger.types';
type TabName = 'list' | 'form';
const msg = useMessage();
const { t } = useI18n();
const activeTab = ref<TabName>('list');
const loading = ref(false);
const saving = ref(false);
const importing = ref(false);
const devices = ref<MaintenanceDevice[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const keyword = ref('');
const status = ref('');
const editingId = ref<number | null>(null);
const importResult = ref<MaintenanceDeviceImportResult | null>(null);
const MAX_IMPORT_FILE_SIZE = 10 * 1024 * 1024;
const DEFAULT_ACCOUNT_SET = '和信';
const accountSetOptions = ['和信', '科技', '电子', '和宏智'];
const form = reactive<MaintenanceDevicePayload>({
deviceCode: '',
deviceName: '',
modelSpec: '',
department: '',
installLocation: '',
deviceStatus: 'in_use',
manufacturer: '',
entryDate: '',
productionDate: '',
startDate: '',
responsibleUser: '',
maintenanceCycle: '',
originalValue: '',
residualValue: '',
accountSet: DEFAULT_ACCOUNT_SET,
remark: '',
});
const statusOptions: Array<{ value: MaintenanceDeviceStatus | ''; label: string }> = [
{ value: '', label: 'maintenance.ledger.status.all' },
{ value: 'in_use', label: 'maintenance.ledger.status.inUse' },
{ value: 'disabled', label: 'maintenance.ledger.status.disabled' },
{ value: 'scrapped', label: 'maintenance.ledger.status.scrapped' },
{ value: 'sold', label: 'maintenance.ledger.status.sold' },
];
const formTitle = computed(() => t(editingId.value ? 'maintenance.ledger.formTitle.edit' : 'maintenance.ledger.formTitle.create'));
/**
* 将后端状态值转换为中文展示。
* @param value - 设备状态值。
* @returns 中文状态。
*/
const formatStatus = (value: string): string => {
const item = statusOptions.find((option) => option.value === value);
return item?.label ? t(item.label) : value || '-';
};
/**
* 从表单状态生成 API payload,集中裁剪字符串。
* @returns 设备保存入参。
*/
const buildPayload = (): MaintenanceDevicePayload => ({
deviceCode: form.deviceCode.trim(),
deviceName: form.deviceName.trim(),
modelSpec: form.modelSpec?.trim(),
department: form.department?.trim(),
installLocation: form.installLocation?.trim(),
deviceStatus: form.deviceStatus,
manufacturer: form.manufacturer?.trim(),
entryDate: form.entryDate || undefined,
productionDate: form.productionDate || undefined,
startDate: form.startDate || undefined,
responsibleUser: form.responsibleUser?.trim(),
maintenanceCycle: form.maintenanceCycle?.trim(),
originalValue: form.originalValue?.trim(),
residualValue: form.residualValue?.trim(),
accountSet: form.accountSet?.trim(),
remark: form.remark?.trim(),
});
/**
* 加载设备台账分页列表。
* 核心逻辑:根据当前 keyword/status/page/pageSize 调用后端,刷新列表 Tab。
*/
const loadDevices = async (): Promise<void> => {
loading.value = true;
try {
const result = await listMaintenanceDevices({
keyword: keyword.value.trim(),
status: status.value,
page: page.value,
pageSize: pageSize.value,
});
devices.value = result.items;
total.value = result.total;
} catch (error: any) {
msg.error(error?.message || t('maintenance.ledger.messages.loadFailed'));
} finally {
loading.value = false;
}
};
/**
* 重置表单并切换到新增模式。
*/
const startCreate = (): void => {
editingId.value = null;
Object.assign(form, {
deviceCode: '',
deviceName: '',
modelSpec: '',
department: '',
installLocation: '',
deviceStatus: 'in_use',
manufacturer: '',
entryDate: '',
productionDate: '',
startDate: '',
responsibleUser: '',
maintenanceCycle: '',
originalValue: '',
residualValue: '',
accountSet: DEFAULT_ACCOUNT_SET,
remark: '',
});
activeTab.value = 'form';
};
/**
* 将选中设备带入表单并切换到配置 Tab。
* @param device - 列表中选中的设备。
*/
const startEdit = (device: MaintenanceDevice): void => {
editingId.value = device.id;
Object.assign(form, {
deviceCode: device.deviceCode || '',
deviceName: device.deviceName || '',
modelSpec: device.modelSpec || '',
department: device.department || '',
installLocation: device.installLocation || '',
deviceStatus: device.deviceStatus,
manufacturer: device.manufacturer || '',
entryDate: device.entryDate || '',
productionDate: device.productionDate || '',
startDate: device.startDate || '',
responsibleUser: device.responsibleUser || '',
maintenanceCycle: device.maintenanceCycle || '',
originalValue: device.originalValue != null ? String(device.originalValue) : '',
residualValue: device.residualValue != null ? String(device.residualValue) : '',
accountSet: device.accountSet || '',
remark: device.remark || '',
});
activeTab.value = 'form';
};
/**
* 保存设备台账配置。
* 核心逻辑:新增/编辑共用同一表单;保存成功后刷新列表并回到设备列表 Tab。
*/
const saveDevice = async (): Promise<void> => {
const payload = buildPayload();
if (!payload.deviceCode || !payload.deviceName) {
msg.warning(t('maintenance.ledger.messages.required'));
return;
}
saving.value = true;
try {
if (editingId.value) {
await updateMaintenanceDevice(editingId.value, payload);
} else {
await createMaintenanceDevice(payload);
}
msg.success(t('maintenance.ledger.messages.saved'));
activeTab.value = 'list';
await loadDevices();
} catch (error: any) {
msg.error(error?.message || t('maintenance.ledger.messages.saveFailed'));
} finally {
saving.value = false;
}
};
/**
* 校验设备台账导入文件,避免明显不符合要求的文件进入后端解析。
* @param file - 用户选择的 Excel 文件。
* @returns 校验是否通过。
*/
const validateImportFile = (file: File): boolean => {
const fileName = file.name.toLowerCase();
if (!fileName.endsWith('.xlsx')) {
msg.warning(t('maintenance.ledger.messages.invalidFormat'));
return false;
}
if (file.size > MAX_IMPORT_FILE_SIZE) {
msg.warning(t('maintenance.ledger.messages.fileTooLarge'));
return false;
}
return true;
};
/**
* 上传 Excel 模板并导入设备台账。
* @param event - 文件选择事件。
*/
const onImportFileChange = async (event: Event): Promise<void> => {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
if (!validateImportFile(file)) return;
importing.value = true;
try {
importResult.value = await importMaintenanceDevices(file);
msg.success(t('maintenance.ledger.messages.importDone'));
await loadDevices();
} catch (error: any) {
msg.error(error?.message || t('maintenance.ledger.messages.importFailed'));
} finally {
importing.value = false;
}
};
onMounted(loadDevices);
</script>
<template>
<section class="flex h-full min-h-0 flex-col">
<div class="mb-4 rounded-xl border border-sky-200 bg-sky-50 px-3 py-2 text-sm text-sky-800">
{{ t('maintenance.ledger.notice') }}
</div>
<div class="mb-4 flex rounded-xl border border-default bg-muted/30 p-1">
<button
type="button"
class="relative flex-1 cursor-pointer rounded-lg border px-3 py-2 text-sm font-semibold transition-all hover:bg-surface hover:text-brand"
:class="activeTab === 'list' ? 'border-brand-300 bg-surface text-brand shadow-sm after:absolute after:inset-x-6 after:bottom-0 after:h-0.5 after:rounded-full after:bg-brand' : 'border-transparent text-secondary'"
:aria-selected="activeTab === 'list'"
@click="activeTab = 'list'"
>
{{ t('maintenance.ledger.tabs.list') }}
</button>
<button
type="button"
class="relative flex-1 cursor-pointer rounded-lg border px-3 py-2 text-sm font-semibold transition-all hover:bg-surface hover:text-brand"
:class="activeTab === 'form' ? 'border-brand-300 bg-surface text-brand shadow-sm after:absolute after:inset-x-6 after:bottom-0 after:h-0.5 after:rounded-full after:bg-brand' : 'border-transparent text-secondary'"
:aria-selected="activeTab === 'form'"
@click="activeTab = 'form'"
>
{{ t('maintenance.ledger.tabs.form') }}
</button>
</div>
<div v-if="activeTab === 'list'" class="flex min-h-0 flex-1 flex-col gap-4">
<div class="flex flex-wrap gap-3">
<input
v-model="keyword"
class="admin-table-filter-input w-full md:w-[360px] lg:w-[420px]"
:placeholder="t('maintenance.ledger.filters.keywordPlaceholder')"
@keyup.enter="page = 1; loadDevices()"
/>
<select v-model="status" class="admin-table-filter-input w-full md:w-[150px]" @change="page = 1; loadDevices()">
<option v-for="item in statusOptions" :key="item.value || 'all'" :value="item.value">
{{ t(item.label) }}
</option>
</select>
</div>
<div class="flex flex-wrap gap-2">
<button type="button" class="admin-report-page-btn admin-report-page-btn--active" @click="page = 1; loadDevices()">
{{ t('maintenance.ledger.actions.search') }}
</button>
<button type="button" class="admin-report-page-btn" @click="startCreate">
{{ t('maintenance.ledger.actions.create') }}
</button>
<a class="admin-report-page-btn" :href="maintenanceLedgerImportTemplateUrl" target="_blank">
{{ t('maintenance.ledger.actions.downloadTemplate') }}
</a>
<label class="admin-report-page-btn cursor-pointer">
{{ importing ? t('maintenance.ledger.actions.importing') : t('maintenance.ledger.actions.importExcel') }}
<input type="file" class="hidden" accept=".xlsx" :disabled="importing" @change="onImportFileChange" />
</label>
</div>
<div v-if="importResult" class="rounded-xl border border-default bg-surface px-3 py-2 text-sm">
{{ t('maintenance.ledger.importResult', importResult) }}
<div v-if="importResult.errors.length" class="mt-2 text-danger">
<div v-for="err in importResult.errors.slice(0, 5)" :key="`${err.row}-${err.message}`">
{{ t('maintenance.ledger.importErrorRow', err) }}
</div>
</div>
</div>
<div class="min-h-0 overflow-auto rounded-xl border border-default bg-surface">
<table class="min-w-full text-left text-sm">
<thead class="bg-muted/50 text-secondary">
<tr>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.deviceCode') }}</th>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.deviceName') }}</th>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.modelSpec') }}</th>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.manufacturer') }}</th>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.status') }}</th>
<th class="px-3 py-2">{{ t('maintenance.ledger.table.operation') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="6" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.ledger.table.loading') }}</td>
</tr>
<tr v-else-if="!devices.length">
<td colspan="6" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.ledger.table.empty') }}</td>
</tr>
<tr v-for="device in devices" v-else :key="device.id" class="border-t border-default">
<td class="px-3 py-2 font-semibold">{{ device.deviceCode }}</td>
<td class="px-3 py-2">{{ device.deviceName }}</td>
<td class="px-3 py-2">{{ device.modelSpec || '-' }}</td>
<td class="px-3 py-2">{{ device.manufacturer || '-' }}</td>
<td class="px-3 py-2">{{ formatStatus(device.deviceStatus) }}</td>
<td class="px-3 py-2">
<button type="button" class="admin-report-page-btn" @click="startEdit(device)">
{{ t('maintenance.ledger.actions.edit') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<PaginationBar
v-model:page="page"
v-model:page-size="pageSize"
:total="total"
@update:page="loadDevices"
@update:page-size="loadDevices"
/>
</div>
<div v-else class="min-h-0 flex-1 overflow-auto">
<div class="mb-4 flex items-center justify-between">
<h3 class="text-base font-semibold text-primary">{{ formTitle }}</h3>
<button type="button" class="admin-report-page-btn" @click="activeTab = 'list'">{{ t('maintenance.ledger.actions.backToList') }}</button>
</div>
<div class="grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.deviceCode') }} *
<input v-model="form.deviceCode" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.deviceName') }} *
<input v-model="form.deviceName" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.modelSpec') }}
<input v-model="form.modelSpec" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.manufacturer') }}
<input v-model="form.manufacturer" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.devicePosition') }}
<input v-model="form.installLocation" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.deviceStatus') }}
<select v-model="form.deviceStatus" class="admin-table-filter-input">
<option value="in_use">{{ t('maintenance.ledger.status.inUse') }}</option>
<option value="disabled">{{ t('maintenance.ledger.status.disabled') }}</option>
<option value="scrapped">{{ t('maintenance.ledger.status.scrapped') }}</option>
<option value="sold">{{ t('maintenance.ledger.status.sold') }}</option>
</select>
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.department') }}
<input v-model="form.department" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.responsibleUser') }}
<input v-model="form.responsibleUser" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.productionDate') }}
<input v-model="form.productionDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.entryDate') }}
<input v-model="form.entryDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.startDate') }}
<input v-model="form.startDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.maintenanceCycle') }}
<input v-model="form.maintenanceCycle" class="admin-table-filter-input" :placeholder="t('maintenance.ledger.placeholder.maintenanceCycle')" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.originalValue') }}
<input v-model="form.originalValue" type="number" min="0" step="0.01" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.residualValue') }}
<input v-model="form.residualValue" type="number" min="0" step="0.01" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.ledger.fields.accountSet') }}
<select v-model="form.accountSet" class="admin-table-filter-input">
<option v-for="item in accountSetOptions" :key="item" :value="item">
{{ item }}
</option>
</select>
</label>
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
{{ t('maintenance.ledger.fields.remark') }}
<textarea v-model="form.remark" class="admin-table-filter-input min-h-24" />
</label>
</div>
<div class="mt-5 flex justify-end gap-2">
<button type="button" class="admin-report-page-btn" @click="activeTab = 'list'">{{ t('maintenance.ledger.actions.cancel') }}</button>
<button
type="button"
class="admin-report-page-btn admin-report-page-btn--active"
:disabled="saving"
@click="saveDevice"
>
{{ saving ? t('maintenance.ledger.actions.saving') : t('maintenance.ledger.actions.save') }}
</button>
</div>
</div>
</section>
</template>
@@ -0,0 +1,484 @@
<script setup lang="ts">
/**
* features/maintenance/components/MaintenanceRecordManagerPanel.vue
* 用途:设备维保助手右侧固定面板中的维修记录管理页,覆盖查询、新增、编辑和删除。
* 依赖:maintenanceRecord.api、maintenanceLedger.api、PaginationBar、useMessage。
* 逻辑:列表 Tab 按设备编号/名称和维修状态筛选;配置 Tab 复用同一表单新增或修改记录。
*/
import { computed, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
import {
createMaintenanceRecord,
deleteMaintenanceRecord,
exportMaintenanceRecords,
listMaintenanceRecords,
updateMaintenanceRecord,
} from '@/features/maintenance/api/maintenanceRecord.api';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import type {
MaintenanceRecord,
MaintenanceRecordPayload,
MaintenanceRepairStatus,
} from '@/features/maintenance/types/record.types';
type TabName = 'list' | 'form';
const msg = useMessage();
const { t } = useI18n();
const activeTab = ref<TabName>('list');
const loading = ref(false);
const saving = ref(false);
const deviceLoading = ref(false);
const deletingId = ref<number | null>(null);
const exporting = ref(false);
const records = ref<MaintenanceRecord[]>([]);
const matchedDevice = ref<MaintenanceDevice | null>(null);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const keyword = ref('');
const status = ref('');
const editingId = ref<number | null>(null);
const today = new Date().toISOString().slice(0, 10);
const form = reactive<MaintenanceRecordPayload>({
deviceCode: '',
reportDate: today,
repairCategory: '',
faultDescription: '',
reporter: '',
approver: '',
repairStatus: 'pending',
repairDate: '',
repairUnit: '',
repairer: '',
repairCost: '',
repairHours: '',
repairDescription: '',
sourceOrderNo: '',
});
const statusOptions: Array<{ value: MaintenanceRepairStatus | ''; label: string }> = [
{ value: '', label: 'maintenance.record.status.all' },
{ value: 'pending', label: 'maintenance.record.status.pending' },
{ value: 'processing', label: 'maintenance.record.status.processing' },
{ value: 'done', label: 'maintenance.record.status.done' },
{ value: 'cancelled', label: 'maintenance.record.status.cancelled' },
];
const formTitle = computed(() => t(editingId.value ? 'maintenance.record.formTitle.edit' : 'maintenance.record.formTitle.create'));
/**
* 将维修状态枚举转为中文展示。
* @param value - 后端状态枚举。
* @returns 中文状态文案。
*/
const formatStatus = (value: string): string => {
const option = statusOptions.find((item) => item.value === value);
return option ? t(option.label) : value || '-';
};
/**
* 从表单生成保存 payload,统一裁剪字符串并保留可空日期。
* @returns 保存维修记录入参。
*/
const buildPayload = (): MaintenanceRecordPayload => ({
deviceCode: form.deviceCode.trim(),
reportDate: form.reportDate,
repairCategory: form.repairCategory?.trim(),
faultDescription: form.faultDescription.trim(),
reporter: form.reporter?.trim(),
approver: form.approver?.trim(),
repairStatus: form.repairStatus,
repairDate: form.repairDate || undefined,
repairUnit: form.repairUnit?.trim(),
repairer: form.repairer?.trim(),
repairCost: form.repairCost?.trim(),
repairHours: form.repairHours?.trim(),
repairDescription: form.repairDescription?.trim(),
sourceOrderNo: form.sourceOrderNo?.trim(),
});
/**
* 查询维修记录列表,仅按设备编号/设备名称和状态筛选。
*/
const loadRecords = async (): Promise<void> => {
loading.value = true;
try {
const result = await listMaintenanceRecords({
keyword: keyword.value.trim(),
status: status.value,
page: page.value,
pageSize: pageSize.value,
});
records.value = result.items;
total.value = result.total;
} catch (error: any) {
msg.error(error?.message || t('maintenance.record.messages.loadFailed'));
} finally {
loading.value = false;
}
};
/**
* 导出当前筛选条件下的维修记录 Excel。
*/
const exportRecords = async (): Promise<void> => {
exporting.value = true;
try {
const blob = await exportMaintenanceRecords({
keyword: keyword.value.trim(),
status: status.value,
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `maintenance_records_${new Date().toISOString().slice(0, 10)}.xlsx`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
msg.success(t('maintenance.record.messages.exported'));
} catch (error: any) {
msg.error(error?.message || t('maintenance.record.messages.exportFailed'));
} finally {
exporting.value = false;
}
};
/**
* 查询设备台账快照,帮助管理员确认维修记录归属。
*/
const loadDeviceSnapshot = async (): Promise<void> => {
const code = form.deviceCode.trim();
matchedDevice.value = null;
if (!code) return;
deviceLoading.value = true;
try {
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || result.items[0] || null;
} catch (error: any) {
msg.error(error?.message || t('maintenance.record.messages.deviceLoadFailed'));
} finally {
deviceLoading.value = false;
}
};
/**
* 重置表单并进入新增模式。
*/
const startCreate = (): void => {
editingId.value = null;
Object.assign(form, {
deviceCode: '',
reportDate: today,
repairCategory: '',
faultDescription: '',
reporter: '',
approver: '',
repairStatus: 'pending',
repairDate: '',
repairUnit: '',
repairer: '',
repairCost: '',
repairHours: '',
repairDescription: '',
sourceOrderNo: '',
});
matchedDevice.value = null;
activeTab.value = 'form';
};
/**
* 将选中的维修记录带入表单并进入编辑模式。
* @param record - 列表中选中的维修记录。
*/
const startEdit = (record: MaintenanceRecord): void => {
editingId.value = record.id;
Object.assign(form, {
deviceCode: record.deviceCode || '',
reportDate: record.reportDate || today,
repairCategory: record.repairCategory || '',
faultDescription: record.faultDescription || '',
reporter: record.reporter || '',
approver: record.approver || '',
repairStatus: record.repairStatus,
repairDate: record.repairDate || '',
repairUnit: record.repairUnit || '',
repairer: record.repairer || '',
repairCost: record.repairCost || '',
repairHours: record.repairHours || '',
repairDescription: record.repairDescription || '',
sourceOrderNo: record.sourceOrderNo || '',
});
matchedDevice.value = record.deviceCode
? {
id: record.deviceId || 0,
deviceCode: record.deviceCode,
deviceName: record.deviceName || '',
modelSpec: record.modelSpec || '',
installLocation: record.installLocation || '',
deviceStatus: 'in_use',
} as MaintenanceDevice
: null;
activeTab.value = 'form';
};
/**
* 新增或更新维修记录,并回到列表刷新结果。
*/
const saveRecord = async (): Promise<void> => {
const payload = buildPayload();
if (!payload.deviceCode || !payload.reportDate || !payload.faultDescription) {
msg.warning(t('maintenance.record.messages.required'));
return;
}
saving.value = true;
try {
if (editingId.value) {
await updateMaintenanceRecord(editingId.value, payload);
msg.success(t('maintenance.record.messages.updated'));
} else {
await createMaintenanceRecord(payload);
msg.success(t('maintenance.record.messages.created'));
keyword.value = payload.deviceCode;
}
activeTab.value = 'list';
await loadRecords();
} catch (error: any) {
msg.error(error?.message || t('maintenance.record.messages.saveFailed'));
} finally {
saving.value = false;
}
};
/**
* 删除维修记录。
* @param record - 待删除的维修记录。
*/
const removeRecord = async (record: MaintenanceRecord): Promise<void> => {
if (!window.confirm(t('maintenance.record.messages.deleteConfirm', { deviceCode: record.deviceCode }))) return;
deletingId.value = record.id;
try {
await deleteMaintenanceRecord(record.id);
msg.success(t('maintenance.record.messages.deleted'));
await loadRecords();
} catch (error: any) {
msg.error(error?.message || t('maintenance.record.messages.deleteFailed'));
} finally {
deletingId.value = null;
}
};
onMounted(loadRecords);
</script>
<template>
<section class="flex h-full min-h-0 flex-col">
<div class="mb-4 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
{{ t('maintenance.record.notice') }}
</div>
<div class="mb-4 flex rounded-xl border border-default bg-muted/30 p-1">
<button
type="button"
class="relative flex-1 cursor-pointer rounded-lg border px-3 py-2 text-sm font-semibold transition-all hover:bg-surface hover:text-brand"
:class="activeTab === 'list' ? 'border-brand-300 bg-surface text-brand shadow-sm after:absolute after:inset-x-6 after:bottom-0 after:h-0.5 after:rounded-full after:bg-brand' : 'border-transparent text-secondary'"
:aria-selected="activeTab === 'list'"
@click="activeTab = 'list'"
>
{{ t('maintenance.record.tabs.list') }}
</button>
<button
type="button"
class="relative flex-1 cursor-pointer rounded-lg border px-3 py-2 text-sm font-semibold transition-all hover:bg-surface hover:text-brand"
:class="activeTab === 'form' ? 'border-brand-300 bg-surface text-brand shadow-sm after:absolute after:inset-x-6 after:bottom-0 after:h-0.5 after:rounded-full after:bg-brand' : 'border-transparent text-secondary'"
:aria-selected="activeTab === 'form'"
@click="activeTab = 'form'"
>
{{ t('maintenance.record.tabs.form') }}
</button>
</div>
<div v-if="activeTab === 'list'" class="flex min-h-0 flex-1 flex-col gap-4">
<div class="flex flex-wrap gap-3">
<input
v-model="keyword"
class="admin-table-filter-input w-full md:w-[360px] lg:w-[420px]"
:placeholder="t('maintenance.record.filters.keywordPlaceholder')"
@keyup.enter="page = 1; loadRecords()"
/>
<select v-model="status" class="admin-table-filter-input w-full md:w-[150px]" @change="page = 1; loadRecords()">
<option v-for="item in statusOptions" :key="item.value || 'all'" :value="item.value">
{{ t(item.label) }}
</option>
</select>
</div>
<div class="flex flex-wrap gap-2">
<button type="button" class="admin-report-page-btn admin-report-page-btn--active" @click="page = 1; loadRecords()">
{{ t('maintenance.record.actions.search') }}
</button>
<button type="button" class="admin-report-page-btn" @click="startCreate">
{{ t('maintenance.record.actions.create') }}
</button>
<button type="button" class="admin-report-page-btn" :disabled="exporting" @click="exportRecords">
{{ exporting ? t('maintenance.record.actions.exporting') : t('maintenance.record.actions.export') }}
</button>
</div>
<div class="min-h-0 overflow-auto rounded-xl border border-default bg-surface">
<table class="min-w-full text-left text-sm">
<thead class="bg-muted/50 text-secondary">
<tr>
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.modelSpec') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.faultDescription') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.repairer') }}</th>
<th class="px-3 py-2">{{ t('maintenance.record.table.operation') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="loading">
<td colspan="7" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
</tr>
<tr v-else-if="!records.length">
<td colspan="7" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.empty') }}</td>
</tr>
<tr v-for="record in records" v-else :key="record.id" class="border-t border-default">
<td class="px-3 py-2 font-semibold">{{ record.deviceCode }}</td>
<td class="px-3 py-2">{{ record.deviceName || '-' }}</td>
<td class="px-3 py-2">{{ record.modelSpec || '-' }}</td>
<td class="max-w-[260px] truncate px-3 py-2">{{ record.faultDescription }}</td>
<td class="px-3 py-2">{{ formatStatus(record.repairStatus) }}</td>
<td class="px-3 py-2">{{ record.repairer || '-' }}</td>
<td class="px-3 py-2">
<div class="flex gap-2">
<button type="button" class="admin-report-page-btn" @click="startEdit(record)">{{ t('maintenance.record.actions.edit') }}</button>
<button
type="button"
class="admin-report-page-btn"
:disabled="deletingId === record.id"
@click="removeRecord(record)"
>
{{ deletingId === record.id ? t('maintenance.record.actions.deleting') : t('maintenance.record.actions.delete') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<PaginationBar
v-model:page="page"
v-model:page-size="pageSize"
:total="total"
@update:page="loadRecords"
@update:page-size="loadRecords"
/>
</div>
<form v-else class="min-h-0 flex-1 overflow-auto" @submit.prevent="saveRecord">
<div class="mb-4 flex items-center justify-between">
<h3 class="text-base font-semibold text-primary">{{ formTitle }}</h3>
<button type="button" class="admin-report-page-btn" @click="activeTab = 'list'">{{ t('maintenance.record.actions.backToList') }}</button>
</div>
<div class="grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.deviceCode') }} *
<input
v-model="form.deviceCode"
class="admin-table-filter-input"
:placeholder="t('maintenance.record.placeholder.deviceCode')"
@blur="loadDeviceSnapshot"
@keyup.enter.prevent="loadDeviceSnapshot"
/>
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.reportDate') }} *
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.repairCategory') }}
<input v-model="form.repairCategory" class="admin-table-filter-input" :placeholder="t('maintenance.record.placeholder.repairCategory')" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.repairStatus') }}
<select v-model="form.repairStatus" class="admin-table-filter-input">
<option value="pending">{{ t('maintenance.record.status.pending') }}</option>
<option value="processing">{{ t('maintenance.record.status.processing') }}</option>
<option value="done">{{ t('maintenance.record.status.done') }}</option>
<option value="cancelled">{{ t('maintenance.record.status.cancelled') }}</option>
</select>
</label>
</div>
<div class="mt-3 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm">
<div v-if="deviceLoading" class="text-secondary">{{ t('maintenance.record.deviceSnapshot.loading') }}</div>
<div v-else-if="matchedDevice" class="grid gap-1 text-secondary">
<div class="font-semibold text-primary">{{ matchedDevice.deviceName }}({{ matchedDevice.deviceCode }})</div>
<div>{{ t('maintenance.record.deviceSnapshot.position') }}:{{ matchedDevice.installLocation || '-' }} | {{ t('maintenance.record.deviceSnapshot.department') }}:{{ matchedDevice.department || '-' }}</div>
<div>{{ t('maintenance.record.deviceSnapshot.responsibleUser') }}:{{ matchedDevice.responsibleUser || '-' }} | {{ t('maintenance.record.deviceSnapshot.status') }}:{{ matchedDevice.deviceStatus }}</div>
</div>
<div v-else class="text-secondary">{{ t('maintenance.record.deviceSnapshot.empty') }}</div>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
{{ t('maintenance.record.fields.faultDescription') }} *
<textarea v-model="form.faultDescription" class="admin-table-filter-input min-h-24" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.reporter') }}
<input v-model="form.reporter" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.approver') }}
<input v-model="form.approver" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.repairDate') }}
<input v-model="form.repairDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.sourceOrderNo') }}
<input v-model="form.sourceOrderNo" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.repairUnit') }}
<input v-model="form.repairUnit" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.repairer') }}
<input v-model="form.repairer" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.repairCost') }}
<input v-model="form.repairCost" class="admin-table-filter-input" :placeholder="t('maintenance.record.placeholder.repairCost')" />
</label>
<label class="grid gap-1 text-sm text-secondary">
{{ t('maintenance.record.fields.repairHours') }}
<input v-model="form.repairHours" class="admin-table-filter-input" :placeholder="t('maintenance.record.placeholder.repairHours')" />
</label>
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
{{ t('maintenance.record.fields.repairDescription') }}
<textarea v-model="form.repairDescription" class="admin-table-filter-input min-h-24" />
</label>
</div>
<div class="sticky bottom-0 mt-5 flex justify-end gap-2 border-t border-default bg-surface py-3">
<button type="button" class="admin-report-page-btn" @click="activeTab = 'list'">{{ t('maintenance.record.actions.cancel') }}</button>
<button type="submit" class="admin-report-page-btn admin-report-page-btn--active" :disabled="saving">
{{ saving ? t('maintenance.record.actions.saving') : t('maintenance.record.actions.save') }}
</button>
</div>
</form>
</section>
</template>
@@ -0,0 +1,316 @@
<script setup lang="ts">
/**
* features/maintenance/components/MaintenanceRecordPanel.vue
* 用途:设备维保助手右侧固定面板中的“新增维修记录”页面。
* 依赖:maintenanceRecord.api、maintenanceLedger.api、useMessage。
* 逻辑:管理员通过按钮进入固定面板后填写维修记录;设备编号失焦时查询台账快照,保存后刷新最近记录用于确认。
*/
import { computed, onMounted, reactive, ref } from 'vue';
import { useMessage } from '@/shared/composables/useMessage';
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
import {
createMaintenanceRecord,
listMaintenanceRecords,
} from '@/features/maintenance/api/maintenanceRecord.api';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import type {
MaintenanceRecord,
MaintenanceRecordPayload,
MaintenanceRepairStatus,
} from '@/features/maintenance/types/record.types';
const msg = useMessage();
const saving = ref(false);
const deviceLoading = ref(false);
const recentLoading = ref(false);
const matchedDevice = ref<MaintenanceDevice | null>(null);
const recentRecords = ref<MaintenanceRecord[]>([]);
const recordKeyword = ref('');
const recordStatus = ref('');
const today = new Date().toISOString().slice(0, 10);
const form = reactive<MaintenanceRecordPayload>({
deviceCode: '',
reportDate: today,
repairCategory: '',
faultDescription: '',
reporter: '',
approver: '',
repairStatus: 'pending',
repairDate: '',
repairUnit: '',
repairer: '',
repairCost: '',
repairHours: '',
repairDescription: '',
sourceOrderNo: '',
});
const statusOptions: Array<{ value: MaintenanceRepairStatus | ''; label: string }> = [
{ value: '', label: '全部状态' },
{ value: 'pending', label: '待维修' },
{ value: 'processing', label: '维修中' },
{ value: 'done', label: '已完成' },
{ value: 'cancelled', label: '已取消' },
];
const selectedStatusLabel = computed(() => {
return statusOptions.find((item) => item.value === form.repairStatus)?.label || form.repairStatus;
});
/**
* 将状态值转换为中文展示。
* @param value - 后端状态枚举。
* @returns 页面展示文案。
*/
const formatStatus = (value: string): string => {
return statusOptions.find((item) => item.value === value)?.label || value || '-';
};
/**
* 从表单状态生成新增维修记录 payload,统一处理空字符串。
* @returns 新增维修记录入参。
*/
const buildPayload = (): MaintenanceRecordPayload => ({
deviceCode: form.deviceCode.trim(),
reportDate: form.reportDate,
repairCategory: form.repairCategory?.trim(),
faultDescription: form.faultDescription.trim(),
reporter: form.reporter?.trim(),
approver: form.approver?.trim(),
repairStatus: form.repairStatus,
repairDate: form.repairDate || undefined,
repairUnit: form.repairUnit?.trim(),
repairer: form.repairer?.trim(),
repairCost: form.repairCost?.trim(),
repairHours: form.repairHours?.trim(),
repairDescription: form.repairDescription?.trim(),
sourceOrderNo: form.sourceOrderNo?.trim(),
});
/**
* 按设备编号查询台账快照,帮助管理员确认记录归属。
* AI 触发时机:当用户输入或修改设备编号后,需要自动带出台账信息时调用。
*/
const loadDeviceSnapshot = async (): Promise<void> => {
const code = form.deviceCode.trim();
matchedDevice.value = null;
if (!code) return;
deviceLoading.value = true;
try {
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || result.items[0] || null;
} catch (error: any) {
msg.error(error?.message || '查询设备台账失败');
} finally {
deviceLoading.value = false;
}
};
/**
* 查询最近维修记录,作为保存后的确认列表和轻量筛选入口。
*/
const loadRecentRecords = async (): Promise<void> => {
recentLoading.value = true;
try {
const result = await listMaintenanceRecords({
keyword: recordKeyword.value.trim(),
status: recordStatus.value,
page: 1,
pageSize: 5,
});
recentRecords.value = result.items;
} catch (error: any) {
msg.error(error?.message || '查询维修记录失败');
} finally {
recentLoading.value = false;
}
};
/**
* 清空维修记录表单,保留默认报修日期。
*/
const resetForm = (): void => {
Object.assign(form, {
deviceCode: '',
reportDate: today,
repairCategory: '',
faultDescription: '',
reporter: '',
approver: '',
repairStatus: 'pending',
repairDate: '',
repairUnit: '',
repairer: '',
repairCost: '',
repairHours: '',
repairDescription: '',
sourceOrderNo: '',
});
matchedDevice.value = null;
};
/**
* 新增维修记录,并刷新最近记录列表。
*/
const saveRecord = async (): Promise<void> => {
const payload = buildPayload();
if (!payload.deviceCode || !payload.reportDate || !payload.faultDescription) {
msg.warning('设备编号、报修日期和故障描述不能为空');
return;
}
saving.value = true;
try {
await createMaintenanceRecord(payload);
msg.success('维修记录已保存');
recordKeyword.value = payload.deviceCode;
resetForm();
await loadRecentRecords();
} catch (error: any) {
msg.error(error?.message || '保存维修记录失败');
} finally {
saving.value = false;
}
};
onMounted(loadRecentRecords);
</script>
<template>
<section class="flex h-full min-h-0 flex-col gap-4">
<form class="min-h-0 flex-1 overflow-auto" @submit.prevent="saveRecord">
<div class="mb-4 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
维修记录为管理员配置入口,查询类问题仍建议通过会话直接提问。
</div>
<div class="grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary">
设备编号 *
<input
v-model="form.deviceCode"
class="admin-table-filter-input"
placeholder="如 EQ-2026-001"
@blur="loadDeviceSnapshot"
@keyup.enter.prevent="loadDeviceSnapshot"
/>
</label>
<label class="grid gap-1 text-sm text-secondary">
报修日期 *
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修类别
<input v-model="form.repairCategory" class="admin-table-filter-input" placeholder="日常维修 / 保养 / 点检" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修状态
<select v-model="form.repairStatus" class="admin-table-filter-input">
<option value="pending">待维修</option>
<option value="processing">维修中</option>
<option value="done">已完成</option>
<option value="cancelled">已取消</option>
</select>
</label>
</div>
<div class="mt-3 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm">
<div v-if="deviceLoading" class="text-secondary">正在查询设备台账...</div>
<div v-else-if="matchedDevice" class="grid gap-1 text-secondary">
<div class="font-semibold text-primary">{{ matchedDevice.deviceName }}({{ matchedDevice.deviceCode }})</div>
<div>位置:{{ matchedDevice.installLocation || '-' }} | 部门:{{ matchedDevice.department || '-' }}</div>
<div>负责人:{{ matchedDevice.responsibleUser || '-' }} | 状态:{{ matchedDevice.deviceStatus }}</div>
</div>
<div v-else class="text-secondary">输入设备编号后可自动匹配设备台账快照。</div>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2">
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
故障描述 *
<textarea v-model="form.faultDescription" class="admin-table-filter-input min-h-24" />
</label>
<label class="grid gap-1 text-sm text-secondary">
报修人
<input v-model="form.reporter" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
审批人
<input v-model="form.approver" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修日期
<input v-model="form.repairDate" type="date" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修单位
<input v-model="form.repairUnit" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修人
<input v-model="form.repairer" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
来源工单号
<input v-model="form.sourceOrderNo" class="admin-table-filter-input" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修费用
<input v-model="form.repairCost" class="admin-table-filter-input" placeholder="如 1200.00" />
</label>
<label class="grid gap-1 text-sm text-secondary">
维修工时
<input v-model="form.repairHours" class="admin-table-filter-input" placeholder="如 3.5h" />
</label>
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
维修说明
<textarea v-model="form.repairDescription" class="admin-table-filter-input min-h-24" />
</label>
</div>
<div class="sticky bottom-0 mt-5 flex justify-end gap-2 border-t border-default bg-surface py-3">
<button type="button" class="admin-report-page-btn" @click="resetForm">清空</button>
<button
type="submit"
class="admin-report-page-btn admin-report-page-btn--active"
:disabled="saving"
>
{{ saving ? '保存中...' : `保存为${selectedStatusLabel}` }}
</button>
</div>
</form>
<div class="border-t border-default pt-4">
<div class="mb-3 flex items-center justify-between gap-2">
<h3 class="text-sm font-semibold text-primary">最近维修记录</h3>
<button type="button" class="admin-report-page-btn" @click="loadRecentRecords">刷新</button>
</div>
<div class="mb-3 grid gap-2 md:grid-cols-[1fr_120px_72px]">
<input v-model="recordKeyword" class="admin-table-filter-input" placeholder="筛选设备编号、故障、维修人" />
<select v-model="recordStatus" class="admin-table-filter-input">
<option v-for="item in statusOptions" :key="item.value || 'all'" :value="item.value">
{{ item.label }}
</option>
</select>
<button type="button" class="admin-report-page-btn admin-report-page-btn--active" @click="loadRecentRecords">
查询
</button>
</div>
<div class="max-h-56 overflow-auto rounded-xl border border-default bg-surface">
<div v-if="recentLoading" class="px-3 py-6 text-center text-sm text-secondary">加载中...</div>
<div v-else-if="!recentRecords.length" class="px-3 py-6 text-center text-sm text-secondary">暂无维修记录</div>
<div
v-for="record in recentRecords"
v-else
:key="record.id"
class="border-t border-default px-3 py-2 text-sm first:border-t-0"
>
<div class="flex items-center justify-between gap-2">
<span class="font-semibold text-primary">{{ record.deviceCode }} {{ record.deviceName || '' }}</span>
<span class="text-xs text-secondary">{{ formatStatus(record.repairStatus) }}</span>
</div>
<div class="mt-1 text-secondary">{{ record.reportDate }} | {{ record.faultDescription }}</div>
</div>
</div>
</div>
</section>
</template>
@@ -0,0 +1,64 @@
/**
* features/maintenance/types/ledger.types.ts
* 用途:设备维保台账配置的前端类型定义。
* 依赖:无运行时依赖。
* 逻辑:API 层、右侧固定面板和后续 Agent 结果卡片共享这些类型,保持字段一致。
*/
export type MaintenanceDeviceStatus = 'in_use' | 'disabled' | 'scrapped' | 'sold';
export interface MaintenanceDevice {
id: number;
deviceCode: string;
deviceName: string;
modelSpec?: string | null;
department?: string | null;
installLocation?: string | null;
deviceStatus: MaintenanceDeviceStatus;
manufacturer?: string | null;
entryDate?: string | null;
productionDate?: string | null;
startDate?: string | null;
responsibleUser?: string | null;
maintenanceCycle?: string | null;
originalValue?: number | null;
residualValue?: number | null;
accountSet?: string | null;
remark?: string | null;
createdAt?: string | null;
updatedAt?: string | null;
}
export interface MaintenanceDevicePayload {
deviceCode: string;
deviceName: string;
modelSpec?: string;
department?: string;
installLocation?: string;
deviceStatus: MaintenanceDeviceStatus;
manufacturer?: string;
entryDate?: string;
productionDate?: string;
startDate?: string;
responsibleUser?: string;
maintenanceCycle?: string;
originalValue?: string;
residualValue?: string;
accountSet?: string;
remark?: string;
}
export interface MaintenanceDeviceListResult {
items: MaintenanceDevice[];
total: number;
page: number;
pageSize: number;
}
export interface MaintenanceDeviceImportResult {
total: number;
created: number;
updated: number;
failed: number;
errors: Array<{ row: number; message: string }>;
}
@@ -0,0 +1,56 @@
/**
* features/maintenance/types/record.types.ts
* 用途:设备维保助手的维修记录前端类型定义。
* 依赖:无运行时依赖。
* 逻辑:API 层、右侧固定面板和后续 Agent 查询结果卡片共享这些字段,保持前后端命名一致。
*/
export type MaintenanceRepairStatus = 'pending' | 'processing' | 'done' | 'cancelled';
export interface MaintenanceRecord {
id: number;
deviceId?: number | null;
deviceCode: string;
deviceName?: string | null;
modelSpec?: string | null;
installLocation?: string | null;
reportDate: string;
repairCategory?: string | null;
faultDescription: string;
reporter?: string | null;
approver?: string | null;
repairStatus: MaintenanceRepairStatus;
repairDate?: string | null;
repairUnit?: string | null;
repairer?: string | null;
repairCost?: string | null;
repairHours?: string | null;
repairDescription?: string | null;
sourceOrderNo?: string | null;
createdAt?: string | null;
updatedAt?: string | null;
}
export interface MaintenanceRecordPayload {
deviceCode: string;
reportDate: string;
repairCategory?: string;
faultDescription: string;
reporter?: string;
approver?: string;
repairStatus: MaintenanceRepairStatus;
repairDate?: string;
repairUnit?: string;
repairer?: string;
repairCost?: string;
repairHours?: string;
repairDescription?: string;
sourceOrderNo?: string;
}
export interface MaintenanceRecordListResult {
items: MaintenanceRecord[];
total: number;
page: number;
pageSize: number;
}
+63
View File
@@ -28,6 +28,13 @@
"reports": "Data Reports",
"schedules": "Schedule Management"
},
"platformApps": {
"guideUsage": "Guide Usage",
"generalGuide": "General Guide",
"trainingVideo": "Employee Training Video",
"trainingExamPdf": "Employee Training Exam PDF",
"guideUsageHint": "The training workspace will prioritize guides marked as employee training video or employee training exam PDF."
},
"dash": {
"activeAgents": "Active Agents",
"totalUsers": "Total Users",
@@ -85,6 +92,9 @@
"email": "Email",
"department": "Department",
"role": "Role",
"featurePermissions": "Feature Permissions",
"trainingHrManage": "Training HR Admin",
"trainingHrManageHint": "Allows this user to open the employee training agent HR Management view for stats, filtering, and Excel export.",
"password": "Password",
"passwordHint": "(leave blank to keep)",
"noAgents": "No agents available."
@@ -203,6 +213,58 @@
"pollInterval": "Progress refresh interval (seconds)",
"lockInput": "Prevent sending new messages while a task is running",
"scheduleTaskRequired": "Please select a linked schedule first"
},
"training": {
"title": "Employee Training Configuration",
"subtitle": "Configure the training workspace pass line, review points, and question bank. After saving, the employee training page will read this backend content first.",
"enable": "Enable employee training workspace",
"enableHint": "When enabled, this agent uses the training flow of video, review, exam, and settlement.",
"disabledHint": "When disabled, this agent will not show the employee training workspace. Existing training content remains stored in the backend.",
"passScore": "Passing score",
"passScoreHint": "The frontend exam and result copy both use this percentage score as the pass line.",
"summaryPoints": "Review points",
"summaryPointsPlaceholder": "One item per line, for example: Salary is paid on the 15th of each month",
"summaryChecklist": "Must know before the exam",
"summaryChecklistPlaceholder": "One item per line, for example: Scores below 90 require a retake",
"questionBank": "Question bank",
"questionHint": "Supports single choice and true or false questions. Employees will use the updated bank immediately after saving.",
"emptyQuestionBank": "No question bank configured yet. The employee view will fall back to the default bank.",
"importFromPdf": "Import From Exam PDF",
"importingPdf": "Parsing PDF...",
"importPdfHint": "The system will parse the uploaded exam PDF \"{fileName}\" first. You can still review and edit the result manually after import.",
"importPdfMissing": "This agent does not have any uploaded guide marked as Employee Training Exam PDF yet. Please upload it first in Platform App Guides.",
"importPdfCreateFirst": "Please save this agent first, then import the question bank from an uploaded exam PDF.",
"importPdfAgentRequired": "Please save this agent first before importing the exam PDF",
"importPdfSuccess": "Imported {count} questions from \"{fileName}\"",
"importPdfPartialSuccess": "Imported {count} questions. These question numbers were skipped: {skipped}",
"importPdfOcrUsed": "This import was completed through OCR. Please review the prompts, options, and answers carefully.",
"importPdfOcrFallback": "Native PDF text parsing failed, so the import automatically fell back to OCR. Please review the prompts, options, and answers carefully.",
"importPdfWarnings": "Parsing notes: {warnings}",
"addQuestion": "Add question",
"removeQuestion": "Remove question",
"questionCardTitle": "Question {index}",
"questionId": "Question ID",
"questionIdPlaceholder": "For example: q1",
"questionType": "Question type",
"single": "Single choice",
"boolean": "True or false",
"correctAnswer": "Correct answer",
"booleanTrue": "True",
"booleanFalse": "False",
"questionPrompt": "Prompt",
"questionPromptPlaceholder": "Enter the question content",
"questionExplanation": "Explanation",
"questionExplanationPlaceholder": "Enter the explanation shown to the learner after answering",
"questionOptions": "Options",
"addOption": "Add option",
"optionLabel": "Option {label}",
"optionPlaceholder": "Enter option text",
"validation": {
"questionRequired": "Please configure at least one training question",
"questionPromptRequired": "Question {index} prompt is required",
"questionSingleOptions": "Question {index} needs at least 2 valid options",
"questionAnswerRequired": "Please choose the correct answer for question {index}"
}
}
},
"question": {
@@ -1023,6 +1085,7 @@
},
"role": {
"user": "User",
"hr": "HR",
"admin": "Admin",
"guest": "Guest"
},
+27 -9
View File
@@ -471,8 +471,8 @@
}
},
"training": {
"badge": "Onboarding Training Workspace",
"title": "Onboarding Training Agent",
"badge": "Employee Training Workspace",
"title": "",
"subtitle": "Complete video learning, knowledge review, one-question-at-a-time testing, and HR reporting in the same chat page.",
"tabs": {
"learner": "Learner",
@@ -482,7 +482,8 @@
"syncLearnerToChat": "Sync learner context to chat",
"syncHrToChat": "Sync HR filters to chat",
"expandWorkspace": "Expand workspace",
"collapseWorkspace": "Collapse workspace"
"collapseWorkspace": "Collapse Workspace",
"viewExamPdf": "View Exam PDF"
},
"steps": {
"video": "Watch Video",
@@ -514,7 +515,7 @@
"title": "Step 3: One-question-at-a-time exam",
"questionCounter": "Question {current} / {total}",
"currentScore": "Current score: {score}",
"passLine": "Pass line: 90 points",
"passLine": "Pass line: {passScore} points",
"correctFeedback": "Correct. Move on to the next question.",
"wrongFeedback": "Incorrect. The correct answer is now shown.",
"selectedAnswer": "Your answer: {answer}",
@@ -527,8 +528,8 @@
"failedTag": "Retake required",
"passTitle": "Congratulations, you passed the onboarding exam",
"failTitle": "This attempt did not meet the requirement",
"passDescription": "The frontend pass-state interaction is complete. Once the backend is connected, it can write training records and the completion date.",
"failDescription": "According to HR rules, any score below 90 requires a full retake until the learner passes.",
"passDescription": "You passed this exam successfully. The score is automatically synced to the HR console and saved into the training record.",
"failDescription": "According to HR rules, any score below {passScore} requires a full retake until the learner passes.",
"scoreLabel": "Final score",
"attemptsLabel": "Attempts",
"correctCount": "Correct answers",
@@ -545,9 +546,9 @@
},
"rules": {
"title": "Exam rules",
"rule1": "There are 20 questions, 5 points each, with a full score of 100.",
"rule1": "There are {total} questions, and the system calculates the result on a 100-point scale.",
"rule2": "The system enforces one question, one answer, one feedback. Wrong answers show the correct answer immediately.",
"rule3": "Any score below 90 is treated as failed and requires a retake.",
"rule3": "Any score below {passScore} is treated as failed and requires a retake.",
"rule4": "HR can view statistics and export Excel from the same chat page."
},
"hr": {
@@ -594,7 +595,24 @@
"afterSummary": "I finished reviewing the knowledge points. Please switch to exam mode and ask the first question.",
"afterPass": "I passed the onboarding training exam with a score of {score}. Please help me generate a short completion summary.",
"afterFail": "I scored {score} in the onboarding training exam and did not pass. Please summarize the weak points and prepare a retake reminder.",
"examInProgress": "I am taking the onboarding training exam and am currently on question {index}/{total}. Please stay in proctor mode and continue."
"examInProgress": "I am taking the onboarding training exam and am currently on question {index}/{total}. Please stay in proctor mode and continue.",
"assistantVideoIntro": "👋 Welcome aboard! I am your onboarding training assistant. Today's training has three steps: watch the video ➡️ review the key knowledge points ➡️ take the quiz ({passScore} points to pass).\n\n▶️ Please start with the onboarding training video. After watching it, move on to the knowledge review.",
"assistantSummaryIntro": "Great. Based on the video, I pulled together the key knowledge points you are most likely to be tested on:",
"assistantSummaryReady": "Ready for the challenge? Click Start Exam directly or reply \"Start Exam\" in the chat.",
"assistantQuestionSingleType": "Single choice",
"assistantQuestionBooleanType": "True or false",
"assistantQuestionReplyHint": "Reply with the option or the answer text directly.",
"assistantResultPass": "🎉 **Congratulations!** Your final score is **{score}**. You passed the onboarding assessment, and your score has been synced to HR automatically.",
"assistantResultFail": "📊 **Exam finished!** Your final score is **{score}**. The passing line is {passScore}. Reply \"Retake Exam\" to try again.",
"startExamCommand": "Start Exam",
"restartExamCommand": "Retake Exam"
},
"errors": {
"persistTitle": "Training record save failed",
"persistBody": "The current exam result has not been written to the database, so the HR console and statistics will not update",
"loadTitle": "Training record load failed",
"loadBody": "The training record cannot be loaded from the database right now, so the page may not reflect the latest result",
"questionBankEmpty": "The training question bank is empty. Please maintain it first in the Agent configuration."
},
"summaryPoints": [
"Salary is paid on the 15th of each month, and attendance or leave requests must go through OA.",
+184
View File
@@ -0,0 +1,184 @@
{
"ledger": {
"notice": "This page manages the equipment ledger.",
"tabs": {
"list": "Equipment List",
"form": "Equipment Config"
},
"status": {
"all": "All Statuses",
"inUse": "In Use",
"disabled": "Disabled",
"scrapped": "Scrapped",
"sold": "Sold"
},
"formTitle": {
"create": "Add Equipment",
"edit": "Edit Equipment"
},
"actions": {
"search": "Search",
"create": "Add Equipment",
"downloadTemplate": "Download Template",
"importExcel": "Import Excel",
"importing": "Importing...",
"edit": "Edit",
"backToList": "Back to List",
"cancel": "Cancel",
"save": "Save",
"saving": "Saving..."
},
"filters": {
"keywordPlaceholder": "Search equipment code or name"
},
"table": {
"deviceCode": "Equipment Code",
"deviceName": "Equipment Name",
"modelSpec": "Model/Spec",
"manufacturer": "Vendor",
"status": "Status",
"operation": "Actions",
"loading": "Loading...",
"empty": "No equipment"
},
"fields": {
"deviceCode": "Equipment Code",
"deviceName": "Equipment Name",
"modelSpec": "Model/Spec",
"department": "Department",
"devicePosition": "Equipment Position",
"deviceStatus": "Equipment Status",
"manufacturer": "Manufacturer",
"responsibleUser": "Responsible Person",
"entryDate": "Entry Date",
"productionDate": "Production Date",
"startDate": "Start Date",
"maintenanceCycle": "Maintenance Cycle",
"originalValue": "Original Value",
"residualValue": "Residual Value",
"accountSet": "Account Set",
"remark": "Remark"
},
"placeholder": {
"maintenanceCycle": "On demand / Monthly inspection"
},
"messages": {
"required": "Equipment code and name are required",
"saved": "Equipment ledger saved",
"saveFailed": "Failed to save equipment ledger",
"loadFailed": "Failed to load equipment ledger",
"invalidFormat": "Please upload a .xlsx equipment ledger template",
"fileTooLarge": "The equipment ledger file cannot exceed 10MB",
"importDone": "Equipment ledger import completed",
"importFailed": "Failed to import equipment ledger"
},
"importResult": "Import result: {total} rows, {created} created, {updated} updated, {failed} failed.",
"importErrorRow": "Row {row}: {message}"
},
"panel": {
"recordTitle": "Maintenance Records",
"ledgerTitle": "Ledger Config",
"adminOnly": "Admin actions: asset admins / maintenance supervisors only",
"resizeTitle": "Drag to resize",
"ledgerSubtitle": "Equipment List / Equipment Config",
"recordSubtitle": "Record List / Record Config",
"fullscreen": "Fullscreen",
"exitFullscreen": "Exit fullscreen",
"close": "Close"
},
"record": {
"notice": "Maintenance records are for administrators to maintain repair requests, handling, costs, and labor hours. General queries can still be completed in chat.",
"tabs": {
"list": "Record List",
"form": "Record Config"
},
"status": {
"all": "All Statuses",
"pending": "Pending",
"processing": "In Repair",
"done": "Completed",
"cancelled": "Cancelled"
},
"formTitle": {
"create": "Add Maintenance Record",
"edit": "Edit Maintenance Record"
},
"actions": {
"search": "Search",
"create": "Add Record",
"export": "Export",
"exporting": "Exporting...",
"edit": "Edit",
"delete": "Delete",
"deleting": "Deleting...",
"backToList": "Back to List",
"cancel": "Cancel",
"save": "Save Record",
"saving": "Saving..."
},
"filters": {
"keywordPlaceholder": "Search equipment code or name"
},
"table": {
"deviceCode": "Equipment Code",
"deviceName": "Equipment Name",
"modelSpec": "Model/Spec",
"faultDescription": "Fault Description",
"status": "Status",
"repairer": "Repairer",
"operation": "Actions",
"loading": "Loading...",
"empty": "No maintenance records"
},
"fields": {
"deviceCode": "Equipment Code",
"reportDate": "Report Date",
"repairCategory": "Repair Category",
"repairStatus": "Repair Status",
"faultDescription": "Fault Description",
"reporter": "Reporter",
"approver": "Approver",
"repairDate": "Repair Date",
"sourceOrderNo": "Source Work Order No.",
"repairUnit": "Repair Unit",
"repairer": "Repairer",
"repairCost": "Repair Cost",
"repairHours": "Repair Hours",
"repairDescription": "Repair Notes"
},
"placeholder": {
"deviceCode": "e.g. EQ-2026-001",
"repairCategory": "Daily repair / Maintenance / Inspection",
"repairCost": "e.g. 1200.00",
"repairHours": "e.g. 3.5h"
},
"deviceSnapshot": {
"loading": "Querying equipment ledger...",
"position": "Position",
"department": "Department",
"responsibleUser": "Responsible Person",
"status": "Status",
"empty": "Enter an equipment code to match an equipment ledger snapshot automatically."
},
"messages": {
"loadFailed": "Failed to query maintenance records",
"exported": "Maintenance records exported",
"exportFailed": "Failed to export maintenance records",
"deviceLoadFailed": "Failed to query equipment ledger",
"required": "Equipment code, report date, and fault description are required",
"updated": "Maintenance record updated",
"created": "Maintenance record added",
"saveFailed": "Failed to save maintenance record",
"deleteConfirm": "Delete the maintenance record for {deviceCode}?",
"deleted": "Maintenance record deleted",
"deleteFailed": "Failed to delete maintenance record"
}
},
"chat": {
"deviceLedgerInfo": "Equipment Ledger Info",
"matched": "Matched",
"recentRecords": "Recent maintenance records ({count})",
"viewRepairHistory": "View Repair History",
"addRepairRecord": "Add Repair Record"
}
}
+8
View File
@@ -50,6 +50,10 @@ import enTheme from './en/theme.json';
import zhCNTheme from './zh-CN/theme.json';
import zhTWTheme from './zh-TW/theme.json';
import thTheme from './th/theme.json';
import enMaintenance from './en/maintenance.json';
import zhCNMaintenance from './zh-CN/maintenance.json';
import zhTWMaintenance from './zh-TW/maintenance.json';
import thMaintenance from './th/maintenance.json';
/** 已外置的 locale 域模块;auth / kb 展平至顶层以匹配原有键路径 */
const externalModules: Record<string, Record<string, unknown>> = {
@@ -66,6 +70,7 @@ const externalModules: Record<string, Record<string, unknown>> = {
profile: enProfile,
feedback: enFeedback,
theme: enTheme,
maintenance: enMaintenance,
},
'zh-CN': {
errors: zhCNErrors,
@@ -80,6 +85,7 @@ const externalModules: Record<string, Record<string, unknown>> = {
profile: zhCNProfile,
feedback: zhCNFeedback,
theme: zhCNTheme,
maintenance: zhCNMaintenance,
},
'zh-TW': {
errors: zhTWErrors,
@@ -94,6 +100,7 @@ const externalModules: Record<string, Record<string, unknown>> = {
profile: zhTWProfile,
feedback: zhTWFeedback,
theme: zhTWTheme,
maintenance: zhTWMaintenance,
},
th: {
errors: thErrors,
@@ -108,6 +115,7 @@ const externalModules: Record<string, Record<string, unknown>> = {
profile: thProfile,
feedback: thFeedback,
theme: thTheme,
maintenance: thMaintenance,
},
};
+63
View File
@@ -28,6 +28,13 @@
"reports": "รายงานข้อมูล",
"schedules": "Schedule Management"
},
"platformApps": {
"guideUsage": "ประเภทการใช้งานเอกสาร",
"generalGuide": "คู่มือทั่วไป",
"trainingVideo": "วิดีโออบรมพนักงาน",
"trainingExamPdf": "PDF ข้อสอบอบรมพนักงาน",
"guideUsageHint": "พื้นที่อบรมจะให้ความสำคัญกับเอกสารที่ทำเครื่องหมายเป็นวิดีโออบรมพนักงานหรือ PDF ข้อสอบอบรมพนักงานก่อน"
},
"dash": {
"activeAgents": "ตัวแทนที่ใช้งานอยู่",
"totalUsers": "ผู้ใช้ทั้งหมด",
@@ -85,6 +92,9 @@
"email": "อีเมล",
"department": "แผนก",
"role": "บทบาท",
"featurePermissions": "สิทธิ์ฟีเจอร์",
"trainingHrManage": "จัดการ HR การฝึกอบรม",
"trainingHrManageHint": "เมื่อเปิดแล้ว ผู้ใช้นี้จะเข้าใช้มุมมอง HR 管理 ใน employee training agent เพื่อดูสถิติ คัดกรองข้อมูล และส่งออก Excel ได้",
"password": "รหัสผ่าน",
"passwordHint": "(เว้นว่างไว้หากไม่ต้องการเปลี่ยน)",
"noAgents": "ไม่มีตัวแทนที่ใช้ได้"
@@ -203,6 +213,58 @@
"pollInterval": "ช่วงรีเฟรชความคืบหน้า (วินาที)",
"lockInput": "ห้ามส่งข้อความใหม่ขณะงานกำลังทำงาน",
"scheduleTaskRequired": "โปรดเลือกตารางงานที่เชื่อมก่อน"
},
"training": {
"title": "การตั้งค่าการอบรมพนักงาน",
"subtitle": "กำหนดคะแนนผ่าน ประเด็นทบทวน และคลังข้อสอบของ workspace การอบรม หลังบันทึกแล้ว หน้าการอบรมพนักงานจะอ่านค่าจาก backend นี้ก่อน",
"enable": "เปิดใช้ workspace การอบรมพนักงาน",
"enableHint": "เมื่อเปิดใช้ Agent นี้จะใช้ลำดับวิดีโอ ทบทวน สอบ และสรุปผล",
"disabledHint": "เมื่อปิดใช้ Agent นี้จะไม่แสดง workspace การอบรมพนักงาน แต่ข้อมูลการอบรมที่กรอกไว้จะยังคงอยู่ใน backend",
"passScore": "คะแนนผ่าน",
"passScoreHint": "ข้อสอบหน้าเว็บและข้อความผลลัพธ์จะใช้คะแนนเปอร์เซ็นต์นี้เป็นเกณฑ์ผ่าน",
"summaryPoints": "ประเด็นทบทวน",
"summaryPointsPlaceholder": "หนึ่งบรรทัดต่อหนึ่งข้อ เช่น เงินเดือนจ่ายทุกวันที่ 15",
"summaryChecklist": "สิ่งที่ต้องรู้ก่อนสอบ",
"summaryChecklistPlaceholder": "หนึ่งบรรทัดต่อหนึ่งข้อ เช่น คะแนนต่ำกว่า 90 ต้องสอบใหม่",
"questionBank": "คลังข้อสอบ",
"questionHint": "รองรับข้อสอบแบบปรนัยและถูกหรือผิด หลังบันทึกแล้วพนักงานจะใช้ชุดข้อสอบใหม่นี้ทันที",
"emptyQuestionBank": "ยังไม่ได้ตั้งค่าคลังข้อสอบ ฝั่งพนักงานจะใช้คลังข้อสอบเริ่มต้นแทน",
"importFromPdf": "นำเข้าจาก PDF ข้อสอบ",
"importingPdf": "กำลังแปลง PDF...",
"importPdfHint": "ระบบจะใช้ไฟล์ PDF ข้อสอบ \"{fileName}\" ที่อัปโหลดไว้เพื่อแปลงเป็นคลังข้อสอบก่อน และยังแก้ไขต่อด้วยมือได้",
"importPdfMissing": "Agent นี้ยังไม่มีไฟล์ที่ถูกทำเครื่องหมายเป็น PDF ข้อสอบอบรมพนักงาน กรุณาอัปโหลดก่อนในหน้าคู่มือแอป",
"importPdfCreateFirst": "กรุณาบันทึก Agent นี้ก่อน แล้วจึงนำเข้าคลังข้อสอบจาก PDF ที่อัปโหลดไว้",
"importPdfAgentRequired": "กรุณาบันทึก Agent นี้ก่อน แล้วจึงนำเข้า PDF ข้อสอบ",
"importPdfSuccess": "นำเข้า {count} ข้อจาก \"{fileName}\" แล้ว",
"importPdfPartialSuccess": "นำเข้าได้ {count} ข้อ และข้อต่อไปนี้ไม่สามารถแปลงได้: {skipped}",
"importPdfOcrUsed": "การนำเข้าครั้งนี้เสร็จสิ้นด้วย OCR กรุณาตรวจทานโจทย์ ตัวเลือก และคำตอบอย่างละเอียด",
"importPdfOcrFallback": "การแยกข้อความจาก PDF แบบปกติล้มเหลว ระบบจึงสลับไปใช้ OCR อัตโนมัติ กรุณาตรวจทานโจทย์ ตัวเลือก และคำตอบอย่างละเอียด",
"importPdfWarnings": "หมายเหตุการแปลง: {warnings}",
"addQuestion": "เพิ่มข้อสอบ",
"removeQuestion": "ลบข้อสอบ",
"questionCardTitle": "ข้อสอบ {index}",
"questionId": "รหัสข้อสอบ",
"questionIdPlaceholder": "เช่น q1",
"questionType": "ประเภทข้อสอบ",
"single": "ปรนัย",
"boolean": "ถูกหรือผิด",
"correctAnswer": "คำตอบที่ถูกต้อง",
"booleanTrue": "ถูก",
"booleanFalse": "ผิด",
"questionPrompt": "คำถาม",
"questionPromptPlaceholder": "กรอกข้อความคำถาม",
"questionExplanation": "คำอธิบาย",
"questionExplanationPlaceholder": "กรอกคำอธิบายที่จะแสดงให้พนักงานหลังตอบ",
"questionOptions": "ตัวเลือก",
"addOption": "เพิ่มตัวเลือก",
"optionLabel": "ตัวเลือก {label}",
"optionPlaceholder": "กรอกข้อความตัวเลือก",
"validation": {
"questionRequired": "กรุณาตั้งค่าข้อสอบการอบรมอย่างน้อย 1 ข้อ",
"questionPromptRequired": "ข้อ {index} ต้องกรอกคำถาม",
"questionSingleOptions": "ข้อ {index} ต้องมีตัวเลือกที่ใช้ได้อย่างน้อย 2 ตัวเลือก",
"questionAnswerRequired": "กรุณาเลือกคำตอบที่ถูกต้องของข้อ {index}"
}
}
},
"question": {
@@ -882,6 +944,7 @@
},
"role": {
"user": "ผู้ใช้ทั่วไป",
"hr": "HR",
"admin": "ผู้ดูแลระบบ",
"guest": "ผู้เยี่ยมชม"
},
+27 -9
View File
@@ -471,8 +471,8 @@
}
},
"training": {
"badge": "พื้นที่อบรมพนักงานใหม่",
"title": "Onboarding Training Agent",
"badge": "พื้นที่อบรมพนักงาน",
"title": "",
"subtitle": "ทำวิดีโอเรียนรู้ ทบทวนความรู้ สอบทีละข้อ และดูสถิติ HR ได้ในหน้าแชตเดียวกัน",
"tabs": {
"learner": "ผู้เรียน",
@@ -482,7 +482,8 @@
"syncLearnerToChat": "ส่งบริบทผู้เรียนเข้าแชต",
"syncHrToChat": "ส่งตัวกรอง HR เข้าแชต",
"expandWorkspace": "ขยายพื้นที่ทำงาน",
"collapseWorkspace": "ย่อพื้นที่ทำงาน"
"collapseWorkspace": "ย่อพื้นที่ทำงาน",
"viewExamPdf": "ดู PDF ข้อสอบ"
},
"steps": {
"video": "ดูวิดีโอ",
@@ -514,7 +515,7 @@
"title": "ขั้นตอน 3: สอบทีละข้อ",
"questionCounter": "ข้อ {current} / {total}",
"currentScore": "คะแนนปัจจุบัน: {score}",
"passLine": "ผ่านเมื่อได้ 90 คะแนน",
"passLine": "เกณฑ์ผ่าน: {passScore} คะแนน",
"correctFeedback": "ตอบถูก ไปข้อถัดไปได้",
"wrongFeedback": "ตอบผิด ระบบแสดงคำตอบที่ถูกต้องแล้ว",
"selectedAnswer": "คำตอบของคุณ: {answer}",
@@ -527,8 +528,8 @@
"failedTag": "ต้องสอบใหม่",
"passTitle": "ยินดีด้วย คุณผ่านการสอบอบรมพนักงานใหม่แล้ว",
"failTitle": "การสอบครั้งนี้ยังไม่ผ่านเกณฑ์",
"passDescription": "ฝั่งหน้าเว็บรองรับสถานะผ่านแล้ว และสามารถเชื่อมต่อหลังบ้านเพื่อบันทึกผลได้ในขั้นถัดไป",
"failDescription": "ตามกฎของ HR หากได้ต่ำกว่า 90 คะแนน ต้องสอบใหม่จนกว่าจะผ่าน",
"passDescription": "คุณผ่านการสอบครั้งนี้แล้ว ระบบจะซิงก์คะแนนไปยังหน้าจอ HR และบันทึกลงประวัติการอบรมโดยอัตโนมัติ",
"failDescription": "ตามกฎของ HR หากได้ต่ำกว่า {passScore} คะแนน ต้องสอบใหม่จนกว่าจะผ่าน",
"scoreLabel": "คะแนนสุดท้าย",
"attemptsLabel": "จำนวนครั้งที่สอบ",
"correctCount": "จำนวนข้อที่ถูก",
@@ -545,9 +546,9 @@
},
"rules": {
"title": "กติกาการสอบ",
"rule1": "มีทั้งหมด 20 ข้อ ข้อละ 5 คะแนน เต็ม 100 คะแนน",
"rule1": "มีทั้งหมด {total} ข้อ และระบบจะคำนวณผลสอบบนสเกล 100 คะแนน",
"rule2": "ระบบทำงานแบบหนึ่งข้อหนึ่งคำตอบหนึ่งฟีดแบ็ก และจะแสดงคำตอบที่ถูกเมื่อผู้ใช้ตอบผิด",
"rule3": "หากได้ต่ำกว่า 90 คะแนน ถือว่าไม่ผ่านและต้องสอบใหม่",
"rule3": "หากได้ต่ำกว่า {passScore} คะแนน ถือว่าไม่ผ่านและต้องสอบใหม่",
"rule4": "HR สามารถดูสถิติและส่งออก Excel ได้จากหน้าแชตเดียวกัน"
},
"hr": {
@@ -594,7 +595,24 @@
"afterSummary": "ฉันทบทวนความรู้เสร็จแล้ว โปรดเริ่มโหมดสอบและถามข้อแรก",
"afterPass": "ฉันผ่านการสอบอบรมพนักงานใหม่ด้วยคะแนน {score} โปรดช่วยสรุปการอบรมให้สั้น ๆ",
"afterFail": "ฉันได้คะแนน {score} ในการสอบอบรมพนักงานใหม่และยังไม่ผ่าน โปรดสรุปจุดอ่อนและเตือนให้สอบใหม่",
"examInProgress": "ฉันกำลังสอบอบรมพนักงานใหม่ ตอนนี้อยู่ที่ข้อ {index}/{total} โปรดทำหน้าที่เป็นผู้คุมสอบและถามต่อ"
"examInProgress": "ฉันกำลังสอบอบรมพนักงานใหม่ ตอนนี้อยู่ที่ข้อ {index}/{total} โปรดทำหน้าที่เป็นผู้คุมสอบและถามต่อ",
"assistantVideoIntro": "👋 ยินดีต้อนรับสู่บริษัท! ฉันคือผู้ช่วยอบรมพนักงานใหม่ของคุณ วันนี้มี 3 ขั้นตอนคือ ดูวิดีโอ ➡️ ทบทวนความรู้ ➡️ ทำแบบทดสอบ (ผ่านที่ {passScore} คะแนน)\n\n▶️ โปรดเริ่มจากการดูวิดีโออบรมพนักงานใหม่ แล้วจึงเข้าสู่ช่วงทบทวนความรู้",
"assistantSummaryIntro": "ยอดเยี่ยม จากวิดีโอเมื่อครู่นี้ ฉันสรุปประเด็นสำคัญที่มีโอกาสออกสอบไว้ให้แล้ว:",
"assistantSummaryReady": "พร้อมรับความท้าทายหรือยัง? กดเริ่มสอบได้เลย หรือพิมพ์ \"เริ่มสอบ\" ในแชตก็ได้",
"assistantQuestionSingleType": "ปรนัย",
"assistantQuestionBooleanType": "ถูกหรือผิด",
"assistantQuestionReplyHint": "ตอบด้วยตัวเลือกหรือข้อความคำตอบได้โดยตรง",
"assistantResultPass": "🎉 **ยินดีด้วย!** คุณได้คะแนนสุดท้าย **{score}** และผ่านการประเมินพนักงานใหม่แล้ว ระบบได้ซิงก์คะแนนไปยัง HR โดยอัตโนมัติ",
"assistantResultFail": "📊 **สอบเสร็จแล้ว!** คะแนนสุดท้ายของคุณคือ **{score}** เกณฑ์ผ่านคือ {passScore} คะแนน พิมพ์ \"สอบใหม่\" เพื่อเริ่มอีกครั้ง",
"startExamCommand": "เริ่มสอบ",
"restartExamCommand": "สอบใหม่"
},
"errors": {
"persistTitle": "บันทึกประวัติการอบรมไม่สำเร็จ",
"persistBody": "ผลสอบปัจจุบันยังไม่ได้เขียนลงฐานข้อมูล ดังนั้นหน้าจอ HR และสถิติจะไม่อัปเดต",
"loadTitle": "โหลดประวัติการอบรมไม่สำเร็จ",
"loadBody": "ไม่สามารถอ่านประวัติการอบรมจากฐานข้อมูลได้ในขณะนี้ ดังนั้นหน้าปัจจุบันอาจไม่ใช่ผลล่าสุด",
"questionBankEmpty": "คลังข้อสอบการอบรมว่างอยู่ โปรดตั้งค่าใน Agent configuration ก่อน"
},
"summaryPoints": [
"เงินเดือนจ่ายทุกวันที่ 15 ของเดือน และการลาหรือการลงเวลาต้องทำผ่าน OA",
+184
View File
@@ -0,0 +1,184 @@
{
"ledger": {
"notice": "หน้านี้ใช้สำหรับจัดการทะเบียนอุปกรณ์",
"tabs": {
"list": "รายการอุปกรณ์",
"form": "ตั้งค่าอุปกรณ์"
},
"status": {
"all": "ทุกสถานะ",
"inUse": "ใช้งานอยู่",
"disabled": "หยุดใช้",
"scrapped": "เลิกใช้",
"sold": "ขายแล้ว"
},
"formTitle": {
"create": "เพิ่มอุปกรณ์",
"edit": "แก้ไขอุปกรณ์"
},
"actions": {
"search": "ค้นหา",
"create": "เพิ่มอุปกรณ์",
"downloadTemplate": "ดาวน์โหลดเทมเพลต",
"importExcel": "นำเข้า Excel",
"importing": "กำลังนำเข้า...",
"edit": "แก้ไข",
"backToList": "กลับไปรายการ",
"cancel": "ยกเลิก",
"save": "บันทึก",
"saving": "กำลังบันทึก..."
},
"filters": {
"keywordPlaceholder": "ค้นหารหัสอุปกรณ์หรือชื่ออุปกรณ์"
},
"table": {
"deviceCode": "รหัสอุปกรณ์",
"deviceName": "ชื่ออุปกรณ์",
"modelSpec": "รุ่น/สเปก",
"manufacturer": "ผู้ขาย",
"status": "สถานะ",
"operation": "การดำเนินการ",
"loading": "กำลังโหลด...",
"empty": "ไม่มีอุปกรณ์"
},
"fields": {
"deviceCode": "รหัสอุปกรณ์",
"deviceName": "ชื่ออุปกรณ์",
"modelSpec": "รุ่น/สเปก",
"department": "แผนกที่ใช้",
"devicePosition": "ตำแหน่งอุปกรณ์",
"deviceStatus": "สถานะอุปกรณ์",
"manufacturer": "ผู้ผลิต",
"responsibleUser": "ผู้รับผิดชอบ",
"entryDate": "วันที่เข้าโรงงาน",
"productionDate": "วันที่ผลิต",
"startDate": "วันที่เริ่มใช้",
"maintenanceCycle": "รอบการบำรุงรักษา",
"originalValue": "มูลค่าเดิม",
"residualValue": "มูลค่าคงเหลือ",
"accountSet": "ชุดบัญชี",
"remark": "หมายเหตุ"
},
"placeholder": {
"maintenanceCycle": "ซ่อมตามต้องการ / ตรวจรายเดือน"
},
"messages": {
"required": "ต้องระบุรหัสอุปกรณ์และชื่ออุปกรณ์",
"saved": "บันทึกทะเบียนอุปกรณ์แล้ว",
"saveFailed": "บันทึกทะเบียนอุปกรณ์ไม่สำเร็จ",
"loadFailed": "โหลดทะเบียนอุปกรณ์ไม่สำเร็จ",
"invalidFormat": "โปรดอัปโหลดเทมเพลตทะเบียนอุปกรณ์รูปแบบ .xlsx",
"fileTooLarge": "ไฟล์ทะเบียนอุปกรณ์ต้องไม่เกิน 10MB",
"importDone": "นำเข้าทะเบียนอุปกรณ์เสร็จสิ้น",
"importFailed": "นำเข้าทะเบียนอุปกรณ์ไม่สำเร็จ"
},
"importResult": "ผลการนำเข้า: ทั้งหมด {total} รายการ, เพิ่ม {created}, อัปเดต {updated}, ล้มเหลว {failed}",
"importErrorRow": "แถว {row}: {message}"
},
"panel": {
"recordTitle": "บันทึกซ่อมบำรุง",
"ledgerTitle": "ตั้งค่าทะเบียน",
"adminOnly": "งานผู้ดูแล: ใช้ได้เฉพาะผู้ดูแลทรัพย์สิน / หัวหน้าซ่อมบำรุง",
"resizeTitle": "ลากเพื่อปรับความกว้าง",
"ledgerSubtitle": "รายการอุปกรณ์ / ตั้งค่าอุปกรณ์",
"recordSubtitle": "รายการบันทึก / ตั้งค่าบันทึก",
"fullscreen": "เต็มหน้าจอ",
"exitFullscreen": "ออกจากเต็มหน้าจอ",
"close": "ปิด"
},
"record": {
"notice": "บันทึกซ่อมบำรุงใช้สำหรับผู้ดูแลในการดูแลการแจ้งซ่อม การดำเนินการ ค่าใช้จ่าย และชั่วโมงงาน ส่วนการค้นหาทั่วไปยังทำผ่านแชทได้",
"tabs": {
"list": "รายการบันทึก",
"form": "ตั้งค่าบันทึก"
},
"status": {
"all": "ทุกสถานะ",
"pending": "รอซ่อม",
"processing": "กำลังซ่อม",
"done": "เสร็จสิ้น",
"cancelled": "ยกเลิกแล้ว"
},
"formTitle": {
"create": "เพิ่มบันทึกซ่อมบำรุง",
"edit": "แก้ไขบันทึกซ่อมบำรุง"
},
"actions": {
"search": "ค้นหา",
"create": "เพิ่มบันทึก",
"export": "ส่งออก",
"exporting": "กำลังส่งออก...",
"edit": "แก้ไข",
"delete": "ลบ",
"deleting": "กำลังลบ...",
"backToList": "กลับไปรายการ",
"cancel": "ยกเลิก",
"save": "บันทึก",
"saving": "กำลังบันทึก..."
},
"filters": {
"keywordPlaceholder": "ค้นหารหัสอุปกรณ์หรือชื่ออุปกรณ์"
},
"table": {
"deviceCode": "รหัสอุปกรณ์",
"deviceName": "ชื่ออุปกรณ์",
"modelSpec": "รุ่น/สเปก",
"faultDescription": "รายละเอียดปัญหา",
"status": "สถานะ",
"repairer": "ผู้ซ่อม",
"operation": "การดำเนินการ",
"loading": "กำลังโหลด...",
"empty": "ไม่มีบันทึกซ่อมบำรุง"
},
"fields": {
"deviceCode": "รหัสอุปกรณ์",
"reportDate": "วันที่แจ้งซ่อม",
"repairCategory": "ประเภทการซ่อม",
"repairStatus": "สถานะการซ่อม",
"faultDescription": "รายละเอียดปัญหา",
"reporter": "ผู้แจ้ง",
"approver": "ผู้อนุมัติ",
"repairDate": "วันที่ซ่อม",
"sourceOrderNo": "เลขที่ใบงานต้นทาง",
"repairUnit": "หน่วยงานซ่อม",
"repairer": "ผู้ซ่อม",
"repairCost": "ค่าซ่อม",
"repairHours": "ชั่วโมงซ่อม",
"repairDescription": "หมายเหตุการซ่อม"
},
"placeholder": {
"deviceCode": "เช่น EQ-2026-001",
"repairCategory": "ซ่อมทั่วไป / บำรุงรักษา / ตรวจเช็ก",
"repairCost": "เช่น 1200.00",
"repairHours": "เช่น 3.5h"
},
"deviceSnapshot": {
"loading": "กำลังค้นหาทะเบียนอุปกรณ์...",
"position": "ตำแหน่ง",
"department": "แผนก",
"responsibleUser": "ผู้รับผิดชอบ",
"status": "สถานะ",
"empty": "กรอกรหัสอุปกรณ์เพื่อจับคู่ข้อมูลทะเบียนอุปกรณ์อัตโนมัติ"
},
"messages": {
"loadFailed": "ค้นหาบันทึกซ่อมบำรุงไม่สำเร็จ",
"exported": "ส่งออกบันทึกซ่อมบำรุงแล้ว",
"exportFailed": "ส่งออกบันทึกซ่อมบำรุงไม่สำเร็จ",
"deviceLoadFailed": "ค้นหาทะเบียนอุปกรณ์ไม่สำเร็จ",
"required": "ต้องระบุรหัสอุปกรณ์ วันที่แจ้งซ่อม และรายละเอียดปัญหา",
"updated": "อัปเดตบันทึกซ่อมบำรุงแล้ว",
"created": "เพิ่มบันทึกซ่อมบำรุงแล้ว",
"saveFailed": "บันทึกข้อมูลซ่อมบำรุงไม่สำเร็จ",
"deleteConfirm": "ลบบันทึกซ่อมบำรุงของ {deviceCode} หรือไม่?",
"deleted": "ลบบันทึกซ่อมบำรุงแล้ว",
"deleteFailed": "ลบบันทึกซ่อมบำรุงไม่สำเร็จ"
}
},
"chat": {
"deviceLedgerInfo": "ข้อมูลทะเบียนอุปกรณ์",
"matched": "พบข้อมูล",
"recentRecords": "บันทึกซ่อมบำรุงล่าสุด ({count})",
"viewRepairHistory": "ดูประวัติซ่อม",
"addRepairRecord": "เพิ่มบันทึกซ่อม"
}
}
+63
View File
@@ -29,6 +29,13 @@
"reports": "数据报表",
"schedules": "排程管理"
},
"platformApps": {
"guideUsage": "资料用途",
"generalGuide": "通用指南",
"trainingVideo": "员工培训视频",
"trainingExamPdf": "员工培训试题 PDF",
"guideUsageHint": "培训工作区会优先读取“员工培训视频”和“员工培训试题 PDF”这两类资料。"
},
"dash": {
"activeAgents": "活跃应用",
"totalUsers": "总用户数",
@@ -86,6 +93,9 @@
"email": "邮箱",
"department": "部门",
"role": "角色",
"featurePermissions": "功能权限",
"trainingHrManage": "培训 HR 管理",
"trainingHrManageHint": "勾选后可进入员工培训 Agent 的【HR 管理】视图,查看统计、筛选记录并导出 Excel。",
"password": "密码",
"passwordHint": "(留空表示不修改)",
"noAgents": "暂无可用应用"
@@ -204,6 +214,58 @@
"pollInterval": "进度刷新间隔(秒)",
"lockInput": "任务执行期间禁止发送新消息",
"scheduleTaskRequired": "请先选择关联的排程任务"
},
"training": {
"title": "员工培训配置",
"subtitle": "配置培训工作区的及格线、复盘要点和题库。保存后,员工培训页会优先读取这里的后台内容。",
"enable": "启用员工培训工作区",
"enableHint": "开启后,当前 Agent 会使用“视频 -> 复盘 -> 考试 -> 结算”的培训工作区流程。",
"disabledHint": "关闭后,当前 Agent 不展示员工培训工作区;已填写的培训配置仍会保留在后台。",
"passScore": "及格线",
"passScoreHint": "按百分制判定是否通过,前台考试和结果文案会同步使用这个分数。",
"summaryPoints": "知识点复盘",
"summaryPointsPlaceholder": "每行一条,例如:工资每月 15 号发放",
"summaryChecklist": "考前必知",
"summaryChecklistPlaceholder": "每行一条,例如:低于 90 分必须重新考试",
"questionBank": "题库",
"questionHint": "支持单选题和判断题;保存后员工考试会即时使用新的题库。",
"emptyQuestionBank": "暂未配置题库,员工端会回退到默认题库。",
"importFromPdf": "从试题 PDF 导入",
"importingPdf": "正在解析 PDF...",
"importPdfHint": "将优先使用已上传的试题 PDF《{fileName}》解析题库,导入后仍可继续人工调整。",
"importPdfMissing": "当前 Agent 还没有上传并标记“员工培训试题 PDF”的资料,请先去“平台应用说明”上传。",
"importPdfCreateFirst": "请先保存当前 Agent,再从已上传的试题 PDF 导入题库。",
"importPdfAgentRequired": "请先保存当前 Agent,再导入试题 PDF",
"importPdfSuccess": "已从《{fileName}》导入 {count} 道题目",
"importPdfPartialSuccess": "已导入 {count} 道题目,以下题号未识别成功:{skipped}",
"importPdfOcrUsed": "本次导入通过 OCR 识别完成,建议重点复核题干、选项和答案。",
"importPdfOcrFallback": "原生 PDF 文本解析失败,已自动回退到 OCR 识别,建议重点复核题干、选项和答案。",
"importPdfWarnings": "解析提示:{warnings}",
"addQuestion": "添加题目",
"removeQuestion": "删除题目",
"questionCardTitle": "题目 {index}",
"questionId": "题目编号",
"questionIdPlaceholder": "例如:q1",
"questionType": "题型",
"single": "单选题",
"boolean": "判断题",
"correctAnswer": "正确答案",
"booleanTrue": "正确",
"booleanFalse": "错误",
"questionPrompt": "题干",
"questionPromptPlaceholder": "请输入题目内容",
"questionExplanation": "解析",
"questionExplanationPlaceholder": "请输入答题解析,答错后会直接展示给员工",
"questionOptions": "选项",
"addOption": "添加选项",
"optionLabel": "选项 {label}",
"optionPlaceholder": "请输入选项内容",
"validation": {
"questionRequired": "请至少配置一道培训题目",
"questionPromptRequired": "第 {index} 题题干不能为空",
"questionSingleOptions": "第 {index} 题至少需要 2 个有效选项",
"questionAnswerRequired": "第 {index} 题请选择正确答案"
}
}
},
"question": {
@@ -1003,6 +1065,7 @@
},
"role": {
"user": "普通用户",
"hr": "HR",
"admin": "管理员",
"guest": "访客"
},
+29 -11
View File
@@ -471,8 +471,8 @@
}
},
"training": {
"badge": "新人培训工作区",
"title": "新人入职培训 Agent",
"badge": "员工培训工作区",
"title": "",
"subtitle": "在同一个 Chat 页面内完成视频学习、知识点复盘、逐题考试以及 HR 管理统计。",
"tabs": {
"learner": "学员端",
@@ -482,7 +482,8 @@
"syncLearnerToChat": "同步学员上下文到聊天",
"syncHrToChat": "同步 HR 筛选到聊天",
"expandWorkspace": "展开工作区",
"collapseWorkspace": "收起工作区"
"collapseWorkspace": "收起工作区",
"viewExamPdf": "查看试题 PDF"
},
"steps": {
"video": "观看视频",
@@ -514,7 +515,7 @@
"title": "第三步:逐题考试",
"questionCounter": "第 {current} / {total} 题",
"currentScore": "当前分数:{score} 分",
"passLine": "及格线:90 分",
"passLine": "及格线:{passScore} 分",
"correctFeedback": "回答正确,继续下一题",
"wrongFeedback": "回答错误,已显示正确答案",
"selectedAnswer": "你的答案:{answer}",
@@ -527,8 +528,8 @@
"failedTag": "需补考",
"passTitle": "恭喜,你已通过新人培训考试",
"failTitle": "本次考试未达标,需要重新考试",
"passDescription": "前端已完成通过态交互,后续接入后端后可直接回写培训记录与完成日期。",
"failDescription": "按照 HR 规则,未达到 90 分必须重新考试,直到最终通过为止。",
"passDescription": "您已顺利通过本次考试,成绩会自动同步到 HR 管理端并计入培训记录。",
"failDescription": "按照 HR 规则,未达到 {passScore} 分必须重新考试,直到最终通过为止。",
"scoreLabel": "最终得分",
"attemptsLabel": "考试次数",
"correctCount": "答对题数",
@@ -545,9 +546,9 @@
},
"rules": {
"title": "考试规则",
"rule1": "共 20 题,每题 5 分,满分 100 分。",
"rule1": "共 {total} 题,系统按百分制自动计算成绩。",
"rule2": "系统按“一题一答一反馈”执行,答错立即展示正确答案。",
"rule3": "低于 90 分判定为未通过,必须重新考试。",
"rule3": "低于 {passScore} 分判定为未通过,必须重新考试。",
"rule4": "HR 管理端可在同一聊天页查看统计并导出 Excel。"
},
"hr": {
@@ -594,7 +595,24 @@
"afterSummary": "我已完成知识点复盘,请切换到考试模式并开始第一题。",
"afterPass": "我已经通过新人培训考试,得分 {score} 分,请帮我生成一段培训完成总结。",
"afterFail": "我本次新人培训考试得分 {score} 分,未达到及格线,请帮我总结错题重点并安排重考提醒。",
"examInProgress": "我正在进行新人培训考试,目前做到第 {index}/{total} 题。题目是:{question}。请保持考官模式,评价我的表现并引导我继续。"
"examInProgress": "我正在进行新人培训考试,目前做到第 {index}/{total} 题。题目是:{question}。请保持考官模式,评价我的表现并引导我继续。",
"assistantVideoIntro": "👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复盘 ➡️ 随堂测试({passScore} 分及格)。\n\n▶️ 请先点击观看【入职培训视频】。观看完毕后,点击进入【知识点复盘】。",
"assistantSummaryIntro": "太棒了!结合刚才的视频,我为你提炼了以下核心知识点(必考哦):",
"assistantSummaryReady": "准备好接受挑战了吗?直接点击【开始考试】或在 Chat 中回复【开始考试】。",
"assistantQuestionSingleType": "单选题",
"assistantQuestionBooleanType": "判断题",
"assistantQuestionReplyHint": "请直接回复选项或内容。",
"assistantResultPass": "🎉 **恭喜!** 您的最终得分是 **{score} 分**,已顺利通过新人考核!您的成绩已自动同步至人事部门。",
"assistantResultFail": "📊 **考试结束!** 您的最终得分是 **{score} 分**。及格线为 {passScore} 分。请回复【重新考试】再次挑战!",
"startExamCommand": "开始考试",
"restartExamCommand": "重新考试"
},
"errors": {
"persistTitle": "培训记录保存失败",
"persistBody": "当前考试结果尚未写入数据库,HR 管理与统计不会更新",
"loadTitle": "培训记录读取失败",
"loadBody": "当前无法从数据库读取培训记录,页面展示可能不是最新结果",
"questionBankEmpty": "当前培训题库为空,请先在后台 Agent 配置中维护题库"
},
"summaryPoints": [
"工资每月 15 号发放,考勤与请假均需要走 OA 流程。",
@@ -618,8 +636,8 @@
"id": "q1",
"type": "single",
"prompt": "工资每月几号发放?",
"answer": "a",
"explanation": "根据新人培训试卷答案,工资固定在每月 8 号发放。",
"answer": "c",
"explanation": "根据新人培训试卷答案,工资固定在每月 15 号发放。",
"options": [
{ "id": "a", "label": "A. 8号" },
{ "id": "b", "label": "B. 9号" },
+184
View File
@@ -0,0 +1,184 @@
{
"ledger": {
"notice": "当前页面用于设备台账管理。",
"tabs": {
"list": "设备列表",
"form": "设备配置"
},
"status": {
"all": "全部状态",
"inUse": "在用",
"disabled": "停用",
"scrapped": "报废",
"sold": "出售"
},
"formTitle": {
"create": "新增设备",
"edit": "编辑设备"
},
"actions": {
"search": "查询",
"create": "新增设备",
"downloadTemplate": "下载模板",
"importExcel": "导入 Excel",
"importing": "导入中...",
"edit": "编辑",
"backToList": "返回列表",
"cancel": "取消",
"save": "保存配置",
"saving": "保存中..."
},
"filters": {
"keywordPlaceholder": "搜索设备编号、设备名称"
},
"table": {
"deviceCode": "设备编号",
"deviceName": "设备名称",
"modelSpec": "型号规格",
"manufacturer": "厂商",
"status": "状态",
"operation": "操作",
"loading": "加载中...",
"empty": "暂无设备"
},
"fields": {
"deviceCode": "设备编号",
"deviceName": "设备名称",
"modelSpec": "型号规格",
"department": "使用部门",
"devicePosition": "设备位置",
"deviceStatus": "设备状态",
"manufacturer": "制造厂家",
"responsibleUser": "责任人",
"entryDate": "进厂日期",
"productionDate": "生产日期",
"startDate": "启用日期",
"maintenanceCycle": "维护周期",
"originalValue": "原值",
"residualValue": "残值",
"accountSet": "账套",
"remark": "备注"
},
"placeholder": {
"maintenanceCycle": "按需维修 / 每月点检"
},
"messages": {
"required": "设备编号和设备名称不能为空",
"saved": "设备台账已保存",
"saveFailed": "保存设备台账失败",
"loadFailed": "加载设备台账失败",
"invalidFormat": "请上传 .xlsx 格式的设备台账模板",
"fileTooLarge": "设备台账文件不能超过 10MB",
"importDone": "设备台账导入完成",
"importFailed": "导入设备台账失败"
},
"importResult": "导入结果:共 {total} 条,新增 {created} 条,更新 {updated} 条,失败 {failed} 条。",
"importErrorRow": "第 {row} 行:{message}"
},
"panel": {
"recordTitle": "维修记录",
"ledgerTitle": "台账配置",
"adminOnly": "管理操作:仅资产管理员 / 维修主管可用",
"resizeTitle": "拖拽调整宽度",
"ledgerSubtitle": "设备列表 / 设备配置",
"recordSubtitle": "记录列表 / 记录配置",
"fullscreen": "全屏",
"exitFullscreen": "退出全屏",
"close": "关闭"
},
"record": {
"notice": "维修记录用于管理员维护设备报修、处理、费用和工时信息;普通查询仍可通过会话完成。",
"tabs": {
"list": "记录列表",
"form": "记录配置"
},
"status": {
"all": "全部状态",
"pending": "待维修",
"processing": "维修中",
"done": "已完成",
"cancelled": "已取消"
},
"formTitle": {
"create": "新增维修记录",
"edit": "编辑维修记录"
},
"actions": {
"search": "查询",
"create": "新增维修记录",
"export": "导出",
"exporting": "导出中...",
"edit": "编辑",
"delete": "删除",
"deleting": "删除中...",
"backToList": "返回列表",
"cancel": "取消",
"save": "保存记录",
"saving": "保存中..."
},
"filters": {
"keywordPlaceholder": "搜索设备编号、设备名称"
},
"table": {
"deviceCode": "设备编号",
"deviceName": "设备名称",
"modelSpec": "型号规格",
"faultDescription": "故障描述",
"status": "状态",
"repairer": "维修人",
"operation": "操作",
"loading": "加载中...",
"empty": "暂无维修记录"
},
"fields": {
"deviceCode": "设备编号",
"reportDate": "报修日期",
"repairCategory": "维修类别",
"repairStatus": "维修状态",
"faultDescription": "故障描述",
"reporter": "报修人",
"approver": "审批人",
"repairDate": "维修日期",
"sourceOrderNo": "来源工单号",
"repairUnit": "维修单位",
"repairer": "维修人",
"repairCost": "维修费用",
"repairHours": "维修工时",
"repairDescription": "维修说明"
},
"placeholder": {
"deviceCode": "如 EQ-2026-001",
"repairCategory": "日常维修 / 保养 / 点检",
"repairCost": "如 1200.00",
"repairHours": "如 3.5h"
},
"deviceSnapshot": {
"loading": "正在查询设备台账...",
"position": "位置",
"department": "部门",
"responsibleUser": "责任人",
"status": "状态",
"empty": "输入设备编号后可自动匹配设备台账快照。"
},
"messages": {
"loadFailed": "查询维修记录失败",
"exported": "维修记录已导出",
"exportFailed": "导出维修记录失败",
"deviceLoadFailed": "查询设备台账失败",
"required": "设备编号、报修日期和故障描述不能为空",
"updated": "维修记录已更新",
"created": "维修记录已新增",
"saveFailed": "保存维修记录失败",
"deleteConfirm": "确认删除 {deviceCode} 的维修记录?",
"deleted": "维修记录已删除",
"deleteFailed": "删除维修记录失败"
}
},
"chat": {
"deviceLedgerInfo": "设备台账信息",
"matched": "已匹配",
"recentRecords": "最近维修记录({count} 条)",
"viewRepairHistory": "查维修历史",
"addRepairRecord": "新增维修记录"
}
}
+63
View File
@@ -28,6 +28,13 @@
"reports": "數據報表",
"schedules": "排程管理"
},
"platformApps": {
"guideUsage": "資料用途",
"generalGuide": "通用指南",
"trainingVideo": "員工培訓視頻",
"trainingExamPdf": "員工培訓試題 PDF",
"guideUsageHint": "培訓工作區會優先讀取「員工培訓視頻」和「員工培訓試題 PDF」這兩類資料。"
},
"dash": {
"activeAgents": "活躍應用",
"totalUsers": "總用戶數",
@@ -85,6 +92,9 @@
"email": "郵箱",
"department": "部門",
"role": "角色",
"featurePermissions": "功能權限",
"trainingHrManage": "培訓 HR 管理",
"trainingHrManageHint": "勾選後可進入員工培訓 Agent 的【HR 管理】視圖,查看統計、篩選記錄並匯出 Excel。",
"password": "密碼",
"passwordHint": "(留空表示不修改)",
"noAgents": "暫無可用應用"
@@ -203,6 +213,58 @@
"pollInterval": "進度刷新間隔(秒)",
"lockInput": "任務執行期間禁止發送新訊息",
"scheduleTaskRequired": "請先選擇關聯的排程任務"
},
"training": {
"title": "員工培訓配置",
"subtitle": "配置培訓工作區的及格線、複盤要點和題庫。保存後,員工培訓頁會優先讀取這裡的後台內容。",
"enable": "啟用員工培訓工作區",
"enableHint": "開啟後,當前 Agent 會使用「影片 -> 複盤 -> 考試 -> 結算」的培訓工作區流程。",
"disabledHint": "關閉後,當前 Agent 不顯示員工培訓工作區;已填寫的培訓配置仍會保留在後台。",
"passScore": "及格線",
"passScoreHint": "按百分制判定是否通過,前台考試和結果文案會同步使用這個分數。",
"summaryPoints": "知識點複盤",
"summaryPointsPlaceholder": "每行一條,例如:工資每月 15 號發放",
"summaryChecklist": "考前必知",
"summaryChecklistPlaceholder": "每行一條,例如:低於 90 分必須重新考試",
"questionBank": "題庫",
"questionHint": "支援單選題和判斷題;保存後員工考試會即時使用新的題庫。",
"emptyQuestionBank": "暫未配置題庫,員工端會回退到預設題庫。",
"importFromPdf": "從試題 PDF 導入",
"importingPdf": "正在解析 PDF...",
"importPdfHint": "將優先使用已上傳的試題 PDF《{fileName}》解析題庫,導入後仍可繼續人工調整。",
"importPdfMissing": "當前 Agent 還沒有上傳並標記「員工培訓試題 PDF」的資料,請先去「平台應用說明」上傳。",
"importPdfCreateFirst": "請先保存當前 Agent,再從已上傳的試題 PDF 導入題庫。",
"importPdfAgentRequired": "請先保存當前 Agent,再導入試題 PDF",
"importPdfSuccess": "已從《{fileName}》導入 {count} 道題目",
"importPdfPartialSuccess": "已導入 {count} 道題目,以下題號未識別成功:{skipped}",
"importPdfOcrUsed": "本次導入透過 OCR 識別完成,建議重點複核題幹、選項與答案。",
"importPdfOcrFallback": "原生 PDF 文字解析失敗,已自動回退至 OCR 識別,建議重點複核題幹、選項與答案。",
"importPdfWarnings": "解析提示:{warnings}",
"addQuestion": "添加題目",
"removeQuestion": "刪除題目",
"questionCardTitle": "題目 {index}",
"questionId": "題目編號",
"questionIdPlaceholder": "例如:q1",
"questionType": "題型",
"single": "單選題",
"boolean": "判斷題",
"correctAnswer": "正確答案",
"booleanTrue": "正確",
"booleanFalse": "錯誤",
"questionPrompt": "題幹",
"questionPromptPlaceholder": "請輸入題目內容",
"questionExplanation": "解析",
"questionExplanationPlaceholder": "請輸入答題解析,答錯後會直接展示給員工",
"questionOptions": "選項",
"addOption": "添加選項",
"optionLabel": "選項 {label}",
"optionPlaceholder": "請輸入選項內容",
"validation": {
"questionRequired": "請至少配置一道培訓題目",
"questionPromptRequired": "第 {index} 題題幹不能為空",
"questionSingleOptions": "第 {index} 題至少需要 2 個有效選項",
"questionAnswerRequired": "第 {index} 題請選擇正確答案"
}
}
},
"question": {
@@ -883,6 +945,7 @@
},
"role": {
"user": "普通用戶",
"hr": "HR",
"admin": "管理員",
"guest": "訪客"
},
+27 -9
View File
@@ -471,8 +471,8 @@
}
},
"training": {
"badge": "新人培訓工作區",
"title": "新人入職培訓 Agent",
"badge": "員工培訓工作區",
"title": "",
"subtitle": "在同一個 Chat 頁面內完成影片學習、知識點複盤、逐題考試與 HR 管理統計。",
"tabs": {
"learner": "學員端",
@@ -482,7 +482,8 @@
"syncLearnerToChat": "同步學員上下文到聊天",
"syncHrToChat": "同步 HR 篩選到聊天",
"expandWorkspace": "展開工作區",
"collapseWorkspace": "收起工作區"
"collapseWorkspace": "收起工作區",
"viewExamPdf": "查看試題 PDF"
},
"steps": {
"video": "觀看影片",
@@ -514,7 +515,7 @@
"title": "第三步:逐題考試",
"questionCounter": "第 {current} / {total} 題",
"currentScore": "當前分數:{score} 分",
"passLine": "及格線:90 分",
"passLine": "及格線:{passScore} 分",
"correctFeedback": "回答正確,繼續下一題",
"wrongFeedback": "回答錯誤,已顯示正確答案",
"selectedAnswer": "你的答案:{answer}",
@@ -527,8 +528,8 @@
"failedTag": "需補考",
"passTitle": "恭喜,你已通過新人培訓考試",
"failTitle": "本次考試未達標,需要重新考試",
"passDescription": "前端已完成通過態互動,後續接入後端後可直接回寫培訓記錄與完成日期。",
"failDescription": "依照 HR 規則,低於 90 分必須重新考試,直到最終通過。",
"passDescription": "你已順利通過本次考試,成績會自動同步到 HR 管理端並記入培訓紀錄。",
"failDescription": "依照 HR 規則,低於 {passScore} 分必須重新考試,直到最終通過。",
"scoreLabel": "最終得分",
"attemptsLabel": "考試次數",
"correctCount": "答對題數",
@@ -545,9 +546,9 @@
},
"rules": {
"title": "考試規則",
"rule1": "共 20 題,每題 5 分,滿分 100 分。",
"rule1": "共 {total} 題,系統按百分制自動計算成績。",
"rule2": "系統依「一題一答一回饋」執行,答錯立即顯示正確答案。",
"rule3": "低於 90 分視為未通過,必須重新考試。",
"rule3": "低於 {passScore} 分視為未通過,必須重新考試。",
"rule4": "HR 管理端可在同一聊天頁查看統計並匯出 Excel。"
},
"hr": {
@@ -594,7 +595,24 @@
"afterSummary": "我已完成知識點複盤,請切換到考試模式並開始第一題。",
"afterPass": "我已通過新人培訓考試,得分 {score} 分,請幫我生成一段培訓完成總結。",
"afterFail": "我本次新人培訓考試得分 {score} 分,未達及格線,請幫我總結錯題重點並安排重考提醒。",
"examInProgress": "我正在進行新人培訓考試,目前做到第 {index}/{total} 題,請保持考官模式繼續出題。"
"examInProgress": "我正在進行新人培訓考試,目前做到第 {index}/{total} 題,請保持考官模式繼續出題。",
"assistantVideoIntro": "👋 歡迎加入公司!我是你的專屬入職培訓助手。今天的培訓分為三個步驟:看影片 ➡️ 知識點複盤 ➡️ 隨堂測試({passScore} 分及格)。\n\n▶️ 請先點擊觀看【入職培訓影片】。觀看完畢後,點擊進入【知識點複盤】。",
"assistantSummaryIntro": "太棒了!結合剛才的影片,我為你提煉了以下核心知識點(必考哦):",
"assistantSummaryReady": "準備好接受挑戰了嗎?直接點擊【開始考試】或在 Chat 中回覆【開始考試】。",
"assistantQuestionSingleType": "單選題",
"assistantQuestionBooleanType": "判斷題",
"assistantQuestionReplyHint": "請直接回覆選項或內容。",
"assistantResultPass": "🎉 **恭喜!** 你的最終得分是 **{score} 分**,已順利通過新人考核!成績已自動同步至人事部門。",
"assistantResultFail": "📊 **考試結束!** 你的最終得分是 **{score} 分**。及格線為 {passScore} 分。請回覆【重新考試】再次挑戰!",
"startExamCommand": "開始考試",
"restartExamCommand": "重新考試"
},
"errors": {
"persistTitle": "培訓記錄保存失敗",
"persistBody": "當前考試結果尚未寫入資料庫,HR 管理與統計不會更新",
"loadTitle": "培訓記錄讀取失敗",
"loadBody": "目前無法從資料庫讀取培訓記錄,頁面顯示可能不是最新結果",
"questionBankEmpty": "當前培訓題庫為空,請先在後台 Agent 配置中維護題庫"
},
"summaryPoints": [
"工資每月 15 號發放,考勤與請假均需走 OA 流程。",
+184
View File
@@ -0,0 +1,184 @@
{
"ledger": {
"notice": "目前頁面用於設備台帳管理。",
"tabs": {
"list": "設備列表",
"form": "設備配置"
},
"status": {
"all": "全部狀態",
"inUse": "在用",
"disabled": "停用",
"scrapped": "報廢",
"sold": "出售"
},
"formTitle": {
"create": "新增設備",
"edit": "編輯設備"
},
"actions": {
"search": "查詢",
"create": "新增設備",
"downloadTemplate": "下載範本",
"importExcel": "匯入 Excel",
"importing": "匯入中...",
"edit": "編輯",
"backToList": "返回列表",
"cancel": "取消",
"save": "儲存配置",
"saving": "儲存中..."
},
"filters": {
"keywordPlaceholder": "搜尋設備編號、設備名稱"
},
"table": {
"deviceCode": "設備編號",
"deviceName": "設備名稱",
"modelSpec": "型號規格",
"manufacturer": "廠商",
"status": "狀態",
"operation": "操作",
"loading": "載入中...",
"empty": "暫無設備"
},
"fields": {
"deviceCode": "設備編號",
"deviceName": "設備名稱",
"modelSpec": "型號規格",
"department": "使用部門",
"devicePosition": "設備位置",
"deviceStatus": "設備狀態",
"manufacturer": "製造廠家",
"responsibleUser": "責任人",
"entryDate": "進廠日期",
"productionDate": "生產日期",
"startDate": "啟用日期",
"maintenanceCycle": "維護週期",
"originalValue": "原值",
"residualValue": "殘值",
"accountSet": "帳套",
"remark": "備註"
},
"placeholder": {
"maintenanceCycle": "按需維修 / 每月點檢"
},
"messages": {
"required": "設備編號和設備名稱不能為空",
"saved": "設備台帳已儲存",
"saveFailed": "儲存設備台帳失敗",
"loadFailed": "載入設備台帳失敗",
"invalidFormat": "請上傳 .xlsx 格式的設備台帳範本",
"fileTooLarge": "設備台帳檔案不能超過 10MB",
"importDone": "設備台帳匯入完成",
"importFailed": "匯入設備台帳失敗"
},
"importResult": "匯入結果:共 {total} 筆,新增 {created} 筆,更新 {updated} 筆,失敗 {failed} 筆。",
"importErrorRow": "第 {row} 行:{message}"
},
"panel": {
"recordTitle": "維修記錄",
"ledgerTitle": "台帳配置",
"adminOnly": "管理操作:僅資產管理員 / 維修主管可用",
"resizeTitle": "拖曳調整寬度",
"ledgerSubtitle": "設備列表 / 設備配置",
"recordSubtitle": "記錄列表 / 記錄配置",
"fullscreen": "全螢幕",
"exitFullscreen": "退出全螢幕",
"close": "關閉"
},
"record": {
"notice": "維修記錄用於管理員維護設備報修、處理、費用和工時資訊;一般查詢仍可透過會話完成。",
"tabs": {
"list": "記錄列表",
"form": "記錄配置"
},
"status": {
"all": "全部狀態",
"pending": "待維修",
"processing": "維修中",
"done": "已完成",
"cancelled": "已取消"
},
"formTitle": {
"create": "新增維修記錄",
"edit": "編輯維修記錄"
},
"actions": {
"search": "查詢",
"create": "新增維修記錄",
"export": "匯出",
"exporting": "匯出中...",
"edit": "編輯",
"delete": "刪除",
"deleting": "刪除中...",
"backToList": "返回列表",
"cancel": "取消",
"save": "儲存記錄",
"saving": "儲存中..."
},
"filters": {
"keywordPlaceholder": "搜尋設備編號、設備名稱"
},
"table": {
"deviceCode": "設備編號",
"deviceName": "設備名稱",
"modelSpec": "型號規格",
"faultDescription": "故障描述",
"status": "狀態",
"repairer": "維修人",
"operation": "操作",
"loading": "載入中...",
"empty": "暫無維修記錄"
},
"fields": {
"deviceCode": "設備編號",
"reportDate": "報修日期",
"repairCategory": "維修類別",
"repairStatus": "維修狀態",
"faultDescription": "故障描述",
"reporter": "報修人",
"approver": "審批人",
"repairDate": "維修日期",
"sourceOrderNo": "來源工單號",
"repairUnit": "維修單位",
"repairer": "維修人",
"repairCost": "維修費用",
"repairHours": "維修工時",
"repairDescription": "維修說明"
},
"placeholder": {
"deviceCode": "如 EQ-2026-001",
"repairCategory": "日常維修 / 保養 / 點檢",
"repairCost": "如 1200.00",
"repairHours": "如 3.5h"
},
"deviceSnapshot": {
"loading": "正在查詢設備台帳...",
"position": "位置",
"department": "部門",
"responsibleUser": "責任人",
"status": "狀態",
"empty": "輸入設備編號後可自動匹配設備台帳快照。"
},
"messages": {
"loadFailed": "查詢維修記錄失敗",
"exported": "維修記錄已匯出",
"exportFailed": "匯出維修記錄失敗",
"deviceLoadFailed": "查詢設備台帳失敗",
"required": "設備編號、報修日期和故障描述不能為空",
"updated": "維修記錄已更新",
"created": "維修記錄已新增",
"saveFailed": "儲存維修記錄失敗",
"deleteConfirm": "確認刪除 {deviceCode} 的維修記錄?",
"deleted": "維修記錄已刪除",
"deleteFailed": "刪除維修記錄失敗"
}
},
"chat": {
"deviceLedgerInfo": "設備台帳資訊",
"matched": "已匹配",
"recentRecords": "最近維修記錄({count} 筆)",
"viewRepairHistory": "查維修歷史",
"addRepairRecord": "新增維修記錄"
}
}
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script setup lang="ts">
/**
* shared/components/FilePreviewModal.vue
* 文件预览弹窗(图片/PDF 等)。
@@ -10,13 +10,15 @@
* 引用文件:vue, marked
* 逻辑关系:
* - 接收 ChatView 传入的 file(name/url)与弹窗显隐状态
* - 根据扩展名选择预览模式(markdown/image/iframe)
* - 根据扩展名选择预览模式(markdown/image/iframe/office)
* - Excel 预览优先走 Office 风格渲染,尽量还原原始表格观感;失败时再降级为简化表格
* - 对 Office 文档在可公网 HTTPS 访问时走 Office 在线预览,否则降级为打开/下载
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { marked } from 'marked';
import * as XLSX from 'xlsx';
import { Minus, Plus, RotateCcw } from 'lucide-vue-next';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
@@ -39,7 +41,7 @@ interface ExcelPreviewData {
}
type OfficeKind = 'docx' | 'excel' | 'pdf' | null;
type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'office';
type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'sheetHtml' | 'office';
const props = defineProps<{
modelValue: boolean;
@@ -56,11 +58,17 @@ const { t } = useI18n();
const isLoading = ref(false);
const error = ref('');
const markdownHtml = ref('');
const excelHtml = ref('');
const excelPreview = ref<ExcelPreviewData | null>(null);
const officeSrc = ref<string | ArrayBuffer | Blob>('');
const officeKind = ref<OfficeKind>(null);
const officeObjectUrl = ref<string>('');
const officeRenderKey = ref(0);
const excelZoom = ref(1);
const EXCEL_ZOOM_STEP = 0.1;
const EXCEL_ZOOM_MIN = 0.6;
const EXCEL_ZOOM_MAX = 1.8;
/**
* 从 URL 或文件名中提取扩展名。
@@ -87,8 +95,7 @@ const ext = computed(() => {
const preferredMode = computed<PreviewMode>(() => {
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
if (['xlsx', 'xls'].includes(ext.value)) return 'sheet';
if (['docx'].includes(ext.value)) return 'office';
if (['xlsx', 'xls', 'docx'].includes(ext.value)) return 'office';
if (['doc', 'ppt', 'pptx', 'pdf'].includes(ext.value)) return 'iframe';
return 'iframe';
});
@@ -120,6 +127,13 @@ const iframeSrc = computed(() => {
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
const officePreviewExts = new Set(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']);
const isExcelPreviewFile = computed(() => ['xls', 'xlsx'].includes(ext.value));
const excelZoomPercent = computed(() => `${Math.round(excelZoom.value * 100)}%`);
const excelPreviewScaleStyle = computed(() => ({
transform: `scale(${excelZoom.value})`,
transformOrigin: 'top left',
width: `${100 / excelZoom.value}%`,
}));
const close = () => emit('update:modelValue', false);
@@ -134,6 +148,25 @@ const clearOfficeObjectUrl = () => {
officeKind.value = null;
};
/**
* 调整 Excel 预览缩放比例。
* AI 触发时机:当用户点击弹窗头部的放大/缩小按钮,希望更清楚查看履历表格时调用。
* 核心逻辑:按照固定步进调整缩放,并限制在可读范围内,避免放得过大或过小。
* 参数与输出约束:delta 仅表示增量,不直接写死最终倍率;最终结果会被钳制到 60%~180%。
*/
const adjustExcelZoom = (delta: number) => {
const nextZoom = excelZoom.value + delta;
excelZoom.value = Math.min(EXCEL_ZOOM_MAX, Math.max(EXCEL_ZOOM_MIN, Number(nextZoom.toFixed(2))));
};
/**
* 重置 Excel 预览缩放比例。
* 用途:让用户一键回到默认 100% 视图,避免多次缩放后难以恢复。
*/
const resetExcelZoom = () => {
excelZoom.value = 1;
};
const extractErrorMessage = (payload: any, fallback: string) => {
if (!payload) return fallback;
if (typeof payload === 'string' && payload.trim()) return payload.trim();
@@ -186,6 +219,27 @@ const applyExcelPreview = (buffer: ArrayBuffer) => {
};
};
/**
* 将 Excel 原始工作表转为 HTML 预览。
* 用途:尽量保留原 Excel 的布局、合并单元格和表格观感,使履历预览更接近用户看到的原文件。
* 约束:仅使用第一个工作表;若库无法解析原始布局,则抛错并交给表格矩阵模式兜底。
*/
const applyExcelHtmlPreview = (buffer: ArrayBuffer) => {
const workbook = XLSX.read(buffer, { type: 'array', cellStyles: true });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
excelHtml.value = XLSX.utils.sheet_to_html(worksheet, {
id: 'hxops-excel-preview-table',
editable: false,
});
};
const tryApplyExcelPreview = (buffer: ArrayBuffer) => {
try {
applyExcelPreview(buffer);
@@ -214,6 +268,40 @@ const loadSheetPreview = async () => {
excelPreview.value = await res.json();
};
/**
* 直接拉取原始 Excel 二进制并在前端解析。
* 用途:当后端 `/preview-excel` 无法处理共享盘里的旧版 Excel 时,前端仍尽量展示首个工作表内容。
* 约束:仅作为 Excel 预览兜底使用;解析失败时继续向上抛错,由统一错误 UI 呈现。
*/
const loadSheetPreviewFromRaw = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for excel preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
throw new Error(await readErrorMessage(res));
}
const buffer = await res.arrayBuffer();
try {
applyExcelHtmlPreview(buffer);
resolvedMode.value = 'sheetHtml';
return;
} catch {
if (!tryApplyExcelPreview(buffer)) {
throw new Error('failed to parse excel file');
}
resolvedMode.value = 'sheet';
}
};
const loadOfficeContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for office preview');
@@ -240,6 +328,23 @@ const loadOfficeContent = async () => {
else officeKind.value = null;
};
/**
* Excel Office 风格渲染失败后的兜底处理。
* AI 触发时机:当 `VueOfficeExcel` 无法正确渲染共享盘里的旧版/特殊 Excel 时调用。
* 核心逻辑:优先走后端 `/preview-excel` 简化预览,失败后再回退到前端原始二进制解析,确保用户至少能看到表格内容。
* 参数与输出约束:该方法只处理当前已加载文件,不接收外部参数;成功后会把 `resolvedMode` 切换为 `sheet`。
*/
const fallbackToSheetPreview = async () => {
try {
await loadSheetPreviewFromRaw();
error.value = '';
} catch {
await loadSheetPreview();
resolvedMode.value = 'sheet';
error.value = '';
}
};
const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
if (!props.file?.url) return 'iframe';
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
@@ -342,7 +447,9 @@ const loadBinaryContent = async () => {
const loadContent = async () => {
error.value = '';
markdownHtml.value = '';
excelHtml.value = '';
excelPreview.value = null;
resetExcelZoom();
clearOfficeObjectUrl();
if (!props.modelValue || !props.file) return;
if (!props.file?.url) return;
@@ -374,8 +481,17 @@ const loadContent = async () => {
}
resolvedMode.value = 'office';
} catch (e: any) {
error.value = e?.message || 'Failed to preview office file';
resolvedMode.value = 'iframe';
if (['xlsx', 'xls'].includes(ext.value)) {
try {
await fallbackToSheetPreview();
} catch {
error.value = e?.message || 'Failed to preview excel';
resolvedMode.value = 'iframe';
}
} else {
error.value = e?.message || 'Failed to preview office file';
resolvedMode.value = 'iframe';
}
} finally {
isLoading.value = false;
}
@@ -387,8 +503,13 @@ const loadContent = async () => {
await loadSheetPreview();
resolvedMode.value = 'sheet';
} catch (e: any) {
error.value = e?.message || 'Failed to preview excel';
resolvedMode.value = 'iframe';
try {
await loadSheetPreviewFromRaw();
resolvedMode.value = 'sheet';
} catch {
error.value = e?.message || 'Failed to preview excel';
resolvedMode.value = 'iframe';
}
} finally {
isLoading.value = false;
}
@@ -464,14 +585,47 @@ watch(
</script>
<template>
<div v-if="modelValue && file" class="dialog-overlay dialog-overlay--z80 items-center">
<div v-if="modelValue && file" class="dialog-overlay z-[140] items-center">
<div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden">
<div class="dialog-header dialog-header--compact items-start">
<div class="min-w-0">
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
</div>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
<div class="flex shrink-0 items-center gap-2">
<div v-if="isExcelPreviewFile" class="flex items-center gap-2 rounded-full border border-default bg-surface px-2 py-1">
<button
type="button"
class="btn-icon-ds h-8 w-8"
aria-label="缩小"
:disabled="excelZoom <= EXCEL_ZOOM_MIN"
@click="adjustExcelZoom(-EXCEL_ZOOM_STEP)"
>
<Minus class="h-4 w-4" />
</button>
<button
type="button"
class="rounded-md px-2 py-1 text-xs font-medium text-secondary transition hover:bg-surface-soft"
aria-label="重置缩放"
@click="resetExcelZoom"
>
<span class="inline-flex items-center gap-1">
<RotateCcw class="h-3.5 w-3.5" />
{{ excelZoomPercent }}
</span>
</button>
<button
type="button"
class="btn-icon-ds h-8 w-8"
aria-label="放大"
:disabled="excelZoom >= EXCEL_ZOOM_MAX"
@click="adjustExcelZoom(EXCEL_ZOOM_STEP)"
>
<Plus class="h-4 w-4" />
</button>
</div>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
</div>
</div>
<div class="dialog-preview-body">
@@ -493,34 +647,44 @@ watch(
v-else-if="resolvedMode === 'sheet' && excelPreview"
class="dialog-preview-frame h-full p-4 overflow-auto"
>
<div class="mb-3 text-xs text-muted">
Sheet: {{ excelPreview.sheet_name }} | Rows: {{ excelPreview.rows.length }}
<span v-if="excelPreview.truncated"> (truncated)</span>
<div :style="excelPreviewScaleStyle" class="pb-6">
<div class="mb-3 text-xs text-muted">
Sheet: {{ excelPreview.sheet_name }} | Rows: {{ excelPreview.rows.length }}
<span v-if="excelPreview.truncated"> (truncated)</span>
</div>
<table class="min-w-full text-xs border-collapse">
<thead>
<tr>
<th
v-for="(col, i) in excelPreview.columns"
:key="`h-${i}`"
class="sticky top-0 bg-surface-soft border border-default px-2 py-1 text-left font-semibold text-secondary"
>
{{ col }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in excelPreview.rows" :key="`r-${ri}`">
<td
v-for="(cell, ci) in row"
:key="`c-${ri}-${ci}`"
class="border border-default px-2 py-1 align-top whitespace-pre-wrap break-words text-secondary"
>
{{ cell }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div
v-else-if="resolvedMode === 'sheetHtml' && excelHtml"
class="dialog-preview-frame h-full overflow-auto bg-white p-4"
>
<div :style="excelPreviewScaleStyle" class="pb-6">
<div class="excel-html-preview min-w-max" v-html="excelHtml"></div>
</div>
<table class="min-w-full text-xs border-collapse">
<thead>
<tr>
<th
v-for="(col, i) in excelPreview.columns"
:key="`h-${i}`"
class="sticky top-0 bg-surface-soft border border-default px-2 py-1 text-left font-semibold text-secondary"
>
{{ col }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in excelPreview.rows" :key="`r-${ri}`">
<td
v-for="(cell, ci) in row"
:key="`c-${ri}-${ci}`"
class="border border-default px-2 py-1 align-top whitespace-pre-wrap break-words text-secondary"
>
{{ cell }}
</td>
</tr>
</tbody>
</table>
</div>
<div
v-else-if="resolvedMode === 'office' && officeKind"
@@ -538,6 +702,8 @@ watch(
v-else-if="officeKind === 'excel'"
:key="`excel-${officeRenderKey}`"
:src="officeSrc"
@rendered="error = ''"
@error="fallbackToSheetPreview().catch(() => { error = 'Excel render failed'; resolvedMode = 'sheet'; })"
style="height: 100%; width: 100%;"
/>
<VueOfficePdf
@@ -581,3 +747,26 @@ watch(
</div>
</div>
</template>
<style scoped>
.excel-html-preview :deep(table) {
border-collapse: collapse;
background: #fff;
color: #111827;
font-size: 14px;
}
.excel-html-preview :deep(td),
.excel-html-preview :deep(th) {
min-width: 52px;
border: 1px solid #111827;
padding: 4px 6px;
vertical-align: middle;
white-space: pre-wrap;
}
.excel-html-preview :deep(tr:nth-child(-n + 2) td),
.excel-html-preview :deep(tr:nth-child(-n + 2) th) {
text-align: center;
}
</style>
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more