Merge branch 'dev' into hugo-shipping-notice
# Conflicts: # backend/app/services/maintenance_chat_service.py # backend/tests/test_maintenance_chat_service.py # frontend/src/features/chat/components/ChatViewContent.vue
This commit is contained in:
commit
2ce1aca023
25 files changed
+1609
-304
No files matched your search
@@ -9,6 +9,7 @@ backend/app/api/maintenance.py
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
@@ -21,6 +22,7 @@ from app.services.maintenance_ledger_service import (
|
||||
import_devices_from_excel,
|
||||
list_devices,
|
||||
update_device,
|
||||
_parse_date,
|
||||
)
|
||||
from app.services.maintenance_record_service import (
|
||||
build_records_import_template,
|
||||
@@ -58,6 +60,28 @@ def _require_ledger_admin():
|
||||
return user
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
"""
|
||||
从请求参数解析维修记录列表/导出共用的筛选条件。
|
||||
核心逻辑:兼容 snake_case 与 camelCase 报修日期参数;日期非法时抛出 ValidationError。
|
||||
"""
|
||||
report_date_from = _parse_date(
|
||||
request.args.get('report_date_from') or request.args.get('reportDateFrom'),
|
||||
'reportDateFrom',
|
||||
)
|
||||
report_date_to = _parse_date(
|
||||
request.args.get('report_date_to') or request.args.get('reportDateTo'),
|
||||
'reportDateTo',
|
||||
)
|
||||
return {
|
||||
'keyword': request.args.get('keyword'),
|
||||
'device_code': request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
'status': request.args.get('status'),
|
||||
'report_date_from': report_date_from,
|
||||
'report_date_to': report_date_to,
|
||||
}
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['GET'])
|
||||
def list_ledger_devices():
|
||||
"""查询设备台账列表,供 Agent 查询结果与右侧台账配置面板使用。"""
|
||||
@@ -121,10 +145,13 @@ def import_ledger_devices():
|
||||
def list_maintenance_records():
|
||||
"""查询设备维修记录,供 Agent 会话查询和结果卡片使用。"""
|
||||
_require_user()
|
||||
filters = _record_list_filters_from_request()
|
||||
result = list_records(
|
||||
keyword=request.args.get('keyword'),
|
||||
device_code=request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
status=request.args.get('status'),
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
@@ -142,10 +169,13 @@ def get_maintenance_record(record_id: int):
|
||||
def export_maintenance_records():
|
||||
"""按当前筛选条件导出设备维修记录 Excel。"""
|
||||
_require_ledger_admin()
|
||||
filters = _record_list_filters_from_request()
|
||||
data = build_records_export(
|
||||
keyword=request.args.get('keyword'),
|
||||
device_code=request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
status=request.args.get('status'),
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
)
|
||||
return send_file(
|
||||
BytesIO(data),
|
||||
|
||||
@@ -25,6 +25,7 @@ chat.py (/api/chat/completions)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
@@ -71,6 +72,66 @@ class DifyService:
|
||||
"video": {"mp4", "mov", "mpeg", "webm"},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _extract_workflow_failure_text(data: dict) -> str:
|
||||
"""
|
||||
从 Dify workflow_finished 失败事件里提取原始错误文本。
|
||||
AI 触发时机:Dify Tool/节点失败但 HTTP 仍为 200 时,用于日志留痕和用户友好提示转译。
|
||||
Args:
|
||||
data: Dify SSE 事件体。
|
||||
Returns:
|
||||
原始错误文本;没有失败信息时返回空字符串。
|
||||
"""
|
||||
if data.get("event") != "workflow_finished":
|
||||
return ""
|
||||
wf_data = data.get("data") if isinstance(data.get("data"), dict) else {}
|
||||
if str(wf_data.get("status") or "").lower() != "failed":
|
||||
return ""
|
||||
candidates = [
|
||||
data.get("message"),
|
||||
data.get("description"),
|
||||
data.get("error"),
|
||||
wf_data.get("message"),
|
||||
wf_data.get("description"),
|
||||
wf_data.get("error"),
|
||||
wf_data.get("errmsg"),
|
||||
]
|
||||
for candidate in candidates:
|
||||
if candidate is None:
|
||||
continue
|
||||
if isinstance(candidate, str) and candidate.strip():
|
||||
return candidate.strip()
|
||||
try:
|
||||
text = json.dumps(candidate, ensure_ascii=False, default=str)
|
||||
except Exception:
|
||||
text = str(candidate)
|
||||
if text.strip() and text.strip() != "null":
|
||||
return text.strip()
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _friendly_workflow_failure_message(raw_error: str) -> str:
|
||||
"""
|
||||
将 Dify/Tool 技术错误转成用户可读提示。
|
||||
Args:
|
||||
raw_error: Dify 返回的原始错误文本。
|
||||
Returns:
|
||||
面向用户展示的简短中文提示。
|
||||
"""
|
||||
text = str(raw_error or "")
|
||||
lower = text.lower()
|
||||
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
|
||||
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
|
||||
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
|
||||
return "设备维保查询服务暂时无法访问,请稍后重试或联系管理员检查工具授权。"
|
||||
if "ssrf" in lower or "blocked" in lower or "private or local network" in lower:
|
||||
return "设备维保查询服务暂时无法访问,请联系管理员检查工具网络访问配置。"
|
||||
if "failed to invoke tool" in lower or "tool" in lower:
|
||||
return "设备维保查询工具调用失败,请稍后重试;如持续失败请联系管理员。"
|
||||
if "maximum context length" in lower or "input_tokens" in lower:
|
||||
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
|
||||
return "设备维保助手暂时无法完成查询,请稍后重试。"
|
||||
|
||||
@staticmethod
|
||||
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if not isinstance(data, dict):
|
||||
@@ -944,6 +1005,22 @@ class DifyService:
|
||||
has_sent_answer = True
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
raw_workflow_error = DifyService._extract_workflow_failure_text(data)
|
||||
if raw_workflow_error:
|
||||
friendly_error = DifyService._friendly_workflow_failure_message(raw_workflow_error)
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[chat-stream] workflow failed request_id=%s agent_id=%s raw_error=%s",
|
||||
request_id,
|
||||
getattr(agent, 'id', None),
|
||||
raw_workflow_error,
|
||||
)
|
||||
data['message'] = friendly_error
|
||||
data['error'] = friendly_error
|
||||
if isinstance(data.get('data'), dict):
|
||||
data['data']['message'] = friendly_error
|
||||
data['data']['error'] = friendly_error
|
||||
|
||||
if event == 'workflow_finished' and not data.get('answer'):
|
||||
final_answer = build_final_answer_text(data, event)
|
||||
if final_answer:
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/maintenance_chat_service.py
|
||||
|
||||
用途:设备维保助手的会话查询直答服务,用于把设备编号/名称或上下文指代转换成设备台账卡片。
|
||||
依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、agent_registry.resolver、SQLAlchemy、SSE JSON 输出。
|
||||
逻辑:chat intent_routes/maintenance_chat 与 try_stream_chat 调用本服务;Agent 门控读 handler_config.intent_routes。
|
||||
逻辑:chat.py 先调用本服务尝试本地直答;识别到管理写入意图时返回固定引导文案;否则无法明确命中设备或记录时放行给 Dify。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,7 +23,16 @@ from app.services.maintenance_record_service import REPAIR_STATUS_LABELS, serial
|
||||
|
||||
MAINTENANCE_INTENT_ROUTE = 'maintenance_chat'
|
||||
MAINTENANCE_MESSAGE_TYPE = 'maintenance-device-result'
|
||||
MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE = (
|
||||
'该操作属于管理配置功能,请在设备维保助手底部点击“台账配置”或“登记维修”按钮进行操作。'
|
||||
'会话只处理查询和问答,不执行新增、修改、删除、导入、导出。'
|
||||
)
|
||||
REFERENCE_DEVICE_PATTERN = re.compile(r'(这个设备|這個設備|这台|這台|该设备|該設備|它|刚才那个|剛才那個|上一个设备|上一個設備|当前设备|當前設備)')
|
||||
RECORD_QUERY_PATTERN = re.compile(r'(维修|維修|报修|報修|故障|修复|修復|维修记录|維修記錄|维修历史|維修歷史|维修履历|維修履歷|记录|記錄|历史|歷史)')
|
||||
QUERY_HINT_PATTERN = re.compile(r'(查询|查詢|查看|检索|查一下|查下|最近|有哪些|是什么|多少|吗|嗎|么|麼|\?)')
|
||||
MANAGEMENT_WRITE_PATTERN = re.compile(
|
||||
r'(新增|新建|添加|修改|更新|编辑|編輯|删除|刪除|导入|導入|导出|導出|登记|登記|提交|配置|台账配置|台帳配置|设备配置|設備配置|报修|報修)'
|
||||
)
|
||||
|
||||
|
||||
def _agent_has_maintenance_chat_route(agent: Any) -> bool:
|
||||
@@ -164,6 +173,38 @@ def resolve_device_query_keyword(query: str, agent: Any, *, session_id: str | No
|
||||
return (keyword, 'explicit') if keyword else (None, 'none')
|
||||
|
||||
|
||||
def detect_query_mode(query: str) -> str:
|
||||
"""
|
||||
判断本轮维保查询应展示设备信息还是维修记录。
|
||||
AI 触发时机:本地直答生成卡片前调用,用于避免“查设备”和“查维修记录”渲染成同一张卡。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
Returns:
|
||||
records 表示维修记录查询;device 表示设备信息查询。
|
||||
"""
|
||||
return 'records' if RECORD_QUERY_PATTERN.search(_clean_text(query)) else 'device'
|
||||
|
||||
|
||||
def detect_management_write_intent(query: str) -> bool:
|
||||
"""
|
||||
判断用户是否在会话里尝试执行台账/维修记录的写入或管理配置动作。
|
||||
核心逻辑:出现新增、导入、删除等写入动词时拦截并引导到底部管理按钮;纯查询语句放行给本地直答或 Dify。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
Returns:
|
||||
True 表示应返回管理操作引导文案,不应继续走 Dify 写入流程。
|
||||
"""
|
||||
text = _clean_text(query)
|
||||
if not text or not MANAGEMENT_WRITE_PATTERN.search(text):
|
||||
return False
|
||||
if QUERY_HINT_PATTERN.search(text) and not re.search(
|
||||
r'(新增|新建|添加|修改|更新|编辑|編輯|删除|刪除|导入|導入|导出|導出|登记|登記|提交|配置|报修|報修)',
|
||||
text,
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _find_device(keyword: str) -> MaintenanceDevice | None:
|
||||
"""按设备编号优先,其次按设备名称模糊匹配查找单台设备。"""
|
||||
value = _clean_text(keyword)
|
||||
@@ -259,6 +300,7 @@ def _build_records_payload(keyword: str, records: list[MaintenanceRecord]) -> di
|
||||
status_counts[key] = status_counts.get(key, 0) + 1
|
||||
return {
|
||||
'source': 'maintenance_record_query',
|
||||
'queryMode': 'records',
|
||||
'matched': True,
|
||||
'keyword': keyword,
|
||||
'device': _build_record_device_snapshot(records[0]) if records else None,
|
||||
@@ -270,7 +312,6 @@ def _build_records_payload(keyword: str, records: list[MaintenanceRecord]) -> di
|
||||
'ledgerMatched': False,
|
||||
},
|
||||
'actions': [
|
||||
{'id': 'viewMaintenanceHistory', 'label': '查维修历史'},
|
||||
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
|
||||
],
|
||||
}
|
||||
@@ -293,6 +334,7 @@ def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, r
|
||||
status_counts[key] = status_counts.get(key, 0) + 1
|
||||
return {
|
||||
'source': 'maintenance_device_query',
|
||||
'queryMode': 'device',
|
||||
'matched': True,
|
||||
'device': serialize_device(device),
|
||||
'records': serialized_records,
|
||||
@@ -302,19 +344,19 @@ def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, r
|
||||
'statusLabels': REPAIR_STATUS_LABELS,
|
||||
},
|
||||
'actions': [
|
||||
{'id': 'viewMaintenanceHistory', 'label': '查维修历史'},
|
||||
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def build_device_query_result(keyword: str, *, include_records: bool = True, record_limit: int = 5) -> dict[str, Any]:
|
||||
def build_device_query_result(keyword: str, *, include_records: bool = True, record_limit: int = 5, query_mode: str = 'device') -> dict[str, Any]:
|
||||
"""
|
||||
查询设备台账并返回统一结构,供会话直答和 Dify Tool 共用。
|
||||
Args:
|
||||
keyword: 设备编号或设备名称。
|
||||
include_records: 是否附带最近维修记录。
|
||||
record_limit: 最近维修记录最大返回条数。
|
||||
query_mode: device 展示设备信息;records 展示维修记录。
|
||||
Returns:
|
||||
设备查询结果 payload。
|
||||
"""
|
||||
@@ -324,7 +366,38 @@ def build_device_query_result(keyword: str, *, include_records: bool = True, rec
|
||||
include_records,
|
||||
record_limit,
|
||||
)
|
||||
normalized_mode = 'records' if query_mode == 'records' else 'device'
|
||||
device = _find_device(keyword)
|
||||
if normalized_mode == 'records':
|
||||
records = _find_records(keyword, record_limit=record_limit) if include_records else []
|
||||
if records:
|
||||
current_app.logger.info('[maintenance-chat] records mode matched keyword=%s count=%s', keyword, len(records))
|
||||
payload = _build_records_payload(keyword, records)
|
||||
if device:
|
||||
payload['device'] = serialize_device(device)
|
||||
payload.setdefault('summary', {})['ledgerMatched'] = True
|
||||
return payload
|
||||
if device:
|
||||
payload = _build_payload(device, include_records=False, record_limit=0)
|
||||
payload['source'] = 'maintenance_record_query'
|
||||
payload['queryMode'] = 'records'
|
||||
payload['records'] = []
|
||||
payload['summary'] = {
|
||||
'recentRecordCount': 0,
|
||||
'statusCounts': {},
|
||||
'statusLabels': REPAIR_STATUS_LABELS,
|
||||
'ledgerMatched': True,
|
||||
}
|
||||
return payload
|
||||
current_app.logger.info('[maintenance-chat] no records matched keyword=%s', keyword)
|
||||
return {
|
||||
'source': 'maintenance_record_query',
|
||||
'queryMode': 'records',
|
||||
'matched': False,
|
||||
'keyword': keyword,
|
||||
'device': None,
|
||||
'records': [],
|
||||
}
|
||||
if not device:
|
||||
records = _find_records(keyword, record_limit=record_limit) if include_records else []
|
||||
if records:
|
||||
@@ -333,6 +406,7 @@ def build_device_query_result(keyword: str, *, include_records: bool = True, rec
|
||||
current_app.logger.info('[maintenance-chat] no device or records matched keyword=%s', keyword)
|
||||
return {
|
||||
'source': 'maintenance_device_query',
|
||||
'queryMode': 'device',
|
||||
'matched': False,
|
||||
'keyword': keyword,
|
||||
'device': None,
|
||||
@@ -428,10 +502,16 @@ def stream_chat(
|
||||
keyword_source,
|
||||
query,
|
||||
)
|
||||
result = result or build_device_query_result(keyword, include_records=True, record_limit=5)
|
||||
query_mode = detect_query_mode(query)
|
||||
result = result or build_device_query_result(
|
||||
keyword,
|
||||
include_records=query_mode == 'records',
|
||||
record_limit=10 if query_mode == 'records' else 0,
|
||||
query_mode=query_mode,
|
||||
)
|
||||
|
||||
if result.get('matched'):
|
||||
content = '已查询设备台账信息,下面是匹配结果。'
|
||||
content = '已查询设备信息,下面是匹配结果。'
|
||||
if result.get('source') == 'maintenance_record_query':
|
||||
content = '已查询设备维修记录,下面是匹配结果。'
|
||||
if keyword_source == 'context':
|
||||
@@ -439,7 +519,7 @@ def stream_chat(
|
||||
payload = result
|
||||
message_type = MAINTENANCE_MESSAGE_TYPE
|
||||
else:
|
||||
content = f'未找到与“{keyword or query}”匹配的设备台账信息,请检查设备编号或设备名称。'
|
||||
content = f'未找到与“{keyword or query}”匹配的设备信息,请检查设备编号或设备名称。'
|
||||
payload = result
|
||||
message_type = 'text'
|
||||
|
||||
@@ -489,6 +569,69 @@ def stream_chat(
|
||||
}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def stream_management_redirect(
|
||||
query: str,
|
||||
user: Any,
|
||||
agent: Any,
|
||||
conversation_id: str | None = None,
|
||||
session_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> Iterator[str]:
|
||||
"""
|
||||
返回管理配置类操作的统一引导文案,阻止会话内直接执行写入动作。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
user: 当前用户代理对象。
|
||||
agent: 当前 Agent 代理对象。
|
||||
conversation_id: 外部会话 ID。
|
||||
session_id: 本地会话 ID。
|
||||
request_id: 当前请求 ID。
|
||||
Yields:
|
||||
SSE data 帧。
|
||||
"""
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or session_id or f'maintenance_{int(time.time())}'
|
||||
content = MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE
|
||||
current_app.logger.info(
|
||||
'[maintenance-chat] management redirect request_id=%s user_id=%s agent_id=%s query=%s',
|
||||
request_id,
|
||||
getattr(user, 'id', None),
|
||||
getattr(agent, 'id', None),
|
||||
query,
|
||||
)
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': content}, ensure_ascii=False)}\n\n"
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=getattr(user, 'id', None),
|
||||
agent_id=getattr(agent, 'id', None),
|
||||
conversation_id=final_conversation_id,
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
answer=content,
|
||||
tokens_used=0,
|
||||
latency=int((time.time() - start_time) * 1000),
|
||||
message_type='text',
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[maintenance-chat] failed to log management redirect: %s', exc)
|
||||
db.session.rollback()
|
||||
|
||||
yield f"data: {json.dumps({
|
||||
'event': 'message_end',
|
||||
'answer': content,
|
||||
'replace_answer': True,
|
||||
'type': 'text',
|
||||
'chat_log_id': chat_log_id,
|
||||
'conversation_id': final_conversation_id,
|
||||
'metadata': {'source': 'maintenance_management_redirect'},
|
||||
}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
def try_stream_chat(
|
||||
query: str,
|
||||
user: Any,
|
||||
@@ -510,6 +653,17 @@ def try_stream_chat(
|
||||
Returns:
|
||||
SSE 生成器;返回 None 表示本地无法处理,应继续走 Dify。
|
||||
"""
|
||||
if not is_maintenance_chat_agent(agent):
|
||||
return None
|
||||
if detect_management_write_intent(query):
|
||||
return stream_management_redirect(
|
||||
query,
|
||||
user,
|
||||
agent,
|
||||
conversation_id,
|
||||
session_id=session_id,
|
||||
request_id=request_id,
|
||||
)
|
||||
keyword, keyword_source = resolve_device_query_keyword(query, agent, session_id=session_id)
|
||||
if not keyword:
|
||||
current_app.logger.info(
|
||||
@@ -520,7 +674,13 @@ def try_stream_chat(
|
||||
query,
|
||||
)
|
||||
return None
|
||||
result = build_device_query_result(keyword, include_records=True, record_limit=5)
|
||||
query_mode = detect_query_mode(query)
|
||||
result = build_device_query_result(
|
||||
keyword,
|
||||
include_records=query_mode == 'records',
|
||||
record_limit=10 if query_mode == 'records' else 0,
|
||||
query_mode=query_mode,
|
||||
)
|
||||
if not result.get('matched'):
|
||||
current_app.logger.info(
|
||||
'[maintenance-chat] bypass local unmatched request_id=%s keyword=%s keyword_source=%s query=%s',
|
||||
@@ -548,5 +708,7 @@ class MaintenanceChatService:
|
||||
|
||||
supports = staticmethod(supports)
|
||||
can_attempt = staticmethod(can_attempt)
|
||||
detect_management_write_intent = staticmethod(detect_management_write_intent)
|
||||
stream_management_redirect = staticmethod(stream_management_redirect)
|
||||
stream_chat = staticmethod(stream_chat)
|
||||
try_stream_chat = staticmethod(try_stream_chat)
|
||||
@@ -25,6 +25,8 @@ from app.path_utils import backend_dir
|
||||
from app.services.maintenance_ledger_service import _load_import_workbook, _operator_name, _parse_date, _write_audit
|
||||
|
||||
REPAIR_STATUS_VALUES = {'pending', 'processing', 'done', 'cancelled'}
|
||||
REPAIR_STATUS_FILTER_ACTIVE = 'active'
|
||||
ACTIVE_REPAIR_STATUSES = ('pending', 'processing')
|
||||
REPAIR_STATUS_LABELS = {
|
||||
'pending': '待维修',
|
||||
'processing': '维修中',
|
||||
@@ -146,16 +148,60 @@ def _normalize_payload(data: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _get_required_device(device_code: str) -> MaintenanceDevice:
|
||||
"""
|
||||
按设备编号读取台账设备,维修记录写入前必须命中。
|
||||
Args:
|
||||
device_code: 维修记录表单里的设备编号。
|
||||
Returns:
|
||||
已存在的设备台账记录。
|
||||
Raises:
|
||||
ValidationError: 设备编号不存在于台账,禁止新增或更新维修记录。
|
||||
"""
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=device_code).first()
|
||||
if not device:
|
||||
raise ValidationError('设备不存在于台账中,不能添加维修记录', details={'deviceCode': device_code})
|
||||
return device
|
||||
|
||||
|
||||
def _apply_device_snapshot(values: dict[str, Any], device: MaintenanceDevice) -> None:
|
||||
"""
|
||||
将设备台账快照写入维修记录,保证记录归属和展示字段一致。
|
||||
Args:
|
||||
values: 待写入 MaintenanceRecord 的字段字典。
|
||||
device: 已校验存在的设备台账记录。
|
||||
"""
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def list_records(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
device_code: str | None = None,
|
||||
status: str | None = None,
|
||||
report_date_from: date | None = None,
|
||||
report_date_to: date | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""分页查询维修记录。"""
|
||||
query = _records_query(keyword=keyword, device_code=device_code, status=status)
|
||||
"""
|
||||
分页查询维修记录。
|
||||
核心逻辑:复用 _records_query 构造筛选;status=active 表示待维修+维修中;报修日期区间可选。
|
||||
"""
|
||||
query = _records_query(
|
||||
keyword=keyword,
|
||||
device_code=device_code,
|
||||
status=status,
|
||||
report_date_from=report_date_from,
|
||||
report_date_to=report_date_to,
|
||||
)
|
||||
total = query.count()
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(200, page_size))
|
||||
@@ -168,13 +214,30 @@ def list_records(
|
||||
return {'items': [serialize_record(item) for item in items], 'total': total, 'page': page, 'pageSize': page_size}
|
||||
|
||||
|
||||
def _records_query(*, keyword: str | None = None, device_code: str | None = None, status: str | None = None):
|
||||
"""构造维修记录查询,供列表和导出复用。"""
|
||||
def _records_query(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
device_code: str | None = None,
|
||||
status: str | None = None,
|
||||
report_date_from: date | None = None,
|
||||
report_date_to: date | None = None,
|
||||
):
|
||||
"""
|
||||
构造维修记录查询,供列表和导出复用。
|
||||
核心逻辑:status=active 映射为 pending+processing;report_date_from/to 按报修日期闭区间过滤。
|
||||
"""
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
if device_code:
|
||||
query = query.filter(MaintenanceRecord.device_code == device_code)
|
||||
if status:
|
||||
status = _clean_text(status)
|
||||
if status == REPAIR_STATUS_FILTER_ACTIVE:
|
||||
query = query.filter(MaintenanceRecord.repair_status.in_(ACTIVE_REPAIR_STATUSES))
|
||||
elif status in REPAIR_STATUS_VALUES:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
if report_date_from:
|
||||
query = query.filter(MaintenanceRecord.report_date >= report_date_from)
|
||||
if report_date_to:
|
||||
query = query.filter(MaintenanceRecord.report_date <= report_date_to)
|
||||
keyword = _clean_text(keyword)
|
||||
if keyword:
|
||||
like = f'%{keyword}%'
|
||||
@@ -331,10 +394,23 @@ def _fill_history_sheet(ws, records: list[MaintenanceRecord]) -> None:
|
||||
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
||||
|
||||
|
||||
def build_records_export(*, keyword: str | None = None, device_code: str | None = None, status: str | None = None) -> bytes:
|
||||
"""按设备维修保养履历模板导出维修记录 Excel。"""
|
||||
def build_records_export(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
device_code: str | None = None,
|
||||
status: str | None = None,
|
||||
report_date_from: date | None = None,
|
||||
report_date_to: date | None = None,
|
||||
) -> bytes:
|
||||
"""按设备维修保养履历模板导出维修记录 Excel,筛选条件与列表查询保持一致。"""
|
||||
rows = (
|
||||
_records_query(keyword=keyword, device_code=device_code, status=status)
|
||||
_records_query(
|
||||
keyword=keyword,
|
||||
device_code=device_code,
|
||||
status=status,
|
||||
report_date_from=report_date_from,
|
||||
report_date_to=report_date_to,
|
||||
)
|
||||
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
|
||||
.limit(5000)
|
||||
.all()
|
||||
@@ -394,9 +470,8 @@ def _parse_history_pair_value(text: str | None, label: str) -> str | None:
|
||||
return compact_raw[len(compact_label):].strip(' ::')
|
||||
return raw
|
||||
|
||||
|
||||
def _parse_history_date(value: Any) -> date | None:
|
||||
"""解析履历模板中的日期,兼容 Excel 序列号和常规日期字符串。"""
|
||||
"""Parse dates from legacy maintenance history templates."""
|
||||
if isinstance(value, (int, float)):
|
||||
try:
|
||||
import xlrd
|
||||
@@ -407,6 +482,28 @@ def _parse_history_date(value: Any) -> date | None:
|
||||
return _parse_date(value, 'repairDate')
|
||||
|
||||
|
||||
def _parse_history_row_date(value: Any, *, row_no: int, label: str) -> date | None:
|
||||
"""
|
||||
Parse a date cell in a history row and convert backend validation text into an import-friendly row error.
|
||||
Args:
|
||||
value: Raw worksheet cell value.
|
||||
row_no: Excel row number, shown to users for correction.
|
||||
label: User-facing date field label.
|
||||
Returns:
|
||||
Parsed date or None.
|
||||
Raises:
|
||||
ValidationError: The date is not a supported format.
|
||||
"""
|
||||
try:
|
||||
return _parse_history_date(value)
|
||||
except ValidationError as exc:
|
||||
text = str(value or '').strip() or '-'
|
||||
raise ValidationError(
|
||||
f'第 {row_no} 行{label}格式不正确:{text},请改为 YYYY-MM-DD 或 YYYY/MM/DD',
|
||||
details={'row': row_no, 'field': label, 'value': text},
|
||||
) from exc
|
||||
|
||||
|
||||
def _is_history_template(ws: Any) -> bool:
|
||||
"""判断工作表是否为设备维修保养履历模板。"""
|
||||
device_code = _find_history_device_code(ws)
|
||||
@@ -478,8 +575,8 @@ def _history_record_payloads(ws: Any) -> list[dict[str, Any]]:
|
||||
continue
|
||||
if not fault_description and not repair_description:
|
||||
continue
|
||||
report_date = _parse_history_date(raw_report_date) or date.today()
|
||||
repair_date = _parse_history_date(raw_repair_date) or report_date
|
||||
report_date = _parse_history_row_date(raw_report_date, row_no=row_no, label='报修日期') or date.today()
|
||||
repair_date = _parse_history_row_date(raw_repair_date, row_no=row_no, label='维修日期') or report_date
|
||||
payloads.append(
|
||||
{
|
||||
'device_code': device_code,
|
||||
@@ -543,16 +640,8 @@ def import_records_from_excel(file_obj: Any, *, operator: Any | None = None, req
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
values = _normalize_payload(raw)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
device = _get_required_device(values['device_code'])
|
||||
_apply_device_snapshot(values, device)
|
||||
record = MaintenanceRecord(**values, created_by=operator_name, updated_by=operator_name)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
@@ -588,28 +677,13 @@ def _import_history_records(ws: Any, *, operator: Any | None = None, request_id:
|
||||
operator_name = _operator_name(operator)
|
||||
for raw in payloads:
|
||||
row_no = raw.pop('_row_no', None)
|
||||
device_name = raw.pop('_device_name', None)
|
||||
model_spec = raw.pop('_model_spec', None)
|
||||
raw.pop('_device_name', None)
|
||||
raw.pop('_model_spec', None)
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
values = _normalize_payload(raw)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
else:
|
||||
values.update(
|
||||
{
|
||||
'device_name': device_name,
|
||||
'model_spec': model_spec,
|
||||
}
|
||||
)
|
||||
device = _get_required_device(values['device_code'])
|
||||
_apply_device_snapshot(values, device)
|
||||
record = MaintenanceRecord(**values, created_by=operator_name, updated_by=operator_name)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
@@ -641,16 +715,8 @@ def get_record(record_id: int) -> dict[str, Any]:
|
||||
def create_record(data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""新增维修记录,并写入审计日志。"""
|
||||
values = _normalize_payload(data)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
device = _get_required_device(values['device_code'])
|
||||
_apply_device_snapshot(values, device)
|
||||
operator_name = _operator_name(operator)
|
||||
record = MaintenanceRecord(**values, created_by=operator_name, updated_by=operator_name)
|
||||
db.session.add(record)
|
||||
@@ -675,15 +741,8 @@ def update_record(record_id: int, data: dict[str, Any], *, operator: Any | None
|
||||
raise NotFoundError('Maintenance record not found')
|
||||
before = _record_to_audit_dict(record)
|
||||
values = _normalize_payload(data)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id if device else None,
|
||||
'device_name': device.device_name if device else None,
|
||||
'model_spec': device.model_spec if device else None,
|
||||
'install_location': device.install_location if device else None,
|
||||
}
|
||||
)
|
||||
device = _get_required_device(values['device_code'])
|
||||
_apply_device_snapshot(values, device)
|
||||
for key, value in values.items():
|
||||
setattr(record, key, value)
|
||||
operator_name = _operator_name(operator)
|
||||
|
||||
@@ -10,6 +10,8 @@ from app import db
|
||||
from app.models import Agent, ChatLog, MaintenanceDevice, User
|
||||
from app.services.maintenance_chat_service import (
|
||||
MAINTENANCE_MESSAGE_TYPE,
|
||||
MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE,
|
||||
detect_management_write_intent,
|
||||
resolve_device_query_keyword,
|
||||
try_stream_chat,
|
||||
)
|
||||
@@ -132,3 +134,28 @@ def test_resolve_context_device_works_for_custom_agent_name_with_intent_route(ap
|
||||
|
||||
assert keyword == 'A070700002'
|
||||
assert source == 'context'
|
||||
|
||||
|
||||
def test_detect_management_write_intent(app):
|
||||
"""断言新增、导入等写入意图会被识别,纯查询语句不会误判。"""
|
||||
assert detect_management_write_intent('新增设备 A070700001') is True
|
||||
assert detect_management_write_intent('导入设备台账 Excel') is True
|
||||
assert detect_management_write_intent('A070700001 的维修记录') is False
|
||||
assert detect_management_write_intent('查询 A070700001 最近维修记录') is False
|
||||
|
||||
|
||||
def test_try_stream_chat_redirects_management_write_intent(app):
|
||||
"""断言管理写入类问题由本地返回引导文案,不再交给 Dify。"""
|
||||
user, agent = _create_user_and_agent()
|
||||
|
||||
redirect_stream = try_stream_chat(
|
||||
'新增一条维修记录,设备 A070700001,线断了',
|
||||
user,
|
||||
agent,
|
||||
session_id='session-maintenance-3',
|
||||
request_id='req-redirect',
|
||||
)
|
||||
|
||||
assert redirect_stream is not None
|
||||
frames = list(redirect_stream)
|
||||
assert any(MAINTENANCE_MANAGEMENT_REDIRECT_MESSAGE in frame for frame in frames)
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* features/chat/components/ChatInputBar.vue
|
||||
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
|
||||
* 逻辑:设备维保助手的管理入口(设备台账、登记维修)与语音按钮同侧排列,发送按钮独占右侧。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
@@ -259,27 +260,6 @@ watch(
|
||||
<span>点发送开始处理</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isMaintenanceAgent && canManageMaintenance"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
|
||||
>
|
||||
<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>
|
||||
<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-create-record')"
|
||||
>
|
||||
{{ $t('maintenance.panel.recordTitle') }}
|
||||
</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
|
||||
@@ -359,7 +339,7 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref="kbMenuRef" class="relative">
|
||||
<div v-if="!isMaintenanceAgent" ref="kbMenuRef" class="relative">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="kbDropdownDisabled"
|
||||
@@ -386,6 +366,27 @@ watch(
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isMaintenanceAgent && canManageMaintenance"
|
||||
class="flex flex-wrap items-center gap-2"
|
||||
:title="$t('maintenance.panel.adminOnly')"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-300 bg-brand-50 px-3 py-1.5 text-xs font-semibold text-brand-700 transition-colors hover:bg-brand-100"
|
||||
@click="emit('maintenance-ledger-config')"
|
||||
>
|
||||
{{ $t('maintenance.chat.manageLedger') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-300 bg-brand-50 px-3 py-1.5 text-xs font-semibold text-brand-700 transition-colors hover:bg-brand-100"
|
||||
@click="emit('maintenance-create-record')"
|
||||
>
|
||||
{{ $t('maintenance.chat.logRepair') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
@@ -402,7 +403,7 @@ watch(
|
||||
v-else
|
||||
type="button"
|
||||
:disabled="!canSendMessage"
|
||||
class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:class="!canSendMessage
|
||||
? 'border-default bg-slate-100 text-muted'
|
||||
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
|
||||
|
||||
@@ -13,6 +13,8 @@ import type { ShippingMappingHandlers } from './messages/ShippingInventoryMappin
|
||||
import type { TrainingHandlers } from './messages/TrainingExamQuestionMessage.vue';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ToolRunProgress } from '../api/toolRunProgress.api';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
const {
|
||||
messages,
|
||||
@@ -55,6 +57,9 @@ const emit = defineEmits<{
|
||||
'open-feedback': [index: number];
|
||||
'select-question': [question: string];
|
||||
'scroll-to-bottom': [];
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
}>();
|
||||
|
||||
const bindScrollContainer = (node: unknown) => {
|
||||
@@ -122,6 +127,9 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
@resend="emit('resend', $event)"
|
||||
@regenerate="emit('regenerate')"
|
||||
@open-feedback="emit('open-feedback', index)"
|
||||
@maintenance-edit-record="emit('maintenance-edit-record', $event)"
|
||||
@maintenance-view-record-history="emit('maintenance-view-record-history', $event)"
|
||||
@maintenance-create-record-for-device="emit('maintenance-create-record-for-device', $event)"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
|
||||
@@ -21,6 +21,19 @@ import MaintenanceRecordManagerPanel from '@/features/maintenance/components/Mai
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
import {
|
||||
MAINTENANCE_PANEL_DEFAULT_WIDTH,
|
||||
buildMaintenancePanelWidthStyle,
|
||||
clampMaintenancePanelWidth,
|
||||
} from '@/features/maintenance/utils/maintenance-panel-layout.utils';
|
||||
|
||||
type MaintenanceRecordPanelCommand = {
|
||||
mode: 'list' | 'create';
|
||||
device: MaintenanceDevice;
|
||||
nonce: number;
|
||||
};
|
||||
|
||||
const page = useChatPageContext();
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
@@ -35,18 +48,16 @@ const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].inc
|
||||
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
|
||||
const isTrainingWorkspaceExpanded = ref(false);
|
||||
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
|
||||
const maintenancePanelWidth = ref(560);
|
||||
const maintenanceEditRecord = ref<MaintenanceRecord | null>(null);
|
||||
const maintenanceRecordPanelCommand = ref<MaintenanceRecordPanelCommand | null>(null);
|
||||
const maintenancePanelWidth = ref(MAINTENANCE_PANEL_DEFAULT_WIDTH);
|
||||
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',
|
||||
};
|
||||
return buildMaintenancePanelWidthStyle(maintenancePanelWidth.value);
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -61,8 +72,7 @@ const startMaintenancePanelResize = (event: MouseEvent): void => {
|
||||
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));
|
||||
maintenancePanelWidth.value = clampMaintenancePanelWidth(nextWidth, window.innerWidth);
|
||||
};
|
||||
const stopResize = () => {
|
||||
isMaintenancePanelResizing.value = false;
|
||||
@@ -73,6 +83,42 @@ const startMaintenancePanelResize = (event: MouseEvent): void => {
|
||||
window.addEventListener('mouseup', stopResize);
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开右侧维修记录面板并进入指定记录的编辑表单。
|
||||
* @param record - 会话结果表格中选中的维修记录。
|
||||
*/
|
||||
const openMaintenanceRecordEdit = (record: MaintenanceRecord): void => {
|
||||
maintenanceEditRecord.value = record;
|
||||
maintenanceRecordPanelCommand.value = null;
|
||||
maintenancePanel.value = 'record';
|
||||
};
|
||||
|
||||
/**
|
||||
* 鎵撳紑鍙充晶缁翠慨璁板綍鍒楄〃锛屽苟鎸夊綋鍓嶈澶囩紪鍙风瓫閫夊巻鍙茶褰曘€?
|
||||
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
|
||||
*/
|
||||
const openMaintenanceRecordHistory = (device: MaintenanceDevice): void => {
|
||||
maintenanceEditRecord.value = null;
|
||||
maintenanceRecordPanelCommand.value = { mode: 'list', device, nonce: Date.now() };
|
||||
maintenancePanel.value = 'record';
|
||||
};
|
||||
|
||||
/**
|
||||
* 鎵撳紑鍙充晶缁翠慨璁板綍鏂板琛ㄥ崟锛屽苟棰勫~褰撳墠璁惧缂栧彿銆?
|
||||
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
|
||||
*/
|
||||
const openMaintenanceRecordCreate = (device: MaintenanceDevice): void => {
|
||||
maintenanceEditRecord.value = null;
|
||||
maintenanceRecordPanelCommand.value = { mode: 'create', device, nonce: Date.now() };
|
||||
maintenancePanel.value = 'record';
|
||||
};
|
||||
|
||||
const openBlankMaintenanceRecordCreate = (): void => {
|
||||
maintenanceEditRecord.value = null;
|
||||
maintenanceRecordPanelCommand.value = null;
|
||||
maintenancePanel.value = 'record';
|
||||
};
|
||||
|
||||
// 切换 Agent 时,重置工作区展开状态,确保每次进入都是收起状态(聊天优先)
|
||||
watch(() => page.currentAgentId, () => {
|
||||
isTrainingWorkspaceExpanded.value = false;
|
||||
@@ -207,6 +253,9 @@ watch(() => page.currentAgentId, () => {
|
||||
@open-feedback="page.handleOpenFeedback($event)"
|
||||
@select-question="page.handleSend"
|
||||
@scroll-to-bottom="page.scrollToBottom"
|
||||
@maintenance-edit-record="openMaintenanceRecordEdit"
|
||||
@maintenance-view-record-history="openMaintenanceRecordHistory"
|
||||
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
|
||||
/>
|
||||
|
||||
<ChatInputBar
|
||||
@@ -241,7 +290,7 @@ watch(() => page.currentAgentId, () => {
|
||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
||||
@maintenance-ledger-config="maintenancePanel = 'ledger'"
|
||||
@maintenance-create-record="maintenancePanel = 'record'"
|
||||
@maintenance-create-record="openBlankMaintenanceRecordCreate"
|
||||
@clear-shipping-focus="page.clearShippingFocus"
|
||||
/>
|
||||
</div>
|
||||
@@ -293,7 +342,11 @@ watch(() => page.currentAgentId, () => {
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||
<LedgerConfigPanel v-if="maintenancePanel === 'ledger'" />
|
||||
<MaintenanceRecordManagerPanel v-else />
|
||||
<MaintenanceRecordManagerPanel
|
||||
v-else
|
||||
:edit-record="maintenanceEditRecord"
|
||||
:command="maintenanceRecordPanelCommand"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
|
||||
import TrainingResultCard from './TrainingResultCard.vue';
|
||||
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
export interface ChatMessageBubbleHandlers {
|
||||
renderMarkdown: (text: string) => string;
|
||||
@@ -76,6 +78,9 @@ const emit = defineEmits<{
|
||||
resend: [content: string];
|
||||
regenerate: [];
|
||||
'open-feedback': [];
|
||||
'maintenance-edit-record': [record: MaintenanceRecord];
|
||||
'maintenance-view-record-history': [device: MaintenanceDevice];
|
||||
'maintenance-create-record-for-device': [device: MaintenanceDevice];
|
||||
}>();
|
||||
|
||||
const authStore = useAuthStore();
|
||||
@@ -693,6 +698,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
<MaintenanceDeviceResultCard
|
||||
v-else-if="message.type === 'maintenance-device-result'"
|
||||
:message="message"
|
||||
@edit-record="emit('maintenance-edit-record', $event)"
|
||||
@view-record-history="emit('maintenance-view-record-history', $event)"
|
||||
@create-record="emit('maintenance-create-record-for-device', $event)"
|
||||
/>
|
||||
<TrainingExamQuestionMessage
|
||||
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
|
||||
|
||||
@@ -1,31 +1,51 @@
|
||||
/**
|
||||
* features/chat/components/messages/MaintenanceDeviceResultCard.vue
|
||||
* 用途:设备维保助手会话中的设备台账查询结果卡片。
|
||||
* 依赖:chat.types、ledger/record 类型、vue-i18n。
|
||||
* 逻辑:后端返回 maintenance-device-result payload 后,本组件按原型展示设备基础信息、匹配状态和快捷操作。
|
||||
* 用途:设备维保助手会话中的设备信息与维修记录结果卡片。
|
||||
* 依赖:auth.store、chat.types、maintenance ledger/record 类型、repair-status-display.utils、maintenance-panel-layout.utils、vue-i18n。
|
||||
* 逻辑:后端返回 queryMode=device 时按台账配置表单同序展示设备信息;queryMode=records 时按维修记录配置字段展示记录列表。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||
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';
|
||||
import { repairStatusBadgeClass } from '@/features/maintenance/utils/repair-status-display.utils';
|
||||
import { buildMaintenancePanelWidthStyle } from '@/features/maintenance/utils/maintenance-panel-layout.utils';
|
||||
|
||||
interface MaintenanceDeviceResultPayload {
|
||||
matched?: boolean;
|
||||
queryMode?: 'device' | 'records';
|
||||
keyword?: string;
|
||||
device?: MaintenanceDevice;
|
||||
records?: MaintenanceRecord[];
|
||||
summary?: {
|
||||
recentRecordCount?: number;
|
||||
statusCounts?: Record<string, number>;
|
||||
ledgerMatched?: boolean;
|
||||
};
|
||||
actions?: Array<{ id: string; label: string }>;
|
||||
}
|
||||
|
||||
type DisplayCell = {
|
||||
label: string;
|
||||
value: string | number | null | undefined;
|
||||
};
|
||||
|
||||
const props = defineProps<{
|
||||
message: ChatMessage;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'edit-record': [record: MaintenanceRecord];
|
||||
'view-record-history': [device: MaintenanceDevice];
|
||||
'create-record': [device: MaintenanceDevice];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
const recordDetailPanelStyle = buildMaintenancePanelWidthStyle();
|
||||
|
||||
const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
|
||||
const raw = props.message.payload;
|
||||
@@ -35,21 +55,39 @@ const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
|
||||
|
||||
const device = computed(() => payload.value?.device || null);
|
||||
const records = computed(() => payload.value?.records || []);
|
||||
const queryMode = computed(() => payload.value?.queryMode === 'records' ? 'records' : 'device');
|
||||
const hasResult = computed(() => Boolean(device.value || records.value.length));
|
||||
const ledgerMatched = computed(() => payload.value?.summary?.ledgerMatched !== false);
|
||||
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(authStore.user?.role || '')));
|
||||
const selectedRecord = ref<MaintenanceRecord | null>(null);
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
const status = device.value?.deviceStatus;
|
||||
const deviceStatusLabel = (status?: string | null) => {
|
||||
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 recordStatusLabel = (status?: string | null) => {
|
||||
if (status === 'pending') return t('maintenance.record.status.pending');
|
||||
if (status === 'processing') return t('maintenance.record.status.processing');
|
||||
if (status === 'done') return t('maintenance.record.status.done');
|
||||
if (status === 'cancelled') return t('maintenance.record.status.cancelled');
|
||||
return status || '-';
|
||||
};
|
||||
|
||||
const displayValue = (value: DisplayCell['value']) => {
|
||||
if (value === null || value === undefined || value === '') return '-';
|
||||
return String(value);
|
||||
};
|
||||
|
||||
const firstCell = (row: DisplayCell[]): DisplayCell => row[0] || { label: '', value: '' };
|
||||
|
||||
const deviceRows = computed<DisplayCell[][]>(() => {
|
||||
const item = device.value;
|
||||
if (!item) return [];
|
||||
// 字段顺序与 LedgerConfigPanel 设备配置表单保持一致(左列优先、逐行两列)。
|
||||
return [
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.deviceCode'), value: item.deviceCode },
|
||||
@@ -57,76 +95,244 @@ const rows = computed(() => {
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.modelSpec'), value: item.modelSpec },
|
||||
{ label: t('maintenance.ledger.fields.department'), value: item.department },
|
||||
{ label: t('maintenance.ledger.fields.manufacturer'), value: item.manufacturer },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.devicePosition'), value: item.installLocation },
|
||||
{ label: t('maintenance.ledger.fields.deviceStatus'), value: statusLabel.value },
|
||||
{ label: t('maintenance.ledger.fields.deviceStatus'), value: deviceStatusLabel(item.deviceStatus) },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.manufacturer'), value: item.manufacturer },
|
||||
{ label: t('maintenance.ledger.fields.startDate'), value: item.startDate },
|
||||
{ label: t('maintenance.ledger.fields.department'), value: item.department },
|
||||
{ label: t('maintenance.ledger.fields.responsibleUser'), value: item.responsibleUser },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.productionDate'), value: item.productionDate },
|
||||
{ label: t('maintenance.ledger.fields.entryDate'), value: item.entryDate },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.originalValue'), value: item.originalValue },
|
||||
{ label: t('maintenance.ledger.fields.residualValue'), value: item.residualValue },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.accountSet'), value: item.accountSet },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.remark'), value: item.remark },
|
||||
],
|
||||
];
|
||||
});
|
||||
|
||||
const latestRepairDate = computed(() => records.value[0]?.reportDate || '-');
|
||||
const totalCost = computed(() => records.value.reduce((sum, item) => {
|
||||
const value = Number(String(item.repairCost || '').replace(/[^\d.-]/g, ''));
|
||||
return Number.isFinite(value) ? sum + value : sum;
|
||||
}, 0));
|
||||
const summaryCards = computed(() => [
|
||||
{ label: t('maintenance.record.fields.deviceCode'), value: device.value?.deviceCode || payload.value?.keyword || '-' },
|
||||
{ label: t('maintenance.chat.latestRepair'), value: latestRepairDate.value },
|
||||
{ label: t('maintenance.chat.totalCount'), value: String(records.value.length) },
|
||||
{ label: t('maintenance.chat.totalCost'), value: totalCost.value ? String(totalCost.value) : '-' },
|
||||
]);
|
||||
|
||||
const recordDetailRows = (record: MaintenanceRecord): DisplayCell[] => [
|
||||
{ label: t('maintenance.record.fields.deviceCode'), value: record.deviceCode },
|
||||
{ label: t('maintenance.ledger.fields.deviceName'), value: record.deviceName },
|
||||
{ label: t('maintenance.record.fields.reportDate'), value: record.reportDate },
|
||||
{ label: t('maintenance.record.fields.repairCategory'), value: record.repairCategory },
|
||||
{ label: t('maintenance.record.fields.repairStatus'), value: recordStatusLabel(record.repairStatus) },
|
||||
{ label: t('maintenance.record.fields.faultDescription'), value: record.faultDescription },
|
||||
{ label: t('maintenance.record.fields.repairDescription'), value: record.repairDescription },
|
||||
{ label: t('maintenance.record.fields.reporter'), value: record.reporter },
|
||||
{ label: t('maintenance.record.fields.repairDate'), value: record.repairDate },
|
||||
{ label: t('maintenance.record.fields.repairUnit'), value: record.repairUnit },
|
||||
{ label: t('maintenance.record.fields.repairer'), value: record.repairer },
|
||||
{ label: t('maintenance.record.fields.approver'), value: record.approver },
|
||||
{ label: t('maintenance.record.fields.repairCost'), value: record.repairCost },
|
||||
{ label: t('maintenance.record.fields.repairHours'), value: record.repairHours },
|
||||
{ label: t('maintenance.record.fields.sourceOrderNo'), value: record.sourceOrderNo },
|
||||
{ label: t('maintenance.ledger.fields.devicePosition'), value: record.installLocation },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="hasResult" 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">
|
||||
{{ device ? t('maintenance.chat.deviceLedgerInfo') : t('maintenance.chat.recordInfo') }}
|
||||
<section
|
||||
v-if="hasResult"
|
||||
class="mt-3 w-full max-w-[760px] overflow-hidden rounded-lg border border-slate-300 bg-white text-sm text-slate-800 shadow-sm"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-3 border-b border-slate-200 bg-slate-50 px-3 py-2.5">
|
||||
<h3 class="font-semibold text-slate-900">
|
||||
{{ queryMode === 'records' ? t('maintenance.chat.recordQueryResult') : t('maintenance.chat.deviceLedgerInfo') }}
|
||||
</h3>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-0.5 text-xs font-semibold"
|
||||
class="shrink-0 rounded-full px-2.5 py-0.5 text-xs font-semibold"
|
||||
:class="ledgerMatched ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'"
|
||||
>
|
||||
{{ ledgerMatched ? t('maintenance.chat.matched') : t('maintenance.chat.recordMatched') }}
|
||||
{{ queryMode === 'records' ? t('maintenance.chat.returnedRecords', { count: records.length }) : t('maintenance.chat.matched') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="device" 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 }) }}
|
||||
<template v-if="queryMode === 'device'">
|
||||
<div v-if="device" class="overflow-x-auto p-3">
|
||||
<table class="w-full min-w-[680px] border-collapse text-sm">
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in deviceRows" :key="rowIndex">
|
||||
<template v-if="row.length === 1">
|
||||
<th class="w-[16%] border border-slate-200 bg-slate-100 px-3 py-2 text-left font-semibold text-slate-700">
|
||||
{{ firstCell(row).label }}
|
||||
</th>
|
||||
<td colspan="3" class="border border-slate-200 px-3 py-2 text-slate-900">
|
||||
{{ displayValue(firstCell(row).value) }}
|
||||
</td>
|
||||
</template>
|
||||
<template v-else>
|
||||
<template v-for="cell in row" :key="cell.label">
|
||||
<th class="w-[16%] border border-slate-200 bg-slate-100 px-3 py-2 text-left font-semibold text-slate-700">
|
||||
{{ cell.label }}
|
||||
</th>
|
||||
<td class="w-[34%] border border-slate-200 px-3 py-2 text-slate-900">
|
||||
{{ displayValue(cell.value) }}
|
||||
</td>
|
||||
</template>
|
||||
</template>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</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>
|
||||
<div v-if="canManageMaintenance" class="flex flex-wrap gap-2 px-3 pb-3">
|
||||
<button
|
||||
v-if="device"
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white transition-colors hover:bg-brand-700"
|
||||
@click="emit('view-record-history', device)"
|
||||
>
|
||||
{{ t('maintenance.chat.viewRepairHistory') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="device"
|
||||
type="button"
|
||||
class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 transition-colors hover:bg-slate-50"
|
||||
@click="emit('create-record', device)"
|
||||
>
|
||||
{{ t('maintenance.chat.addRepairRecord') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-else class="px-3 pb-3 text-xs text-slate-500">
|
||||
{{ t('maintenance.chat.adminActionsHidden') }}
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="grid gap-2 p-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div v-for="card in summaryCards" :key="card.label" class="rounded-lg border border-dashed border-slate-300 bg-white px-3 py-2">
|
||||
<div class="text-xs text-slate-500">{{ card.label }}</div>
|
||||
<div class="mt-1 text-lg font-bold text-slate-900">{{ card.value }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="px-3 pb-3">
|
||||
<div class="overflow-hidden border border-slate-200">
|
||||
<table class="w-full table-fixed border-collapse text-left text-xs">
|
||||
<thead class="bg-slate-100 text-slate-700">
|
||||
<tr>
|
||||
<th class="w-[13%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.record.fields.reportDate') }}</th>
|
||||
<th class="w-[29%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.record.fields.faultDescription') }}</th>
|
||||
<th class="w-[29%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.record.fields.repairDescription') }}</th>
|
||||
<th class="w-[11%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.record.fields.repairStatus') }}</th>
|
||||
<th class="w-[18%] border border-slate-200 px-2 py-2 font-semibold">{{ t('maintenance.chat.operation') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="record in records" :key="record.id" class="bg-white">
|
||||
<td class="whitespace-nowrap border border-slate-200 px-2 py-2">{{ displayValue(record.reportDate) }}</td>
|
||||
<td class="border border-slate-200 px-2 py-2 align-top" :title="displayValue(record.faultDescription)">
|
||||
<span class="line-clamp-2 break-words leading-relaxed">{{ displayValue(record.faultDescription) }}</span>
|
||||
</td>
|
||||
<td class="border border-slate-200 px-2 py-2 align-top" :title="displayValue(record.repairDescription)">
|
||||
<span class="line-clamp-2 break-words leading-relaxed">{{ displayValue(record.repairDescription) }}</span>
|
||||
</td>
|
||||
<td class="border border-slate-200 px-2 py-2">
|
||||
<span
|
||||
class="inline-flex whitespace-nowrap rounded-full border px-2 py-0.5 text-xs font-semibold"
|
||||
:class="repairStatusBadgeClass(record.repairStatus)"
|
||||
>
|
||||
{{ recordStatusLabel(record.repairStatus) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="border border-slate-200 px-2 py-2">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-md border border-brand-200 bg-brand-50 px-2 py-1 text-xs font-semibold leading-none text-brand-700 transition-colors hover:bg-brand-100"
|
||||
@click="selectedRecord = record"
|
||||
>
|
||||
{{ t('maintenance.chat.viewRecordDetail') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canManageMaintenance"
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-md border border-brand-200 bg-brand-50 px-2 py-1 text-xs font-semibold leading-none text-brand-700 transition-colors hover:bg-brand-100"
|
||||
@click="emit('edit-record', record)"
|
||||
>
|
||||
{{ t('maintenance.record.actions.edit') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="selectedRecord"
|
||||
class="fixed inset-y-0 right-0 z-50 flex flex-col border-l border-slate-200 bg-white shadow-2xl"
|
||||
:style="recordDetailPanelStyle"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3 border-b border-slate-200 px-5 py-4">
|
||||
<div>
|
||||
<h3 class="text-base font-semibold text-slate-900">{{ t('maintenance.chat.recordDetailTitle') }}</h3>
|
||||
<p class="mt-1 text-xs text-slate-500">{{ t('maintenance.chat.recordDetailHint') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-lg border border-slate-200 text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-700"
|
||||
@click="selectedRecord = null"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto px-4 py-4">
|
||||
<div class="mb-4 rounded-lg border border-dashed border-brand-300 bg-brand-50 px-3 py-2 text-xs text-brand-700">
|
||||
{{ t('maintenance.chat.recordDetailPermissionHint') }}
|
||||
</div>
|
||||
<dl class="overflow-hidden border border-slate-200 text-sm">
|
||||
<div
|
||||
v-for="detail in recordDetailRows(selectedRecord)"
|
||||
:key="detail.label"
|
||||
class="grid grid-cols-[118px_minmax(0,1fr)] border-b border-slate-200 last:border-b-0"
|
||||
>
|
||||
<dt class="bg-slate-100 px-3 py-2 font-semibold text-slate-700">{{ detail.label }}</dt>
|
||||
<dd class="min-w-0 break-words px-3 py-2 text-slate-900">{{ displayValue(detail.value) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="canManageMaintenance" class="flex flex-wrap gap-2 px-3 pb-3">
|
||||
<button
|
||||
v-if="device"
|
||||
type="button"
|
||||
class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 transition-colors hover:bg-slate-50"
|
||||
@click="emit('create-record', device)"
|
||||
>
|
||||
{{ t('maintenance.chat.addRepairRecord') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-else class="px-3 pb-3 text-xs text-slate-500">
|
||||
{{ t('maintenance.chat.adminActionsHidden') }}
|
||||
</p>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
@@ -19,6 +19,8 @@ export interface ListMaintenanceRecordsParams {
|
||||
keyword?: string;
|
||||
deviceCode?: string;
|
||||
status?: string;
|
||||
reportDateFrom?: string;
|
||||
reportDateTo?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
@@ -28,13 +30,19 @@ const jsonHeaders = () => ({
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
|
||||
export const listMaintenanceRecords = (params: ListMaintenanceRecordsParams = {}) => {
|
||||
const sp = new URLSearchParams();
|
||||
const appendListQueryParams = (sp: URLSearchParams, params: ListMaintenanceRecordsParams = {}) => {
|
||||
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.reportDateFrom) sp.set('reportDateFrom', params.reportDateFrom);
|
||||
if (params.reportDateTo) sp.set('reportDateTo', params.reportDateTo);
|
||||
if (params.page) sp.set('page', String(params.page));
|
||||
if (params.pageSize) sp.set('page_size', String(params.pageSize));
|
||||
};
|
||||
|
||||
export const listMaintenanceRecords = (params: ListMaintenanceRecordsParams = {}) => {
|
||||
const sp = new URLSearchParams();
|
||||
appendListQueryParams(sp, params);
|
||||
const qs = sp.toString();
|
||||
return requestJson<MaintenanceRecordListResult>(`${API_BASE}${qs ? `?${qs}` : ''}`, {
|
||||
headers: getAuthHeaders(),
|
||||
@@ -72,9 +80,7 @@ export const deleteMaintenanceRecord = (id: number) => {
|
||||
|
||||
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);
|
||||
appendListQueryParams(sp, params);
|
||||
const qs = sp.toString();
|
||||
const response = await fetch(`${API_BASE}/export${qs ? `?${qs}` : ''}`, {
|
||||
headers: getAuthHeaders(),
|
||||
@@ -106,12 +112,25 @@ export const downloadMaintenanceRecordImportTemplate = async (): Promise<Blob> =
|
||||
return response.blob();
|
||||
};
|
||||
|
||||
export const importMaintenanceRecords = (file: File) => {
|
||||
export const importMaintenanceRecords = async (file: File) => {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return requestJson<MaintenanceRecordImportResult>(`${API_BASE}/import`, {
|
||||
const response = await fetch(`${API_BASE}/import`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: form,
|
||||
});
|
||||
const data = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const message = data?.error?.message || data?.message || `HTTP ${response.status}`;
|
||||
const code = data?.error?.code || data?.code || 'SYSTEM.HTTP_ERROR';
|
||||
throw new BusinessError({
|
||||
message,
|
||||
code,
|
||||
details: data?.error?.details || data?.details || {},
|
||||
requestId: data?.request_id,
|
||||
status: response.status,
|
||||
});
|
||||
}
|
||||
return (data?.success === true ? data.data : data) as MaintenanceRecordImportResult;
|
||||
};
|
||||
@@ -3,7 +3,7 @@
|
||||
* features/maintenance/components/LedgerConfigPanel.vue
|
||||
* 用途:设备维保助手右侧固定面板中的“台账配置”页面,包含设备列表与设备配置两个 Tab。
|
||||
* 依赖:maintenanceLedger.api、PaginationBar、useMessage。
|
||||
* 逻辑:列表 Tab 负责查询/导入/选择设备;配置 Tab 负责新增或编辑设备台账,保存后刷新列表。
|
||||
* 逻辑:列表 Tab 负责查询/导入/选择设备;配置 Tab 负责新增或编辑设备台账,保存后刷新列表;启用日期与维护周期仅保留后端字段,不在 UI 展示。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -83,8 +83,33 @@ const formatStatus = (value: string): string => {
|
||||
return item?.label ? t(item.label) : value || '-';
|
||||
};
|
||||
|
||||
/**
|
||||
* 根据设备状态返回列表标签颜色,帮助管理员快速区分设备可用性。
|
||||
* @param value - 设备状态枚举值。
|
||||
* @returns Tailwind class 字符串。
|
||||
*/
|
||||
const statusBadgeClass = (value: string): string => {
|
||||
if (value === 'in_use') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
if (value === 'disabled') return 'border-slate-200 bg-slate-100 text-slate-600';
|
||||
if (value === 'scrapped') return 'border-rose-200 bg-rose-50 text-rose-700';
|
||||
if (value === 'sold') return 'border-sky-200 bg-sky-50 text-sky-700';
|
||||
return 'border-slate-200 bg-slate-50 text-slate-600';
|
||||
};
|
||||
|
||||
/**
|
||||
* 将金额输入统一转为可提交字符串,兼容 type=number 绑定产生的 number 值。
|
||||
* @param value - 表单中的原值/残值。
|
||||
* @returns 裁剪后的字符串;空值返回 undefined。
|
||||
*/
|
||||
const normalizeAmountField = (value: string | number | null | undefined): string | undefined => {
|
||||
if (value === null || value === undefined || value === '') return undefined;
|
||||
const text = String(value).trim();
|
||||
return text || undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从表单状态生成 API payload,集中裁剪字符串。
|
||||
* 核心逻辑:startDate / maintenanceCycle 虽不在 UI 展示,编辑时仍随 payload 回传,避免保存其他字段时清空库内已有值。
|
||||
* @returns 设备保存入参。
|
||||
*/
|
||||
const buildPayload = (): MaintenanceDevicePayload => ({
|
||||
@@ -100,8 +125,8 @@ const buildPayload = (): MaintenanceDevicePayload => ({
|
||||
startDate: form.startDate || undefined,
|
||||
responsibleUser: form.responsibleUser?.trim(),
|
||||
maintenanceCycle: form.maintenanceCycle?.trim(),
|
||||
originalValue: form.originalValue?.trim(),
|
||||
residualValue: form.residualValue?.trim(),
|
||||
originalValue: normalizeAmountField(form.originalValue),
|
||||
residualValue: normalizeAmountField(form.residualValue),
|
||||
accountSet: form.accountSet?.trim(),
|
||||
remark: form.remark?.trim(),
|
||||
});
|
||||
@@ -350,7 +375,7 @@ onMounted(loadDevices);
|
||||
<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>
|
||||
<th class="px-3 py-2 text-right">{{ t('maintenance.ledger.table.operation') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -365,11 +390,24 @@ onMounted(loadDevices);
|
||||
<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>
|
||||
<span
|
||||
class="inline-flex min-w-14 items-center justify-center rounded-full border px-2.5 py-1 text-xs font-semibold"
|
||||
:class="statusBadgeClass(device.deviceStatus)"
|
||||
>
|
||||
{{ formatStatus(device.deviceStatus) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class="admin-report-page-btn admin-report-page-btn--edit"
|
||||
@click="startEdit(device)"
|
||||
>
|
||||
{{ t('maintenance.ledger.actions.edit') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -437,14 +475,6 @@ onMounted(loadDevices);
|
||||
{{ 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" />
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/maintenance/components/MaintenanceDeviceSnapshotCard.vue
|
||||
* 用途:维修记录表单中展示已匹配的设备台账快照卡片。
|
||||
* 依赖:device-status-display.utils、maintenance ledger 类型、vue-i18n。
|
||||
* 逻辑:MaintenanceRecordManagerPanel / MaintenanceRecordPanel 在设备编号下方引用;按加载、匹配、未找到、空态四种状态渲染。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BadgeCheck, BriefcaseBusiness, Building2, MapPin, UserRound } from 'lucide-vue-next';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import { deviceStatusBadgeClass, deviceStatusLabelKey } from '@/features/maintenance/utils/device-status-display.utils';
|
||||
|
||||
const props = defineProps<{
|
||||
device: MaintenanceDevice | null;
|
||||
loading?: boolean;
|
||||
deviceCode?: string;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const trimmedCode = computed(() => props.deviceCode?.trim() || '');
|
||||
|
||||
/**
|
||||
* 根据加载态、匹配结果与是否已输入编号,计算快照卡片展示状态。
|
||||
* @returns loading | matched | notFound | empty
|
||||
*/
|
||||
const displayState = computed(() => {
|
||||
if (props.loading) return 'loading';
|
||||
if (props.device) return 'matched';
|
||||
if (trimmedCode.value) return 'notFound';
|
||||
return 'empty';
|
||||
});
|
||||
|
||||
/**
|
||||
* 将设备状态枚举转为当前语言的展示文案。
|
||||
* @param value - 设备状态枚举。
|
||||
* @returns 本地化状态文案。
|
||||
*/
|
||||
const formatDeviceStatus = (value: string): string => {
|
||||
const key = deviceStatusLabelKey(value);
|
||||
return key ? t(key) : value || '-';
|
||||
};
|
||||
|
||||
const infoCells = computed(() => {
|
||||
if (!props.device) return [];
|
||||
return [
|
||||
{ label: t('maintenance.ledger.fields.modelSpec'), value: props.device.modelSpec, icon: BriefcaseBusiness },
|
||||
{ label: t('maintenance.record.deviceSnapshot.position'), value: props.device.installLocation, icon: MapPin },
|
||||
{ label: t('maintenance.record.deviceSnapshot.department'), value: props.device.department, icon: Building2 },
|
||||
{ label: t('maintenance.record.deviceSnapshot.responsibleUser'), value: props.device.responsibleUser, icon: UserRound },
|
||||
];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="displayState === 'loading'" class="rounded-xl border border-sky-100 bg-gradient-to-r from-sky-50/90 to-white p-4 shadow-sm">
|
||||
<div class="animate-pulse space-y-3">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="h-4 w-28 rounded bg-sky-100" />
|
||||
<div class="h-6 w-14 rounded-full bg-sky-100" />
|
||||
</div>
|
||||
<div class="h-6 w-40 rounded bg-sky-100" />
|
||||
<div class="h-4 w-28 rounded bg-sky-50" />
|
||||
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div v-for="index in 4" :key="index" class="h-14 rounded-lg bg-white/80 ring-1 ring-sky-100" />
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-3 text-xs text-secondary">{{ t('maintenance.record.deviceSnapshot.loading') }}</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="displayState === 'matched' && device"
|
||||
class="rounded-xl border border-sky-100 border-l-4 border-l-brand-500 bg-gradient-to-r from-sky-50/90 to-white p-4 shadow-sm"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-xs font-semibold text-sky-800">{{ t('maintenance.record.deviceSnapshot.title') }}</span>
|
||||
<span class="inline-flex items-center gap-1 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700">
|
||||
<BadgeCheck class="h-3.5 w-3.5" />
|
||||
{{ t('maintenance.record.deviceSnapshot.matched') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-wrap items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="text-lg font-semibold text-primary">{{ device.deviceName || '-' }}</div>
|
||||
<div class="mt-1 font-mono text-sm text-secondary">{{ device.deviceCode }}</div>
|
||||
</div>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
|
||||
:class="deviceStatusBadgeClass(device.deviceStatus)"
|
||||
>
|
||||
{{ formatDeviceStatus(device.deviceStatus) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div
|
||||
v-for="cell in infoCells"
|
||||
:key="cell.label"
|
||||
class="rounded-lg bg-white/85 px-3 py-2 ring-1 ring-sky-100"
|
||||
>
|
||||
<div class="flex items-start gap-2">
|
||||
<component :is="cell.icon" class="mt-0.5 h-4 w-4 shrink-0 text-brand-600" />
|
||||
<div class="min-w-0">
|
||||
<div class="text-[11px] text-secondary">{{ cell.label }}</div>
|
||||
<div class="mt-0.5 truncate text-xs font-medium text-primary" :title="cell.value || '-'">
|
||||
{{ cell.value || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="displayState === 'notFound'"
|
||||
class="rounded-xl border border-dashed border-amber-300 bg-amber-50/60 px-4 py-3 text-sm text-amber-900"
|
||||
>
|
||||
{{ t('maintenance.record.deviceSnapshot.notFound') }}
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="rounded-xl border border-dashed border-slate-300 bg-slate-50 px-4 py-3 text-sm text-secondary"
|
||||
>
|
||||
{{ t('maintenance.record.deviceSnapshot.empty') }}
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,15 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/maintenance/components/MaintenanceRecordManagerPanel.vue
|
||||
* 用途:设备维保助手右侧固定面板中的维修记录管理页,覆盖查询、新增、编辑和删除。
|
||||
* 依赖:maintenanceRecord.api、maintenanceLedger.api、PaginationBar、useMessage。
|
||||
* 依赖:maintenanceRecord.api、maintenanceLedger.api、MaintenanceDeviceSnapshotCard、repair-status-display.utils、PaginationBar、useMessage。
|
||||
* 逻辑:列表 Tab 按设备编号/名称和维修状态筛选;配置 Tab 复用同一表单新增或修改记录。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import MaintenanceDeviceSnapshotCard from '@/features/maintenance/components/MaintenanceDeviceSnapshotCard.vue';
|
||||
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
|
||||
import {
|
||||
createMaintenanceRecord,
|
||||
@@ -24,12 +25,29 @@ import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.type
|
||||
import type {
|
||||
MaintenanceRecord,
|
||||
MaintenanceRecordImportResult,
|
||||
MaintenanceRecordListStatus,
|
||||
MaintenanceRecordPayload,
|
||||
MaintenanceRepairStatus,
|
||||
} from '@/features/maintenance/types/record.types';
|
||||
import { repairStatusBadgeClass } from '@/features/maintenance/utils/repair-status-display.utils';
|
||||
import {
|
||||
DEFAULT_MAINTENANCE_RECORD_TIME_RANGE,
|
||||
resolveMaintenanceRecordReportDateRange,
|
||||
type MaintenanceRecordTimeRange,
|
||||
} from '@/features/maintenance/utils/record-list-filter.utils';
|
||||
|
||||
type TabName = 'list' | 'form';
|
||||
|
||||
interface MaintenanceRecordPanelCommand {
|
||||
mode: 'list' | 'create';
|
||||
device?: MaintenanceDevice | null;
|
||||
nonce?: number;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
editRecord?: MaintenanceRecord | null;
|
||||
command?: MaintenanceRecordPanelCommand | null;
|
||||
}>();
|
||||
|
||||
const msg = useMessage();
|
||||
const { t } = useI18n();
|
||||
const activeTab = ref<TabName>('list');
|
||||
@@ -46,7 +64,8 @@ const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(10);
|
||||
const keyword = ref('');
|
||||
const status = ref('');
|
||||
const status = ref<MaintenanceRecordListStatus>('active');
|
||||
const timeRange = ref<MaintenanceRecordTimeRange>(DEFAULT_MAINTENANCE_RECORD_TIME_RANGE);
|
||||
const editingId = ref<number | null>(null);
|
||||
const importResult = ref<MaintenanceRecordImportResult | null>(null);
|
||||
const deleteDialogOpen = ref(false);
|
||||
@@ -71,14 +90,25 @@ const form = reactive<MaintenanceRecordPayload>({
|
||||
sourceOrderNo: '',
|
||||
});
|
||||
|
||||
const statusOptions: Array<{ value: MaintenanceRepairStatus | ''; label: string }> = [
|
||||
const statusOptions: Array<{ value: MaintenanceRecordListStatus; label: string }> = [
|
||||
{ value: '', label: 'maintenance.record.status.all' },
|
||||
{ value: 'active', label: 'maintenance.record.status.active' },
|
||||
{ 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 timeRangeOptions: Array<{ value: MaintenanceRecordTimeRange; label: string }> = [
|
||||
{ value: '3m', label: 'maintenance.record.filters.timeRange3m' },
|
||||
{ value: '1y', label: 'maintenance.record.filters.timeRange1y' },
|
||||
{ value: 'all', label: 'maintenance.record.filters.timeRangeAll' },
|
||||
];
|
||||
|
||||
const isDefaultScopedFilter = computed(
|
||||
() => status.value === 'active' && timeRange.value === '1y' && !keyword.value.trim(),
|
||||
);
|
||||
|
||||
const formTitle = computed(() => t(editingId.value ? 'maintenance.record.formTitle.edit' : 'maintenance.record.formTitle.create'));
|
||||
const deleteConfirmMessage = computed(() =>
|
||||
pendingDeleteRecord.value
|
||||
@@ -118,17 +148,24 @@ const buildPayload = (): MaintenanceRecordPayload => ({
|
||||
});
|
||||
|
||||
/**
|
||||
* 查询维修记录列表,仅按设备编号/设备名称和状态筛选。
|
||||
* 组装当前列表筛选参数,供查询与导出共用。
|
||||
* @returns 维修记录列表 API 入参。
|
||||
*/
|
||||
const buildListQueryParams = () => ({
|
||||
keyword: keyword.value.trim(),
|
||||
status: status.value,
|
||||
...resolveMaintenanceRecordReportDateRange(timeRange.value),
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
});
|
||||
|
||||
/**
|
||||
* 查询维修记录列表,默认聚焦近一年内未完成记录。
|
||||
*/
|
||||
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,
|
||||
});
|
||||
const result = await listMaintenanceRecords(buildListQueryParams());
|
||||
records.value = result.items;
|
||||
total.value = result.total;
|
||||
} catch (error: any) {
|
||||
@@ -147,6 +184,7 @@ const exportRecords = async (): Promise<void> => {
|
||||
const blob = await exportMaintenanceRecords({
|
||||
keyword: keyword.value.trim(),
|
||||
status: status.value,
|
||||
...resolveMaintenanceRecordReportDateRange(timeRange.value),
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
@@ -237,7 +275,7 @@ const loadDeviceSnapshot = async (): Promise<void> => {
|
||||
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;
|
||||
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.deviceLoadFailed'));
|
||||
} finally {
|
||||
@@ -245,6 +283,31 @@ const loadDeviceSnapshot = async (): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存维修记录前精确校验设备编号,避免把记录挂到不存在的设备上。
|
||||
* @returns 台账中是否存在当前设备编号。
|
||||
*/
|
||||
const ensureDeviceExists = async (): Promise<boolean> => {
|
||||
const code = form.deviceCode.trim();
|
||||
if (!code) return false;
|
||||
if (matchedDevice.value?.deviceCode === code) return true;
|
||||
deviceLoading.value = true;
|
||||
try {
|
||||
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
|
||||
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
|
||||
if (!matchedDevice.value) {
|
||||
msg.warning(t('maintenance.record.messages.deviceNotFound'));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.deviceLoadFailed'));
|
||||
return false;
|
||||
} finally {
|
||||
deviceLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 重置表单并进入新增模式。
|
||||
*/
|
||||
@@ -270,6 +333,49 @@ const startCreate = (): void => {
|
||||
activeTab.value = 'form';
|
||||
};
|
||||
|
||||
/**
|
||||
* 从会话结果里的设备卡片进入新增时,预填设备编号并复用设备快照,减少管理员重复录入。
|
||||
* @param device - 当前会话结果命中的设备。
|
||||
*/
|
||||
const startCreateForDevice = (device: MaintenanceDevice): void => {
|
||||
startCreate();
|
||||
form.deviceCode = device.deviceCode || '';
|
||||
matchedDevice.value = device;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从会话结果里的设备卡片进入历史时,按设备编号筛选维修记录列表。
|
||||
* @param device - 当前会话结果命中的设备。
|
||||
*/
|
||||
const showHistoryForDevice = async (device: MaintenanceDevice): Promise<void> => {
|
||||
keyword.value = device.deviceCode || '';
|
||||
status.value = '';
|
||||
timeRange.value = 'all';
|
||||
page.value = 1;
|
||||
activeTab.value = 'list';
|
||||
await loadRecords();
|
||||
};
|
||||
|
||||
/**
|
||||
* 切换报修日期快捷范围并刷新列表。
|
||||
* @param range - 近 3 个月 / 近 1 年 / 全部时间。
|
||||
*/
|
||||
const applyTimeRange = async (range: MaintenanceRecordTimeRange): Promise<void> => {
|
||||
timeRange.value = range;
|
||||
page.value = 1;
|
||||
await loadRecords();
|
||||
};
|
||||
|
||||
/**
|
||||
* 一键查看全部历史记录,取消默认的未完成与时间限制。
|
||||
*/
|
||||
const viewAllHistory = async (): Promise<void> => {
|
||||
status.value = '';
|
||||
timeRange.value = 'all';
|
||||
page.value = 1;
|
||||
await loadRecords();
|
||||
};
|
||||
|
||||
/**
|
||||
* 将选中的维修记录带入表单并进入编辑模式。
|
||||
* @param record - 列表中选中的维修记录。
|
||||
@@ -314,6 +420,9 @@ const saveRecord = async (): Promise<void> => {
|
||||
msg.warning(t('maintenance.record.messages.required'));
|
||||
return;
|
||||
}
|
||||
if (!await ensureDeviceExists()) {
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
if (editingId.value) {
|
||||
@@ -366,6 +475,27 @@ const cancelDeleteDialog = (): void => {
|
||||
};
|
||||
|
||||
onMounted(loadRecords);
|
||||
|
||||
watch(
|
||||
() => props.editRecord,
|
||||
(record) => {
|
||||
if (record) startEdit(record);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.command,
|
||||
async (command) => {
|
||||
if (!command?.device) return;
|
||||
if (command.mode === 'create') {
|
||||
startCreateForDevice(command.device);
|
||||
return;
|
||||
}
|
||||
await showHistoryForDevice(command.device);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -396,6 +526,10 @@ onMounted(loadRecords);
|
||||
</div>
|
||||
|
||||
<div v-if="activeTab === 'list'" class="flex min-h-0 flex-1 flex-col gap-4">
|
||||
<div class="rounded-xl border border-brand-100 bg-brand-50/70 px-3 py-2 text-sm text-brand-900">
|
||||
{{ t('maintenance.record.filters.defaultHint') }}
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<input
|
||||
v-model="keyword"
|
||||
@@ -410,6 +544,20 @@ onMounted(loadRecords);
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-sm text-secondary">{{ t('maintenance.record.filters.timeRangeLabel') }}</span>
|
||||
<button
|
||||
v-for="item in timeRangeOptions"
|
||||
:key="item.value"
|
||||
type="button"
|
||||
class="admin-report-page-btn"
|
||||
:class="{ 'admin-report-page-btn--active': timeRange === item.value }"
|
||||
@click="applyTimeRange(item.value)"
|
||||
>
|
||||
{{ t(item.label) }}
|
||||
</button>
|
||||
</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') }}
|
||||
@@ -439,34 +587,75 @@ onMounted(loadRecords);
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 overflow-auto rounded-xl border border-default bg-surface">
|
||||
<table class="w-full table-fixed text-left text-sm">
|
||||
<thead class="bg-muted/50 text-secondary">
|
||||
<table class="w-full min-w-[1040px] table-fixed border-separate border-spacing-0 text-left text-sm">
|
||||
<colgroup>
|
||||
<col style="width: 140px" />
|
||||
<col style="width: 150px" />
|
||||
<col />
|
||||
<col style="width: 120px" />
|
||||
<col style="width: 120px" />
|
||||
<col style="width: 110px" />
|
||||
<col style="width: 110px" />
|
||||
<col style="width: 150px" />
|
||||
</colgroup>
|
||||
<thead class="bg-surface-soft text-secondary">
|
||||
<tr>
|
||||
<th class="w-[24%] px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
|
||||
<th class="w-[22%] px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
|
||||
<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.faultDescription') }}</th>
|
||||
<th class="w-[14%] px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
|
||||
<th class="w-[18%] px-3 py-2 text-right">{{ t('maintenance.record.table.operation') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairDate') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairer') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairCost') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
|
||||
<th class="admin-table-sticky-right-head px-3 py-2 text-center">
|
||||
{{ t('maintenance.record.table.operation') }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="5" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
|
||||
<td colspan="8" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
|
||||
</tr>
|
||||
<tr v-else-if="!records.length">
|
||||
<td colspan="5" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.empty') }}</td>
|
||||
<td colspan="8" class="px-3 py-8 text-center text-secondary">
|
||||
<div>{{ t(isDefaultScopedFilter ? 'maintenance.record.table.emptyActive' : 'maintenance.record.table.empty') }}</div>
|
||||
<button
|
||||
v-if="isDefaultScopedFilter"
|
||||
type="button"
|
||||
class="admin-report-page-btn admin-report-page-btn--active mt-3"
|
||||
@click="viewAllHistory"
|
||||
>
|
||||
{{ t('maintenance.record.actions.viewAllHistory') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="record in records" v-else :key="record.id" class="border-t border-default">
|
||||
<td class="truncate px-3 py-2 font-semibold" :title="record.deviceCode">{{ record.deviceCode }}</td>
|
||||
<td class="truncate px-3 py-2" :title="record.deviceName || '-'">{{ record.deviceName || '-' }}</td>
|
||||
<td class="truncate px-3 py-2" :title="record.faultDescription">{{ record.faultDescription }}</td>
|
||||
<td class="px-3 py-2">{{ formatStatus(record.repairStatus) }}</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="flex justify-end gap-2">
|
||||
<button type="button" class="admin-report-page-btn" @click="startEdit(record)">{{ t('maintenance.record.actions.edit') }}</button>
|
||||
<tr v-for="record in records" v-else :key="record.id">
|
||||
<td class="border-t border-default px-3 py-2 font-semibold" :title="record.deviceCode">{{ record.deviceCode }}</td>
|
||||
<td class="truncate border-t border-default px-3 py-2" :title="record.deviceName || '-'">{{ record.deviceName || '-' }}</td>
|
||||
<td class="truncate border-t border-default px-3 py-2" :title="record.faultDescription">{{ record.faultDescription }}</td>
|
||||
<td class="whitespace-nowrap border-t border-default px-3 py-2">{{ record.repairDate || '-' }}</td>
|
||||
<td class="truncate border-t border-default px-3 py-2" :title="record.repairer || '-'">{{ record.repairer || '-' }}</td>
|
||||
<td class="truncate border-t border-default px-3 py-2" :title="record.repairCost || '-'">{{ record.repairCost || '-' }}</td>
|
||||
<td class="border-t border-default px-3 py-2">
|
||||
<span
|
||||
class="inline-flex min-w-14 items-center justify-center rounded-full border px-2.5 py-1 text-xs font-semibold"
|
||||
:class="repairStatusBadgeClass(record.repairStatus)"
|
||||
>
|
||||
{{ formatStatus(record.repairStatus) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="admin-table-sticky-right-cell border-t border-default px-3 py-2">
|
||||
<div class="relative z-[1] flex justify-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="admin-report-page-btn"
|
||||
class="admin-report-page-btn admin-report-page-btn--edit"
|
||||
@click="startEdit(record)"
|
||||
>
|
||||
{{ t('maintenance.record.actions.edit') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="admin-report-page-btn admin-report-page-btn--danger"
|
||||
:disabled="deletingId === record.id"
|
||||
@click="openDeleteDialog(record)"
|
||||
>
|
||||
@@ -509,6 +698,17 @@ onMounted(loadRecords);
|
||||
{{ t('maintenance.record.fields.reportDate') }} *
|
||||
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<MaintenanceDeviceSnapshotCard
|
||||
:device="matchedDevice"
|
||||
:loading="deviceLoading"
|
||||
:device-code="form.deviceCode"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid gap-4 md:grid-cols-2">
|
||||
<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')" />
|
||||
@@ -524,16 +724,6 @@ onMounted(loadRecords);
|
||||
</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') }} *
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
/**
|
||||
* features/maintenance/components/MaintenanceRecordPanel.vue
|
||||
* 用途:设备维保助手右侧固定面板中的“新增维修记录”页面。
|
||||
* 依赖:maintenanceRecord.api、maintenanceLedger.api、useMessage。
|
||||
* 依赖:maintenanceRecord.api、maintenanceLedger.api、MaintenanceDeviceSnapshotCard、useMessage。
|
||||
* 逻辑:管理员通过按钮进入固定面板后填写维修记录;设备编号失焦时查询台账快照,保存后刷新最近记录用于确认。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import MaintenanceDeviceSnapshotCard from '@/features/maintenance/components/MaintenanceDeviceSnapshotCard.vue';
|
||||
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
|
||||
import {
|
||||
createMaintenanceRecord,
|
||||
@@ -100,7 +101,7 @@ const loadDeviceSnapshot = async (): Promise<void> => {
|
||||
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;
|
||||
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || '查询设备台账失败');
|
||||
} finally {
|
||||
@@ -108,6 +109,30 @@ const loadDeviceSnapshot = async (): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存前精确校验设备编号必须存在于台账,避免产生无设备归属的维修记录。
|
||||
*/
|
||||
const ensureDeviceExists = async (): Promise<boolean> => {
|
||||
const code = form.deviceCode.trim();
|
||||
if (!code) return false;
|
||||
if (matchedDevice.value?.deviceCode === code) return true;
|
||||
deviceLoading.value = true;
|
||||
try {
|
||||
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
|
||||
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || null;
|
||||
if (!matchedDevice.value) {
|
||||
msg.warning('设备不存在,不能新增维修记录');
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || '鏌ヨ璁惧鍙拌处澶辫触');
|
||||
return false;
|
||||
} finally {
|
||||
deviceLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 查询最近维修记录,作为保存后的确认列表和轻量筛选入口。
|
||||
*/
|
||||
@@ -160,6 +185,9 @@ const saveRecord = async (): Promise<void> => {
|
||||
msg.warning('设备编号、报修日期和故障描述不能为空');
|
||||
return;
|
||||
}
|
||||
if (!await ensureDeviceExists()) {
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
await createMaintenanceRecord(payload);
|
||||
@@ -199,6 +227,17 @@ onMounted(loadRecentRecords);
|
||||
报修日期 *
|
||||
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<MaintenanceDeviceSnapshotCard
|
||||
:device="matchedDevice"
|
||||
:loading="deviceLoading"
|
||||
:device-code="form.deviceCode"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid gap-4 md:grid-cols-2">
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
维修类别
|
||||
<input v-model="form.repairCategory" class="admin-table-filter-input" placeholder="日常维修 / 保养 / 点检" />
|
||||
@@ -214,16 +253,6 @@ onMounted(loadRecentRecords);
|
||||
</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">
|
||||
故障描述 *
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
|
||||
export type MaintenanceRepairStatus = 'pending' | 'processing' | 'done' | 'cancelled';
|
||||
|
||||
/** 列表筛选状态:active 表示待维修 + 维修中。 */
|
||||
export type MaintenanceRecordListStatus = MaintenanceRepairStatus | 'active' | '';
|
||||
|
||||
export interface MaintenanceRecord {
|
||||
id: number;
|
||||
deviceId?: number | null;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* features/maintenance/utils/device-status-display.utils.ts
|
||||
* 用途:设备台账状态在列表、快照卡片中的标签配色映射。
|
||||
* 依赖:MaintenanceDeviceStatus 类型。
|
||||
* 逻辑:LedgerConfigPanel、MaintenanceDeviceSnapshotCard 等组件统一引用,保证设备状态色一致。
|
||||
*/
|
||||
import type { MaintenanceDeviceStatus } from '@/features/maintenance/types/ledger.types';
|
||||
|
||||
/**
|
||||
* 根据设备状态返回 Tailwind 标签配色,帮助用户快速区分在用、停用与报废设备。
|
||||
* @param value - 设备状态枚举值。
|
||||
* @returns Tailwind class 字符串(border / background / text)。
|
||||
*/
|
||||
export function deviceStatusBadgeClass(value: MaintenanceDeviceStatus | string): string {
|
||||
if (value === 'in_use') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
if (value === 'disabled') return 'border-slate-200 bg-slate-100 text-slate-600';
|
||||
if (value === 'scrapped') return 'border-rose-200 bg-rose-50 text-rose-700';
|
||||
if (value === 'sold') return 'border-sky-200 bg-sky-50 text-sky-700';
|
||||
return 'border-slate-200 bg-slate-50 text-slate-600';
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回设备状态对应的 i18n 文案 key,供组件内 t() 翻译。
|
||||
* @param value - 设备状态枚举值。
|
||||
* @returns maintenance.ledger.status.* 的 key 路径。
|
||||
*/
|
||||
export function deviceStatusLabelKey(value: MaintenanceDeviceStatus | string): string {
|
||||
if (value === 'in_use') return 'maintenance.ledger.status.inUse';
|
||||
if (value === 'disabled') return 'maintenance.ledger.status.disabled';
|
||||
if (value === 'scrapped') return 'maintenance.ledger.status.scrapped';
|
||||
if (value === 'sold') return 'maintenance.ledger.status.sold';
|
||||
return '';
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* features/maintenance/utils/maintenance-panel-layout.utils.ts
|
||||
* 用途:设备维保助手右侧管理面板与会话维修记录明细面板的统一宽度约束。
|
||||
* 依赖:无运行时依赖。
|
||||
* 逻辑:ChatViewContent 管理面板与 MaintenanceDeviceResultCard 明细抽屉共用同一组默认值。
|
||||
*/
|
||||
|
||||
export const MAINTENANCE_PANEL_MIN_WIDTH = 520;
|
||||
export const MAINTENANCE_PANEL_DEFAULT_WIDTH = 760;
|
||||
export const MAINTENANCE_PANEL_MAX_WIDTH_RATIO = 0.82;
|
||||
|
||||
/**
|
||||
* 生成维保右侧面板宽度样式,默认与管理面板初始宽度一致。
|
||||
* @param width - 当前面板宽度,默认 760px。
|
||||
* @returns 可直接绑定到 style 的宽度对象。
|
||||
*/
|
||||
export function buildMaintenancePanelWidthStyle(width = MAINTENANCE_PANEL_DEFAULT_WIDTH): Record<string, string> {
|
||||
return {
|
||||
width: `${width}px`,
|
||||
minWidth: `${MAINTENANCE_PANEL_MIN_WIDTH}px`,
|
||||
maxWidth: `${Math.round(MAINTENANCE_PANEL_MAX_WIDTH_RATIO * 100)}vw`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算拖拽调整后的面板宽度,保持与管理面板相同上下限。
|
||||
* @param nextWidth - 拖拽后的目标宽度。
|
||||
* @param viewportWidth - 当前视口宽度。
|
||||
* @returns 合法宽度像素值。
|
||||
*/
|
||||
export function clampMaintenancePanelWidth(nextWidth: number, viewportWidth: number): number {
|
||||
const maxWidth = Math.max(
|
||||
MAINTENANCE_PANEL_MIN_WIDTH,
|
||||
Math.floor(viewportWidth * MAINTENANCE_PANEL_MAX_WIDTH_RATIO),
|
||||
);
|
||||
return Math.min(maxWidth, Math.max(MAINTENANCE_PANEL_MIN_WIDTH, nextWidth));
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* features/maintenance/utils/record-list-filter.utils.ts
|
||||
* 用途:维修记录管理列表的默认筛选与时间范围计算。
|
||||
* 依赖:无运行时依赖。
|
||||
* 逻辑:MaintenanceRecordManagerPanel 进入时默认「未完成 + 近一年」;本工具负责把 UI 选项转为 API 报修日期参数。
|
||||
*/
|
||||
|
||||
export type MaintenanceRecordTimeRange = '3m' | '1y' | 'all';
|
||||
|
||||
export const DEFAULT_MAINTENANCE_RECORD_TIME_RANGE: MaintenanceRecordTimeRange = '1y';
|
||||
|
||||
export interface MaintenanceRecordReportDateRange {
|
||||
reportDateFrom?: string;
|
||||
reportDateTo?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将时间快捷选项转为报修日期闭区间参数。
|
||||
* 核心逻辑:3m/1y 以 referenceDate 为结束日倒推;all 不传日期参数表示不限时间。
|
||||
* @param range - 近 3 个月 / 近 1 年 / 全部时间。
|
||||
* @param referenceDate - 计算基准日期,默认当天。
|
||||
* @returns API 可用的 reportDateFrom/reportDateTo。
|
||||
*/
|
||||
export function resolveMaintenanceRecordReportDateRange(
|
||||
range: MaintenanceRecordTimeRange,
|
||||
referenceDate: Date = new Date(),
|
||||
): MaintenanceRecordReportDateRange {
|
||||
if (range === 'all') {
|
||||
return {};
|
||||
}
|
||||
|
||||
const reportDateTo = referenceDate.toISOString().slice(0, 10);
|
||||
const fromDate = new Date(referenceDate);
|
||||
if (range === '3m') {
|
||||
fromDate.setMonth(fromDate.getMonth() - 3);
|
||||
} else {
|
||||
fromDate.setFullYear(fromDate.getFullYear() - 1);
|
||||
}
|
||||
|
||||
return {
|
||||
reportDateFrom: fromDate.toISOString().slice(0, 10),
|
||||
reportDateTo,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* features/maintenance/utils/repair-status-display.utils.ts
|
||||
* 用途:维修记录状态在列表、卡片中的标签配色映射。
|
||||
* 依赖:MaintenanceRepairStatus 类型。
|
||||
* 逻辑:MaintenanceRecordManagerPanel、MaintenanceDeviceResultCard 等组件统一引用,保证状态色一致。
|
||||
*/
|
||||
import type { MaintenanceRepairStatus } from '@/features/maintenance/types/record.types';
|
||||
|
||||
/**
|
||||
* 根据维修状态返回 Tailwind 标签配色,帮助用户快速区分待办、进行中与已完成。
|
||||
* @param value - 维修状态枚举值。
|
||||
* @returns Tailwind class 字符串(border / background / text)。
|
||||
*/
|
||||
export function repairStatusBadgeClass(value: MaintenanceRepairStatus | string): string {
|
||||
if (value === 'pending') return 'border-amber-200 bg-amber-50 text-amber-700';
|
||||
if (value === 'processing') return 'border-sky-200 bg-sky-50 text-sky-700';
|
||||
if (value === 'done') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
if (value === 'cancelled') return 'border-slate-200 bg-slate-100 text-slate-600';
|
||||
return 'border-slate-200 bg-slate-50 text-slate-600';
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
"ledger": {
|
||||
"notice": "This page manages the equipment ledger.",
|
||||
"tabs": {
|
||||
"list": "Equipment List",
|
||||
"form": "Equipment Config"
|
||||
"list": "Equipment Ledger",
|
||||
"form": "Add/Edit"
|
||||
},
|
||||
"status": {
|
||||
"all": "All Statuses",
|
||||
@@ -79,11 +79,11 @@
|
||||
},
|
||||
"panel": {
|
||||
"recordTitle": "Maintenance Records",
|
||||
"ledgerTitle": "Ledger Config",
|
||||
"ledgerTitle": "Equipment Ledger",
|
||||
"adminOnly": "Admin actions: admins / maintenance admins only",
|
||||
"resizeTitle": "Drag to resize",
|
||||
"ledgerSubtitle": "Equipment List / Equipment Config",
|
||||
"recordSubtitle": "Record List / Record Config",
|
||||
"ledgerSubtitle": "Equipment ledger management",
|
||||
"recordSubtitle": "Maintenance record management",
|
||||
"fullscreen": "Fullscreen",
|
||||
"exitFullscreen": "Exit fullscreen",
|
||||
"close": "Close"
|
||||
@@ -91,11 +91,12 @@
|
||||
"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"
|
||||
"list": "Maintenance Records",
|
||||
"form": "Add/Edit"
|
||||
},
|
||||
"status": {
|
||||
"all": "All Statuses",
|
||||
"active": "Open",
|
||||
"pending": "Pending",
|
||||
"processing": "In Repair",
|
||||
"done": "Completed",
|
||||
@@ -119,11 +120,17 @@
|
||||
"deleting": "Deleting...",
|
||||
"backToList": "Back to List",
|
||||
"cancel": "Cancel",
|
||||
"save": "Save Record",
|
||||
"saving": "Saving..."
|
||||
"save": "Save",
|
||||
"saving": "Saving...",
|
||||
"viewAllHistory": "View All History"
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "Search equipment code or name"
|
||||
"keywordPlaceholder": "Search equipment code or name",
|
||||
"defaultHint": "By default, only open records (pending or in repair) from the last year are shown. Choose All Statuses and All Time to browse full history.",
|
||||
"timeRangeLabel": "Report Date",
|
||||
"timeRange3m": "Last 3 Months",
|
||||
"timeRange1y": "Last Year",
|
||||
"timeRangeAll": "All Time"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "Equipment Code",
|
||||
@@ -134,7 +141,8 @@
|
||||
"repairer": "Repairer",
|
||||
"operation": "Actions",
|
||||
"loading": "Loading...",
|
||||
"empty": "No maintenance records"
|
||||
"empty": "No maintenance records",
|
||||
"emptyActive": "No open records in the last year"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "Equipment Code",
|
||||
@@ -160,11 +168,14 @@
|
||||
},
|
||||
"deviceSnapshot": {
|
||||
"loading": "Querying equipment ledger...",
|
||||
"title": "Ledger Equipment",
|
||||
"matched": "Matched",
|
||||
"notFound": "Equipment not found. Check the code or register it in the ledger first.",
|
||||
"position": "Position",
|
||||
"department": "Department",
|
||||
"responsibleUser": "Responsible Person",
|
||||
"status": "Status",
|
||||
"empty": "Enter an equipment code to match an equipment ledger snapshot automatically."
|
||||
"empty": "Enter an equipment code to match ledger information automatically."
|
||||
},
|
||||
"importResult": "Import result: {total} rows, {created} created, {failed} failed.",
|
||||
"importErrorRow": "Row {row}: {message}",
|
||||
@@ -184,17 +195,32 @@
|
||||
"saveFailed": "Failed to save maintenance record",
|
||||
"deleteConfirm": "Delete the maintenance record for {deviceCode}?",
|
||||
"deleted": "Maintenance record deleted",
|
||||
"deleteFailed": "Failed to delete maintenance record"
|
||||
"deleteFailed": "Failed to delete maintenance record",
|
||||
"deviceNotFound": "The equipment does not exist, so a maintenance record cannot be added."
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"deviceLedgerInfo": "Equipment Ledger Info",
|
||||
"deviceLedgerInfo": "Equipment Info",
|
||||
"recordInfo": "Equipment Maintenance Records",
|
||||
"recordQueryResult": "Maintenance Record Results",
|
||||
"matched": "Matched",
|
||||
"recordMatched": "Maintenance records matched",
|
||||
"recentRecords": "Recent maintenance records ({count})",
|
||||
"returnedRecords": "{count} records returned",
|
||||
"latestRepair": "Latest Repair",
|
||||
"totalCount": "Total Count",
|
||||
"totalCost": "Total Cost",
|
||||
"viewRepairHistory": "View Repair History",
|
||||
"viewRecordDetail": "View Details",
|
||||
"operation": "Action",
|
||||
"recordDetailTitle": "Maintenance Record Details",
|
||||
"recordDetailHint": "The right-side panel shows the selected maintenance record.",
|
||||
"recordDetailPermissionHint": "Query details are visible to regular users; edit, delete, and supplement actions require management permission.",
|
||||
"continueFilter": "Continue Filtering",
|
||||
"adminActionsHidden": "Management actions are only available to admins / maintenance managers.",
|
||||
"addRepairRecord": "Add Repair Record",
|
||||
"inputPlaceholder": "Ask me about equipment maintenance, e.g. query ledger info for A022700978"
|
||||
"manageLedger": "Equipment Ledger",
|
||||
"logRepair": "Log Repair",
|
||||
"inputPlaceholder": "Ask me about equipment maintenance, e.g. query equipment info for A022700978"
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
"ledger": {
|
||||
"notice": "หน้านี้ใช้สำหรับจัดการทะเบียนอุปกรณ์",
|
||||
"tabs": {
|
||||
"list": "รายการอุปกรณ์",
|
||||
"form": "ตั้งค่าอุปกรณ์"
|
||||
"list": "ทะเบียนอุปกรณ์",
|
||||
"form": "เพิ่ม/แก้ไข"
|
||||
},
|
||||
"status": {
|
||||
"all": "ทุกสถานะ",
|
||||
@@ -79,11 +79,11 @@
|
||||
},
|
||||
"panel": {
|
||||
"recordTitle": "บันทึกซ่อมบำรุง",
|
||||
"ledgerTitle": "ตั้งค่าทะเบียน",
|
||||
"ledgerTitle": "ทะเบียนอุปกรณ์",
|
||||
"adminOnly": "งานผู้ดูแล: เฉพาะผู้ดูแลระบบ / ผู้ดูแลซ่อมบำรุง",
|
||||
"resizeTitle": "ลากเพื่อปรับความกว้าง",
|
||||
"ledgerSubtitle": "รายการอุปกรณ์ / ตั้งค่าอุปกรณ์",
|
||||
"recordSubtitle": "รายการบันทึก / ตั้งค่าบันทึก",
|
||||
"ledgerSubtitle": "จัดการทะเบียนอุปกรณ์",
|
||||
"recordSubtitle": "จัดการบันทึกซ่อมบำรุง",
|
||||
"fullscreen": "เต็มหน้าจอ",
|
||||
"exitFullscreen": "ออกจากเต็มหน้าจอ",
|
||||
"close": "ปิด"
|
||||
@@ -91,11 +91,12 @@
|
||||
"record": {
|
||||
"notice": "บันทึกซ่อมบำรุงใช้สำหรับผู้ดูแลในการดูแลการแจ้งซ่อม การดำเนินการ ค่าใช้จ่าย และชั่วโมงงาน ส่วนการค้นหาทั่วไปยังทำผ่านแชทได้",
|
||||
"tabs": {
|
||||
"list": "รายการบันทึก",
|
||||
"form": "ตั้งค่าบันทึก"
|
||||
"list": "บันทึกซ่อมบำรุง",
|
||||
"form": "เพิ่ม/แก้ไข"
|
||||
},
|
||||
"status": {
|
||||
"all": "ทุกสถานะ",
|
||||
"active": "ยังไม่เสร็จ",
|
||||
"pending": "รอซ่อม",
|
||||
"processing": "กำลังซ่อม",
|
||||
"done": "เสร็จสิ้น",
|
||||
@@ -120,10 +121,16 @@
|
||||
"backToList": "กลับไปรายการ",
|
||||
"cancel": "ยกเลิก",
|
||||
"save": "บันทึก",
|
||||
"saving": "กำลังบันทึก..."
|
||||
"saving": "กำลังบันทึก...",
|
||||
"viewAllHistory": "ดูประวัติทั้งหมด"
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "ค้นหารหัสอุปกรณ์หรือชื่ออุปกรณ์"
|
||||
"keywordPlaceholder": "ค้นหารหัสอุปกรณ์หรือชื่ออุปกรณ์",
|
||||
"defaultHint": "ค่าเริ่มต้นแสดงเฉพาะรายการที่ยังไม่เสร็จ (รอซ่อม/กำลังซ่อม) ในช่วง 1 ปีล่าสุด หากต้องการดูประวัติทั้งหมด ให้เลือกทุกสถานะและทุกช่วงเวลา",
|
||||
"timeRangeLabel": "วันที่แจ้งซ่อม",
|
||||
"timeRange3m": "3 เดือนล่าสุด",
|
||||
"timeRange1y": "1 ปีล่าสุด",
|
||||
"timeRangeAll": "ทุกช่วงเวลา"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "รหัสอุปกรณ์",
|
||||
@@ -134,7 +141,8 @@
|
||||
"repairer": "ผู้ซ่อม",
|
||||
"operation": "การดำเนินการ",
|
||||
"loading": "กำลังโหลด...",
|
||||
"empty": "ไม่มีบันทึกซ่อมบำรุง"
|
||||
"empty": "ไม่มีบันทึกซ่อมบำรุง",
|
||||
"emptyActive": "ไม่มีรายการที่ยังไม่เสร็จในช่วง 1 ปีล่าสุด"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "รหัสอุปกรณ์",
|
||||
@@ -160,11 +168,14 @@
|
||||
},
|
||||
"deviceSnapshot": {
|
||||
"loading": "กำลังค้นหาทะเบียนอุปกรณ์...",
|
||||
"title": "อุปกรณ์ในทะเบียน",
|
||||
"matched": "จับคู่แล้ว",
|
||||
"notFound": "ไม่พบอุปกรณ์ โปรดตรวจสอบรหัสหรือลงทะเบียนในทะเบียนก่อน",
|
||||
"position": "ตำแหน่ง",
|
||||
"department": "แผนก",
|
||||
"responsibleUser": "ผู้รับผิดชอบ",
|
||||
"status": "สถานะ",
|
||||
"empty": "กรอกรหัสอุปกรณ์เพื่อจับคู่ข้อมูลทะเบียนอุปกรณ์อัตโนมัติ"
|
||||
"empty": "กรอกรหัสอุปกรณ์เพื่อจับคู่ข้อมูลทะเบียนอัตโนมัติ"
|
||||
},
|
||||
"importResult": "ผลการนำเข้า: ทั้งหมด {total} รายการ, เพิ่ม {created}, ล้มเหลว {failed}",
|
||||
"importErrorRow": "แถว {row}: {message}",
|
||||
@@ -184,17 +195,32 @@
|
||||
"saveFailed": "บันทึกข้อมูลซ่อมบำรุงไม่สำเร็จ",
|
||||
"deleteConfirm": "ลบบันทึกซ่อมบำรุงของ {deviceCode} หรือไม่?",
|
||||
"deleted": "ลบบันทึกซ่อมบำรุงแล้ว",
|
||||
"deleteFailed": "ลบบันทึกซ่อมบำรุงไม่สำเร็จ"
|
||||
"deleteFailed": "ลบบันทึกซ่อมบำรุงไม่สำเร็จ",
|
||||
"deviceNotFound": "ไม่พบอุปกรณ์ จึงไม่สามารถเพิ่มบันทึกซ่อมบำรุงได้"
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"deviceLedgerInfo": "ข้อมูลทะเบียนอุปกรณ์",
|
||||
"deviceLedgerInfo": "ข้อมูลอุปกรณ์",
|
||||
"recordInfo": "บันทึกซ่อมบำรุงอุปกรณ์",
|
||||
"recordQueryResult": "ผลการค้นหาบันทึกซ่อมบำรุง",
|
||||
"matched": "พบข้อมูล",
|
||||
"recordMatched": "พบบันทึกซ่อมบำรุง",
|
||||
"recentRecords": "บันทึกซ่อมบำรุงล่าสุด ({count})",
|
||||
"returnedRecords": "พบ {count} รายการ",
|
||||
"latestRepair": "ซ่อมล่าสุด",
|
||||
"totalCount": "จำนวนรวม",
|
||||
"totalCost": "ค่าใช้จ่ายรวม",
|
||||
"viewRepairHistory": "ดูประวัติซ่อม",
|
||||
"viewRecordDetail": "ดูรายละเอียด",
|
||||
"operation": "การทำงาน",
|
||||
"recordDetailTitle": "รายละเอียดบันทึกซ่อม",
|
||||
"recordDetailHint": "แผงด้านขวาแสดงบันทึกซ่อมที่เลือก",
|
||||
"recordDetailPermissionHint": "รายละเอียดสำหรับค้นหาผู้ใช้ทั่วไปดูได้ ส่วนแก้ไข ลบ และเพิ่มข้อมูลต้องมีสิทธิ์จัดการ",
|
||||
"continueFilter": "กรองต่อ",
|
||||
"adminActionsHidden": "การจัดการใช้ได้เฉพาะผู้ดูแลระบบ / ผู้จัดการซ่อมบำรุง",
|
||||
"addRepairRecord": "เพิ่มบันทึกซ่อม",
|
||||
"inputPlaceholder": "ถามข้อมูลซ่อมบำรุงอุปกรณ์ เช่น ค้นหาทะเบียนของ A022700978"
|
||||
"manageLedger": "ทะเบียนอุปกรณ์",
|
||||
"logRepair": "ลงทะเบียนซ่อม",
|
||||
"inputPlaceholder": "ถามข้อมูลซ่อมบำรุงอุปกรณ์ เช่น ค้นหาข้อมูลอุปกรณ์ A022700978"
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
"ledger": {
|
||||
"notice": "当前页面用于设备台账管理。",
|
||||
"tabs": {
|
||||
"list": "设备列表",
|
||||
"form": "设备配置"
|
||||
"list": "设备台账",
|
||||
"form": "新增/编辑"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部状态",
|
||||
@@ -26,7 +26,7 @@
|
||||
"edit": "编辑",
|
||||
"backToList": "返回列表",
|
||||
"cancel": "取消",
|
||||
"save": "保存配置",
|
||||
"save": "保存",
|
||||
"saving": "保存中..."
|
||||
},
|
||||
"filters": {
|
||||
@@ -79,11 +79,11 @@
|
||||
},
|
||||
"panel": {
|
||||
"recordTitle": "维修记录",
|
||||
"ledgerTitle": "台账配置",
|
||||
"ledgerTitle": "设备台账",
|
||||
"adminOnly": "管理操作:仅管理员 / 维保管理员可用",
|
||||
"resizeTitle": "拖拽调整宽度",
|
||||
"ledgerSubtitle": "设备列表 / 设备配置",
|
||||
"recordSubtitle": "记录列表 / 记录配置",
|
||||
"ledgerSubtitle": "设备台账管理",
|
||||
"recordSubtitle": "维修记录管理",
|
||||
"fullscreen": "全屏",
|
||||
"exitFullscreen": "退出全屏",
|
||||
"close": "关闭"
|
||||
@@ -91,11 +91,12 @@
|
||||
"record": {
|
||||
"notice": "维修记录用于管理员维护设备报修、处理、费用和工时信息;普通查询仍可通过会话完成。",
|
||||
"tabs": {
|
||||
"list": "记录列表",
|
||||
"form": "记录配置"
|
||||
"list": "维修记录",
|
||||
"form": "新增/编辑"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部状态",
|
||||
"active": "未完成",
|
||||
"pending": "待维修",
|
||||
"processing": "维修中",
|
||||
"done": "已完成",
|
||||
@@ -119,11 +120,17 @@
|
||||
"deleting": "删除中...",
|
||||
"backToList": "返回列表",
|
||||
"cancel": "取消",
|
||||
"save": "保存记录",
|
||||
"saving": "保存中..."
|
||||
"save": "保存",
|
||||
"saving": "保存中...",
|
||||
"viewAllHistory": "查看全部历史"
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "搜索设备编号、设备名称"
|
||||
"keywordPlaceholder": "搜索设备编号、设备名称",
|
||||
"defaultHint": "默认显示近一年内未完成(待维修、维修中)的记录;查全部历史请选择「全部状态」和「全部时间」。",
|
||||
"timeRangeLabel": "报修时间",
|
||||
"timeRange3m": "近 3 个月",
|
||||
"timeRange1y": "近 1 年",
|
||||
"timeRangeAll": "全部时间"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "设备编号",
|
||||
@@ -134,7 +141,8 @@
|
||||
"repairer": "维修人",
|
||||
"operation": "操作",
|
||||
"loading": "加载中...",
|
||||
"empty": "暂无维修记录"
|
||||
"empty": "暂无维修记录",
|
||||
"emptyActive": "近一年内暂无未完成记录"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "设备编号",
|
||||
@@ -160,11 +168,14 @@
|
||||
},
|
||||
"deviceSnapshot": {
|
||||
"loading": "正在查询设备台账...",
|
||||
"title": "台账设备",
|
||||
"matched": "已匹配",
|
||||
"notFound": "未找到该设备,请检查编号或先在台账中登记",
|
||||
"position": "位置",
|
||||
"department": "部门",
|
||||
"responsibleUser": "责任人",
|
||||
"status": "状态",
|
||||
"empty": "输入设备编号后可自动匹配设备台账快照。"
|
||||
"empty": "输入设备编号后将自动匹配台账信息"
|
||||
},
|
||||
"importResult": "导入结果:共 {total} 条,新增 {created} 条,失败 {failed} 条。",
|
||||
"importErrorRow": "第 {row} 行:{message}",
|
||||
@@ -184,17 +195,32 @@
|
||||
"saveFailed": "保存维修记录失败",
|
||||
"deleteConfirm": "确认删除 {deviceCode} 的维修记录?",
|
||||
"deleted": "维修记录已删除",
|
||||
"deleteFailed": "删除维修记录失败"
|
||||
"deleteFailed": "删除维修记录失败",
|
||||
"deviceNotFound": "设备不存在,不能新增维修记录"
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"deviceLedgerInfo": "设备台账信息",
|
||||
"deviceLedgerInfo": "设备信息",
|
||||
"recordInfo": "设备维修记录",
|
||||
"recordQueryResult": "维修记录查询结果",
|
||||
"matched": "已匹配",
|
||||
"recordMatched": "已匹配维修记录",
|
||||
"recentRecords": "最近维修记录({count} 条)",
|
||||
"returnedRecords": "已返回 {count} 条",
|
||||
"latestRepair": "最近维修",
|
||||
"totalCount": "累计次数",
|
||||
"totalCost": "累计费用",
|
||||
"viewRepairHistory": "查维修历史",
|
||||
"viewRecordDetail": "查看明细",
|
||||
"operation": "操作",
|
||||
"recordDetailTitle": "维修记录明细",
|
||||
"recordDetailHint": "右侧固定面板展示当前选中维修记录。",
|
||||
"recordDetailPermissionHint": "查询类明细面板:普通用户可查看;编辑、删除、补录仍需管理权限。",
|
||||
"continueFilter": "继续筛选",
|
||||
"adminActionsHidden": "管理操作仅管理员 / 维保管理员可用。",
|
||||
"addRepairRecord": "新增维修记录",
|
||||
"inputPlaceholder": "问我设备维保相关信息,例如:查询 A022700978 的设备台账信息"
|
||||
"manageLedger": "设备台账",
|
||||
"logRepair": "登记维修",
|
||||
"inputPlaceholder": "问我设备维保相关信息,例如:查询 A022700978 的设备信息"
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
"ledger": {
|
||||
"notice": "目前頁面用於設備台帳管理。",
|
||||
"tabs": {
|
||||
"list": "設備列表",
|
||||
"form": "設備配置"
|
||||
"list": "設備台帳",
|
||||
"form": "新增/編輯"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部狀態",
|
||||
@@ -26,7 +26,7 @@
|
||||
"edit": "編輯",
|
||||
"backToList": "返回列表",
|
||||
"cancel": "取消",
|
||||
"save": "儲存配置",
|
||||
"save": "儲存",
|
||||
"saving": "儲存中..."
|
||||
},
|
||||
"filters": {
|
||||
@@ -79,11 +79,11 @@
|
||||
},
|
||||
"panel": {
|
||||
"recordTitle": "維修記錄",
|
||||
"ledgerTitle": "台帳配置",
|
||||
"ledgerTitle": "設備台帳",
|
||||
"adminOnly": "管理操作:僅管理員 / 維保管理員可用",
|
||||
"resizeTitle": "拖曳調整寬度",
|
||||
"ledgerSubtitle": "設備列表 / 設備配置",
|
||||
"recordSubtitle": "記錄列表 / 記錄配置",
|
||||
"ledgerSubtitle": "設備台帳管理",
|
||||
"recordSubtitle": "維修記錄管理",
|
||||
"fullscreen": "全螢幕",
|
||||
"exitFullscreen": "退出全螢幕",
|
||||
"close": "關閉"
|
||||
@@ -91,11 +91,12 @@
|
||||
"record": {
|
||||
"notice": "維修記錄用於管理員維護設備報修、處理、費用和工時資訊;一般查詢仍可透過會話完成。",
|
||||
"tabs": {
|
||||
"list": "記錄列表",
|
||||
"form": "記錄配置"
|
||||
"list": "維修記錄",
|
||||
"form": "新增/編輯"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部狀態",
|
||||
"active": "未完成",
|
||||
"pending": "待維修",
|
||||
"processing": "維修中",
|
||||
"done": "已完成",
|
||||
@@ -119,11 +120,17 @@
|
||||
"deleting": "刪除中...",
|
||||
"backToList": "返回列表",
|
||||
"cancel": "取消",
|
||||
"save": "儲存記錄",
|
||||
"saving": "儲存中..."
|
||||
"save": "儲存",
|
||||
"saving": "儲存中...",
|
||||
"viewAllHistory": "查看全部歷史"
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "搜尋設備編號、設備名稱"
|
||||
"keywordPlaceholder": "搜尋設備編號、設備名稱",
|
||||
"defaultHint": "預設顯示近一年內未完成(待維修、維修中)的記錄;查全部歷史請選擇「全部狀態」和「全部時間」。",
|
||||
"timeRangeLabel": "報修時間",
|
||||
"timeRange3m": "近 3 個月",
|
||||
"timeRange1y": "近 1 年",
|
||||
"timeRangeAll": "全部時間"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "設備編號",
|
||||
@@ -134,7 +141,8 @@
|
||||
"repairer": "維修人",
|
||||
"operation": "操作",
|
||||
"loading": "載入中...",
|
||||
"empty": "暫無維修記錄"
|
||||
"empty": "暫無維修記錄",
|
||||
"emptyActive": "近一年內暫無未完成記錄"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "設備編號",
|
||||
@@ -160,11 +168,14 @@
|
||||
},
|
||||
"deviceSnapshot": {
|
||||
"loading": "正在查詢設備台帳...",
|
||||
"title": "台帳設備",
|
||||
"matched": "已匹配",
|
||||
"notFound": "未找到該設備,請檢查編號或先在台帳中登記",
|
||||
"position": "位置",
|
||||
"department": "部門",
|
||||
"responsibleUser": "責任人",
|
||||
"status": "狀態",
|
||||
"empty": "輸入設備編號後可自動匹配設備台帳快照。"
|
||||
"empty": "輸入設備編號後將自動匹配台帳資訊"
|
||||
},
|
||||
"importResult": "匯入結果:共 {total} 筆,新增 {created} 筆,失敗 {failed} 筆。",
|
||||
"importErrorRow": "第 {row} 行:{message}",
|
||||
@@ -184,17 +195,32 @@
|
||||
"saveFailed": "儲存維修記錄失敗",
|
||||
"deleteConfirm": "確認刪除 {deviceCode} 的維修記錄?",
|
||||
"deleted": "維修記錄已刪除",
|
||||
"deleteFailed": "刪除維修記錄失敗"
|
||||
"deleteFailed": "刪除維修記錄失敗",
|
||||
"deviceNotFound": "設備不存在,不能新增維修記錄"
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"deviceLedgerInfo": "設備台帳資訊",
|
||||
"deviceLedgerInfo": "設備資訊",
|
||||
"recordInfo": "設備維修記錄",
|
||||
"recordQueryResult": "維修記錄查詢結果",
|
||||
"matched": "已匹配",
|
||||
"recordMatched": "已匹配維修記錄",
|
||||
"recentRecords": "最近維修記錄({count} 筆)",
|
||||
"returnedRecords": "已返回 {count} 筆",
|
||||
"latestRepair": "最近維修",
|
||||
"totalCount": "累計次數",
|
||||
"totalCost": "累計費用",
|
||||
"viewRepairHistory": "查維修歷史",
|
||||
"viewRecordDetail": "查看明細",
|
||||
"operation": "操作",
|
||||
"recordDetailTitle": "維修記錄明細",
|
||||
"recordDetailHint": "右側固定面板展示目前選中的維修記錄。",
|
||||
"recordDetailPermissionHint": "查詢類明細面板:普通用戶可查看;編輯、刪除、補錄仍需管理權限。",
|
||||
"continueFilter": "繼續篩選",
|
||||
"adminActionsHidden": "管理操作僅管理員 / 維保管理員可用。",
|
||||
"addRepairRecord": "新增維修記錄",
|
||||
"inputPlaceholder": "問我設備維保相關資訊,例如:查詢 A022700978 的設備台帳資訊"
|
||||
"manageLedger": "設備台帳",
|
||||
"logRepair": "登記維修",
|
||||
"inputPlaceholder": "問我設備維保相關資訊,例如:查詢 A022700978 的設備資訊"
|
||||
}
|
||||
}
|
||||
@@ -333,6 +333,26 @@
|
||||
background-color: var(--bg-surface);
|
||||
}
|
||||
|
||||
.admin-table-sticky-right-head {
|
||||
position: sticky;
|
||||
right: 0;
|
||||
z-index: 30;
|
||||
background-color: var(--bg-surface-soft);
|
||||
background-clip: padding-box;
|
||||
border-left: 1px solid var(--border-default);
|
||||
box-shadow: -8px 0 16px -8px rgba(15, 23, 42, 0.18);
|
||||
}
|
||||
|
||||
.admin-table-sticky-right-cell {
|
||||
position: sticky;
|
||||
right: 0;
|
||||
z-index: 20;
|
||||
background-color: var(--bg-surface);
|
||||
background-clip: padding-box;
|
||||
border-left: 1px solid var(--border-default);
|
||||
box-shadow: -8px 0 16px -8px rgba(15, 23, 42, 0.12);
|
||||
}
|
||||
|
||||
.admin-report-table-wrap {
|
||||
@apply overflow-x-auto rounded-2xl border border-default shadow-elevated;
|
||||
background-color: var(--bg-surface);
|
||||
@@ -463,6 +483,22 @@
|
||||
background-color: #0284c7;
|
||||
}
|
||||
|
||||
.admin-report-page-btn--edit {
|
||||
@apply border-brand-300 bg-brand-50 font-semibold text-brand-700;
|
||||
}
|
||||
|
||||
.admin-report-page-btn--edit:hover:not(:disabled) {
|
||||
@apply bg-brand-100;
|
||||
}
|
||||
|
||||
.admin-report-page-btn--danger {
|
||||
@apply border-rose-300 bg-rose-50 font-semibold text-rose-700;
|
||||
}
|
||||
|
||||
.admin-report-page-btn--danger:hover:not(:disabled) {
|
||||
@apply bg-rose-100;
|
||||
}
|
||||
|
||||
.admin-report-page-btn:disabled {
|
||||
@apply opacity-40 cursor-not-allowed;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user