Merge branch 'device' into dev
This commit is contained in:
commit
3a22df736e
39 files changed
+6554
-6
No files matched your search
@@ -56,7 +56,7 @@ MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
# RoHS / 货代/ 设备维保等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
@@ -58,5 +58,5 @@ MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
@@ -60,7 +60,7 @@ MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
# RoHS / 货代/ 设备维保等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
@@ -24,6 +24,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
from app.api.user import user_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.maintenance import maintenance_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
|
||||
@@ -36,7 +37,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
workspace_schedule_bp,
|
||||
workspace_shipping_notice_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, shipping_notice_bp
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
@@ -51,7 +52,9 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
@@ -1356,6 +1356,7 @@ def chat_completions():
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
from app.services.maintenance_chat_service import MaintenanceChatService
|
||||
faq_hit = FaqCacheService.try_match(query, agent_id) if not normalized_files else None
|
||||
|
||||
if faq_hit:
|
||||
@@ -1367,6 +1368,14 @@ def chat_completions():
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif not normalized_files and MaintenanceChatService.supports(query, agent_proxy):
|
||||
generator = MaintenanceChatService.stream_chat(
|
||||
query,
|
||||
user_proxy,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif PLMOracleService.supports(query, agent_proxy):
|
||||
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported and leave_feature_enabled:
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
"""
|
||||
backend/app/api/maintenance.py
|
||||
|
||||
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
||||
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
||||
逻辑:查询接口面向会话与面板复用;写入/导入接口先做角色校验,再委托 service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.maintenance_ledger_service import (
|
||||
build_import_template,
|
||||
create_device,
|
||||
get_device,
|
||||
import_devices_from_excel,
|
||||
list_devices,
|
||||
update_device,
|
||||
)
|
||||
from app.services.maintenance_record_service import (
|
||||
build_records_export,
|
||||
create_record,
|
||||
delete_record,
|
||||
get_record,
|
||||
list_records,
|
||||
update_record,
|
||||
)
|
||||
|
||||
maintenance_bp = Blueprint('maintenance', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_ledger_admin():
|
||||
"""
|
||||
校验设备台账管理权限。
|
||||
Returns:
|
||||
当前用户对象。
|
||||
Raises:
|
||||
ForbiddenError: 当前角色不允许写入台账。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, 'role', None) not in {'admin', 'asset_admin', 'maintenance_manager'}:
|
||||
raise ForbiddenError('Maintenance ledger admin privilege required')
|
||||
return user
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['GET'])
|
||||
def list_ledger_devices():
|
||||
"""查询设备台账列表,供 Agent 查询结果与右侧台账配置面板使用。"""
|
||||
_require_user()
|
||||
result = list_devices(
|
||||
keyword=request.args.get('keyword'),
|
||||
status=request.args.get('status'),
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['GET'])
|
||||
def get_ledger_device(device_id: int):
|
||||
"""读取设备台账详情。"""
|
||||
_require_user()
|
||||
return jsonify(get_device(device_id))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['POST'])
|
||||
def create_ledger_device():
|
||||
"""新增设备台账,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(create_device(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['PUT'])
|
||||
def update_ledger_device(device_id: int):
|
||||
"""更新设备台账,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(update_device(device_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/import-template', methods=['GET'])
|
||||
def download_ledger_import_template():
|
||||
"""下载设备台账 Excel 导入模板。"""
|
||||
_require_ledger_admin()
|
||||
return send_file(
|
||||
BytesIO(build_import_template()),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_devices_import_template.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/import', methods=['POST'])
|
||||
def import_ledger_devices():
|
||||
"""上传 Excel 模板并批量新增/更新设备台账。"""
|
||||
user = _require_ledger_admin()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
result = import_devices_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['GET'])
|
||||
def list_maintenance_records():
|
||||
"""查询设备维修记录,供 Agent 会话查询和结果卡片使用。"""
|
||||
_require_user()
|
||||
result = list_records(
|
||||
keyword=request.args.get('keyword'),
|
||||
device_code=request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
status=request.args.get('status'),
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['GET'])
|
||||
def get_maintenance_record(record_id: int):
|
||||
"""读取设备维修记录详情。"""
|
||||
_require_user()
|
||||
return jsonify(get_record(record_id))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/export', methods=['GET'])
|
||||
def export_maintenance_records():
|
||||
"""按当前筛选条件导出设备维修记录 Excel。"""
|
||||
_require_user()
|
||||
data = build_records_export(
|
||||
keyword=request.args.get('keyword'),
|
||||
device_code=request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
status=request.args.get('status'),
|
||||
)
|
||||
return send_file(
|
||||
BytesIO(data),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_records.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['POST'])
|
||||
def create_maintenance_record():
|
||||
"""新增设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(create_record(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['PUT'])
|
||||
def update_maintenance_record(record_id: int):
|
||||
"""更新设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(update_record(record_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['DELETE'])
|
||||
def delete_maintenance_record(record_id: int):
|
||||
"""删除设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
return jsonify(delete_record(record_id, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
backend/app/api/maintenance_tools.py
|
||||
|
||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import MaintenanceRecord
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.maintenance_chat_service import build_device_query_result
|
||||
from app.services.maintenance_record_service import serialize_record
|
||||
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
|
||||
|
||||
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验设备维保 Tool API 鉴权。
|
||||
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
return exc.code
|
||||
|
||||
|
||||
@maintenance_tool_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""Tool API 统一错误响应。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@maintenance_tool_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""读取 JSON 请求体。"""
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _clean_text(value) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON。"""
|
||||
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(
|
||||
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
|
||||
def query_device():
|
||||
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
include_records = bool(data.get("include_records", True))
|
||||
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
|
||||
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
|
||||
def query_records():
|
||||
"""按设备编号/名称和状态查询维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
status = _clean_text(data.get("status"))
|
||||
limit = max(1, min(50, int(data.get("limit") or 10)))
|
||||
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceRecord.device_code.ilike(like),
|
||||
MaintenanceRecord.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"matched": bool(rows),
|
||||
"keyword": keyword,
|
||||
"items": [serialize_record(item) for item in rows],
|
||||
"totalReturned": len(rows),
|
||||
})
|
||||
|
||||
@@ -6,5 +6,6 @@ backend/app/api/tools/__init__.py
|
||||
"""
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
from app.api.tools.file_check import file_check_bp # noqa: F401
|
||||
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp']
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/api/tools/maintenance.py
|
||||
|
||||
用途:设备维保 Tool API Blueprint re-export。
|
||||
依赖:app.api.maintenance_tools。
|
||||
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
|
||||
"""
|
||||
|
||||
from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401
|
||||
@@ -13,6 +13,7 @@ from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlL
|
||||
from app.models.department import Department
|
||||
from app.models.job import Job
|
||||
from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob
|
||||
from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord
|
||||
from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.models.settings import AppSetting
|
||||
from app.models.shipping import (
|
||||
@@ -66,4 +67,7 @@ __all__ = [
|
||||
'ShippingInventoryMapping',
|
||||
'AgentGuide',
|
||||
'TrainingRecord',
|
||||
'MaintenanceDevice',
|
||||
'MaintenanceRecord',
|
||||
'MaintenanceAuditLog',
|
||||
]
|
||||
@@ -0,0 +1,101 @@
|
||||
"""
|
||||
backend/app/models/maintenance.py
|
||||
|
||||
用途:设备维保域数据模型,当前覆盖设备台账与台账变更审计。
|
||||
依赖:models.base.Base、SQLAlchemy mapped_column。
|
||||
逻辑:maintenance_devices 为维保助手查询/配置的设备主数据;audit_logs 记录台账导入与人工修改。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Date, DateTime, Index, Numeric, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class MaintenanceDevice(Base):
|
||||
"""设备台账主数据;责任人暂存用户名字符串,不与 users 表建立外键关系。"""
|
||||
|
||||
__tablename__ = 'maintenance_devices'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('device_code', name='uq_maintenance_devices_device_code'),
|
||||
Index('ix_maintenance_devices_name', 'device_name'),
|
||||
Index('ix_maintenance_devices_location', 'install_location'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
device_code: Mapped[str] = mapped_column(String(80), nullable=False)
|
||||
device_name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
model_spec: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
department: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
install_location: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
device_status: Mapped[str] = mapped_column(String(30), default='in_use', nullable=False)
|
||||
manufacturer: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
entry_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
production_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
start_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
responsible_user: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
maintenance_cycle: Mapped[Optional[str]] = mapped_column(String(80), nullable=True)
|
||||
original_value: Mapped[Optional[float]] = mapped_column(Numeric(14, 2), nullable=True)
|
||||
residual_value: Mapped[Optional[float]] = mapped_column(Numeric(14, 2), nullable=True)
|
||||
account_set: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
updated_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class MaintenanceAuditLog(Base):
|
||||
"""设备维保域审计日志,记录台账新增、更新、Excel 导入等写入动作。"""
|
||||
|
||||
__tablename__ = 'maintenance_audit_logs'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
object_type: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
object_id: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
action: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
before_data: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
after_data: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
operator_name: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(80), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class MaintenanceRecord(Base):
|
||||
"""设备维修记录,保存报修、修复与费用工时信息。"""
|
||||
|
||||
__tablename__ = 'maintenance_records'
|
||||
__table_args__ = (
|
||||
Index('ix_maintenance_records_device_code', 'device_code'),
|
||||
Index('ix_maintenance_records_report_date', 'report_date'),
|
||||
Index('ix_maintenance_records_status', 'repair_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
device_id: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
device_code: Mapped[str] = mapped_column(String(80), nullable=False)
|
||||
device_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
model_spec: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
install_location: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
report_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
repair_category: Mapped[Optional[str]] = mapped_column(String(80), nullable=True)
|
||||
fault_description: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
reporter: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
approver: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
repair_status: Mapped[str] = mapped_column(String(30), default='pending', nullable=False)
|
||||
repair_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
repair_unit: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
repairer: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
repair_cost: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
repair_hours: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
repair_description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
source_order_no: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
created_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
updated_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
@@ -0,0 +1,229 @@
|
||||
"""
|
||||
backend/app/services/maintenance_chat_service.py
|
||||
|
||||
用途:设备维保助手的会话查询直答服务,用于把设备编号/名称查询转换成设备台账卡片。
|
||||
依赖:MaintenanceDevice/MaintenanceRecord、ChatLog、SQLAlchemy、SSE JSON 输出。
|
||||
逻辑:chat.py 在设备维保助手命中查询意图时调用本服务;本服务查询台账和维修记录,写入聊天历史并返回结构化消息。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from typing import Any, Iterator
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.models import ChatLog, MaintenanceDevice, MaintenanceRecord
|
||||
from app.services.maintenance_ledger_service import serialize_device
|
||||
from app.services.maintenance_record_service import REPAIR_STATUS_LABELS, serialize_record
|
||||
|
||||
MAINTENANCE_AGENT_NAME = '设备维保助手'
|
||||
|
||||
|
||||
def is_maintenance_chat_agent(agent: Any) -> bool:
|
||||
"""
|
||||
判断当前 Agent 是否为设备维保助手。
|
||||
Args:
|
||||
agent: Agent ORM 或代理对象。
|
||||
Returns:
|
||||
命中设备维保助手时返回 True。
|
||||
"""
|
||||
name = str(getattr(agent, 'name', '') or '').strip()
|
||||
return name == MAINTENANCE_AGENT_NAME or ('设备维保' in name and '助手' in name)
|
||||
|
||||
|
||||
def _clean_text(value: Any) -> str:
|
||||
return str(value or '').strip()
|
||||
|
||||
|
||||
def extract_device_query_keyword(query: str) -> str | None:
|
||||
"""
|
||||
从用户自然语言里提取设备编号或设备名称关键词。
|
||||
AI 触发时机:当用户在设备维保助手里询问“查询某设备/某编号/维修记录”时,用它判断是否走本地台账查询。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
Returns:
|
||||
设备编号或名称关键词;无法判断时返回 None。
|
||||
"""
|
||||
text = _clean_text(query)
|
||||
if not text:
|
||||
return None
|
||||
if not re.search(r'(设备|台账|台帳|维保|維保|维修|維修|保养|保養|查询|查詢|查看|检索)', text):
|
||||
return None
|
||||
|
||||
code_match = re.search(r'\b[A-Za-z]{1,6}\d{4,}[A-Za-z0-9_-]*\b', text)
|
||||
if code_match:
|
||||
return code_match.group(0).strip()
|
||||
digit_match = re.search(r'\b\d{6,}\b', text)
|
||||
if digit_match:
|
||||
return digit_match.group(0).strip()
|
||||
|
||||
cleaned = re.sub(
|
||||
r'(查询|查詢|查看|检索|一下|这条|這條|这个|這個|设备|設備|台账|台帳|信息|資料|维保|維保|维修|維修|记录|記錄|历史|歷史|的|了|请|請|帮我|幫我)',
|
||||
' ',
|
||||
text,
|
||||
)
|
||||
cleaned = re.sub(r'[\s,。,.??!!::;;]+', ' ', cleaned).strip()
|
||||
return cleaned[:80] or None
|
||||
|
||||
|
||||
def _find_device(keyword: str) -> MaintenanceDevice | None:
|
||||
"""按设备编号优先,其次按设备名称模糊匹配查找单台设备。"""
|
||||
value = _clean_text(keyword)
|
||||
if not value:
|
||||
return None
|
||||
exact = db.session.query(MaintenanceDevice).filter(MaintenanceDevice.device_code == value).first()
|
||||
if exact:
|
||||
return exact
|
||||
like = f'%{value}%'
|
||||
return (
|
||||
db.session.query(MaintenanceDevice)
|
||||
.filter(or_(MaintenanceDevice.device_code.ilike(like), MaintenanceDevice.device_name.ilike(like)))
|
||||
.order_by(MaintenanceDevice.updated_at.desc(), MaintenanceDevice.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _build_payload(device: MaintenanceDevice, *, include_records: bool = True, record_limit: int = 5) -> dict[str, Any]:
|
||||
"""构建设备台账卡片 payload,包含设备信息和最近维修记录。"""
|
||||
record_limit = max(0, min(20, int(record_limit or 0)))
|
||||
records = (
|
||||
db.session.query(MaintenanceRecord)
|
||||
.filter(MaintenanceRecord.device_code == device.device_code)
|
||||
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
|
||||
.limit(record_limit)
|
||||
.all()
|
||||
) if include_records and record_limit > 0 else []
|
||||
serialized_records = [serialize_record(item) for item in records]
|
||||
status_counts: dict[str, int] = {}
|
||||
for item in serialized_records:
|
||||
key = str(item.get('repairStatus') or '')
|
||||
status_counts[key] = status_counts.get(key, 0) + 1
|
||||
return {
|
||||
'source': 'maintenance_device_query',
|
||||
'matched': True,
|
||||
'device': serialize_device(device),
|
||||
'records': serialized_records,
|
||||
'summary': {
|
||||
'recentRecordCount': len(serialized_records),
|
||||
'statusCounts': status_counts,
|
||||
'statusLabels': REPAIR_STATUS_LABELS,
|
||||
},
|
||||
'actions': [
|
||||
{'id': 'viewMaintenanceHistory', 'label': '查维修历史'},
|
||||
{'id': 'createMaintenanceRecord', 'label': '新增维修记录'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def build_device_query_result(keyword: str, *, include_records: bool = True, record_limit: int = 5) -> dict[str, Any]:
|
||||
"""
|
||||
查询设备台账并返回统一结构,供会话直答和 Dify Tool 共用。
|
||||
Args:
|
||||
keyword: 设备编号或设备名称。
|
||||
include_records: 是否附带最近维修记录。
|
||||
record_limit: 最近维修记录最大返回条数。
|
||||
Returns:
|
||||
设备查询结果 payload。
|
||||
"""
|
||||
device = _find_device(keyword)
|
||||
if not device:
|
||||
return {
|
||||
'source': 'maintenance_device_query',
|
||||
'matched': False,
|
||||
'keyword': keyword,
|
||||
'device': None,
|
||||
'records': [],
|
||||
}
|
||||
return _build_payload(device, include_records=include_records, record_limit=record_limit)
|
||||
|
||||
|
||||
def supports(query: str, agent: Any) -> bool:
|
||||
"""
|
||||
判断是否应由设备维保本地查询服务接管。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
agent: 当前 Agent。
|
||||
Returns:
|
||||
True 表示命中设备查询意图。
|
||||
"""
|
||||
return is_maintenance_chat_agent(agent) and bool(extract_device_query_keyword(query))
|
||||
|
||||
|
||||
def stream_chat(
|
||||
query: str,
|
||||
user: Any,
|
||||
agent: Any,
|
||||
conversation_id: str | None = None,
|
||||
session_id: str | None = None,
|
||||
) -> Iterator[str]:
|
||||
"""
|
||||
以 SSE 返回设备查询结果,并写入 ChatLog 供历史会话回放。
|
||||
Args:
|
||||
query: 用户原始问题。
|
||||
user: 当前用户代理对象。
|
||||
agent: 当前 Agent 代理对象。
|
||||
conversation_id: 外部会话 ID,设备本地查询会沿用本地 session。
|
||||
session_id: 本地会话 ID。
|
||||
Yields:
|
||||
SSE data 帧。
|
||||
"""
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or session_id or f'maintenance_{int(time.time())}'
|
||||
keyword = extract_device_query_keyword(query) or ''
|
||||
result = build_device_query_result(keyword, include_records=True, record_limit=5)
|
||||
|
||||
if result.get('matched'):
|
||||
content = '已查询设备台账信息,下面是匹配结果。'
|
||||
payload = result
|
||||
message_type = 'maintenance-device-result'
|
||||
else:
|
||||
content = f'未找到与“{keyword or query}”匹配的设备台账信息,请检查设备编号或设备名称。'
|
||||
payload = result
|
||||
message_type = 'text'
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': content}, ensure_ascii=False)}\n\n"
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=getattr(user, 'id', None),
|
||||
agent_id=getattr(agent, 'id', None),
|
||||
conversation_id=final_conversation_id,
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
answer=content,
|
||||
tokens_used=0,
|
||||
latency=int((time.time() - start_time) * 1000),
|
||||
message_type=message_type if message_type != 'text' else None,
|
||||
payload=payload,
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[maintenance-chat] failed to log chat: %s', exc)
|
||||
db.session.rollback()
|
||||
|
||||
yield f"data: {json.dumps({
|
||||
'event': 'message_end',
|
||||
'answer': content,
|
||||
'replace_answer': True,
|
||||
'type': message_type,
|
||||
'payload': payload,
|
||||
'message_payload': payload,
|
||||
'chat_log_id': chat_log_id,
|
||||
'conversation_id': final_conversation_id,
|
||||
'metadata': {'source': 'maintenance_device_query'},
|
||||
}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
class MaintenanceChatService:
|
||||
"""设备维保助手会话查询服务门面,供 chat.py 按统一 Service 风格调用。"""
|
||||
|
||||
supports = staticmethod(supports)
|
||||
stream_chat = staticmethod(stream_chat)
|
||||
@@ -0,0 +1,423 @@
|
||||
"""
|
||||
backend/app/services/maintenance_ledger_service.py
|
||||
|
||||
用途:设备维保台账的查询、保存、Excel 模板与导入业务编排。
|
||||
依赖:MaintenanceDevice/MaintenanceAuditLog、openpyxl、统一 AppError。
|
||||
逻辑:API 层只做请求解析;本服务负责字段校验、upsert、审计与 Excel 行级导入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import MaintenanceAuditLog, MaintenanceDevice
|
||||
|
||||
DEVICE_STATUS_VALUES = {'in_use', 'disabled', 'scrapped', 'sold'}
|
||||
ACCOUNT_SET_VALUES = {'和信', '科技', '电子', '和宏智'}
|
||||
DEFAULT_ACCOUNT_SET = '和信'
|
||||
|
||||
TEMPLATE_COLUMNS = [
|
||||
'设备编号',
|
||||
'设备名称',
|
||||
'型号规格',
|
||||
'使用部门',
|
||||
'安装地点',
|
||||
'设备状态',
|
||||
'制造厂家',
|
||||
'进厂日期',
|
||||
'生产日期',
|
||||
'启用日期',
|
||||
'责任人用户名',
|
||||
'维护周期',
|
||||
'原值',
|
||||
'残值',
|
||||
'账套',
|
||||
'备注',
|
||||
]
|
||||
|
||||
HEADER_MAP = {
|
||||
'设备编号': 'device_code',
|
||||
'设备名称': 'device_name',
|
||||
'型号规格': 'model_spec',
|
||||
'使用部门': 'department',
|
||||
'安装地点': 'install_location',
|
||||
'设备状态': 'device_status',
|
||||
'制造厂家': 'manufacturer',
|
||||
'进厂日期': 'entry_date',
|
||||
'生产日期': 'production_date',
|
||||
'启用日期': 'start_date',
|
||||
'责任人用户名': 'responsible_user',
|
||||
'维护周期': 'maintenance_cycle',
|
||||
'原值': 'original_value',
|
||||
'残值': 'residual_value',
|
||||
'账套': 'account_set',
|
||||
'备注': 'remark',
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ImportResult:
|
||||
"""Excel 导入统计结果。"""
|
||||
|
||||
total: int = 0
|
||||
created: int = 0
|
||||
updated: int = 0
|
||||
failed: int = 0
|
||||
errors: list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
def _clean_text(value: Any) -> str | None:
|
||||
text = str(value or '').strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _parse_date(value: Any, field_name: str) -> date | None:
|
||||
"""
|
||||
解析台账日期字段。
|
||||
Args:
|
||||
value: Excel/JSON 中传入的日期、日期时间或 YYYY-MM-DD 字符串。
|
||||
field_name: 字段名,用于错误提示。
|
||||
Returns:
|
||||
date 或 None。
|
||||
Raises:
|
||||
ValidationError: 日期格式不合法。
|
||||
"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
text = str(value).strip()
|
||||
for fmt in ('%Y-%m-%d', '%Y/%m/%d'):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValidationError(f'{field_name} must be YYYY-MM-DD')
|
||||
|
||||
|
||||
def _parse_amount(value: Any, field_name: str) -> float | None:
|
||||
"""
|
||||
解析设备金额字段。
|
||||
Args:
|
||||
value: JSON/Excel 中传入的金额,可为空、数字或数字字符串。
|
||||
field_name: 字段名,用于错误提示。
|
||||
Returns:
|
||||
两位小数浮点数或 None。
|
||||
Raises:
|
||||
ValidationError: 金额格式非法或小于 0。
|
||||
"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
try:
|
||||
amount = round(float(str(value).replace(',', '').strip()), 2)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f'{field_name} must be numeric') from exc
|
||||
if amount < 0:
|
||||
raise ValidationError(f'{field_name} must be greater than or equal to 0')
|
||||
return amount
|
||||
|
||||
|
||||
def _device_to_audit_dict(device: MaintenanceDevice) -> dict[str, Any]:
|
||||
"""设备 ORM 转审计快照 dict。"""
|
||||
return serialize_device(device)
|
||||
|
||||
|
||||
def _operator_name(user: Any | None) -> str | None:
|
||||
"""从当前用户对象中取展示用户名;未登录时返回 None。"""
|
||||
if not user:
|
||||
return None
|
||||
return getattr(user, 'real_name', None) or getattr(user, 'username', None) or str(getattr(user, 'id', '') or '') or None
|
||||
|
||||
|
||||
def _write_audit(
|
||||
*,
|
||||
object_type: str,
|
||||
object_id: int | None,
|
||||
action: str,
|
||||
before_data: dict[str, Any] | None,
|
||||
after_data: dict[str, Any] | None,
|
||||
operator_name: str | None,
|
||||
request_id: str | None,
|
||||
) -> None:
|
||||
"""写入设备维保域审计日志,随业务事务一起提交。"""
|
||||
db.session.add(
|
||||
MaintenanceAuditLog(
|
||||
object_type=object_type,
|
||||
object_id=object_id,
|
||||
action=action,
|
||||
before_data=json.dumps(before_data, ensure_ascii=False, default=str) if before_data else None,
|
||||
after_data=json.dumps(after_data, ensure_ascii=False, default=str) if after_data else None,
|
||||
operator_name=operator_name,
|
||||
request_id=request_id,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def serialize_device(device: MaintenanceDevice) -> dict[str, Any]:
|
||||
"""设备 ORM 转 API dict,保持前端 camelCase 命名。"""
|
||||
return {
|
||||
'id': device.id,
|
||||
'deviceCode': device.device_code,
|
||||
'deviceName': device.device_name,
|
||||
'modelSpec': device.model_spec,
|
||||
'department': device.department,
|
||||
'installLocation': device.install_location,
|
||||
'deviceStatus': device.device_status,
|
||||
'manufacturer': device.manufacturer,
|
||||
'entryDate': device.entry_date.isoformat() if device.entry_date else None,
|
||||
'productionDate': device.production_date.isoformat() if device.production_date else None,
|
||||
'startDate': device.start_date.isoformat() if device.start_date else None,
|
||||
'responsibleUser': device.responsible_user,
|
||||
'maintenanceCycle': device.maintenance_cycle,
|
||||
'originalValue': float(device.original_value) if device.original_value is not None else None,
|
||||
'residualValue': float(device.residual_value) if device.residual_value is not None else None,
|
||||
'accountSet': device.account_set,
|
||||
'remark': device.remark,
|
||||
'createdAt': device.created_at.isoformat() if device.created_at else None,
|
||||
'updatedAt': device.updated_at.isoformat() if device.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _normalize_payload(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
标准化设备台账入参。
|
||||
Args:
|
||||
data: 前端 JSON 或 Excel 行映射。
|
||||
Returns:
|
||||
可直接写入 MaintenanceDevice 的 snake_case dict。
|
||||
Raises:
|
||||
ValidationError: 必填字段缺失或状态/日期非法。
|
||||
"""
|
||||
device_code = _clean_text(data.get('deviceCode') or data.get('device_code'))
|
||||
device_name = _clean_text(data.get('deviceName') or data.get('device_name'))
|
||||
if not device_code:
|
||||
raise ValidationError('deviceCode is required')
|
||||
if not device_name:
|
||||
raise ValidationError('deviceName is required')
|
||||
|
||||
status = _clean_text(data.get('deviceStatus') or data.get('device_status')) or 'in_use'
|
||||
status_map = {'在用': 'in_use', '停用': 'disabled', '报废': 'scrapped', '出售': 'sold', '已出售': 'sold'}
|
||||
status = status_map.get(status, status)
|
||||
if status not in DEVICE_STATUS_VALUES:
|
||||
raise ValidationError('deviceStatus is invalid')
|
||||
account_set = _clean_text(data.get('accountSet') or data.get('account_set')) or DEFAULT_ACCOUNT_SET
|
||||
if account_set and account_set not in ACCOUNT_SET_VALUES:
|
||||
raise ValidationError('accountSet is invalid')
|
||||
|
||||
return {
|
||||
'device_code': device_code,
|
||||
'device_name': device_name,
|
||||
'model_spec': _clean_text(data.get('modelSpec') or data.get('model_spec')),
|
||||
'department': _clean_text(data.get('department')),
|
||||
'install_location': _clean_text(data.get('installLocation') or data.get('install_location')),
|
||||
'device_status': status,
|
||||
'manufacturer': _clean_text(data.get('manufacturer')),
|
||||
'entry_date': _parse_date(data.get('entryDate') or data.get('entry_date'), 'entryDate'),
|
||||
'production_date': _parse_date(data.get('productionDate') or data.get('production_date'), 'productionDate'),
|
||||
'start_date': _parse_date(data.get('startDate') or data.get('start_date'), 'startDate'),
|
||||
'responsible_user': _clean_text(data.get('responsibleUser') or data.get('responsible_user')),
|
||||
'maintenance_cycle': _clean_text(data.get('maintenanceCycle') or data.get('maintenance_cycle')),
|
||||
'original_value': _parse_amount(data.get('originalValue') or data.get('original_value'), 'originalValue'),
|
||||
'residual_value': _parse_amount(data.get('residualValue') or data.get('residual_value'), 'residualValue'),
|
||||
'account_set': account_set,
|
||||
'remark': _clean_text(data.get('remark')),
|
||||
}
|
||||
|
||||
|
||||
def list_devices(*, keyword: str | None = None, status: str | None = None, page: int = 1, page_size: int = 20) -> dict[str, Any]:
|
||||
"""分页查询设备台账,支持关键字与状态筛选。"""
|
||||
query = db.session.query(MaintenanceDevice)
|
||||
keyword = _clean_text(keyword)
|
||||
if keyword:
|
||||
like = f'%{keyword}%'
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceDevice.device_code.ilike(like),
|
||||
MaintenanceDevice.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(MaintenanceDevice.device_status == status)
|
||||
total = query.count()
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(200, page_size))
|
||||
items = (
|
||||
query.order_by(MaintenanceDevice.updated_at.desc(), MaintenanceDevice.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {'items': [serialize_device(item) for item in items], 'total': total, 'page': page, 'pageSize': page_size}
|
||||
|
||||
|
||||
def get_device(device_id: int) -> dict[str, Any]:
|
||||
"""读取单台设备详情。"""
|
||||
device = db.session.get(MaintenanceDevice, device_id)
|
||||
if not device:
|
||||
raise NotFoundError('Device not found')
|
||||
return serialize_device(device)
|
||||
|
||||
|
||||
def create_device(data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""新增设备台账,并写入审计日志。"""
|
||||
values = _normalize_payload(data)
|
||||
if db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first():
|
||||
raise ConflictError('deviceCode exists', code='MAINTENANCE.DEVICE_CODE_EXISTS')
|
||||
now_operator = _operator_name(operator)
|
||||
device = MaintenanceDevice(**values, created_by=now_operator, updated_by=now_operator)
|
||||
db.session.add(device)
|
||||
db.session.flush()
|
||||
after = _device_to_audit_dict(device)
|
||||
_write_audit(
|
||||
object_type='device',
|
||||
object_id=device.id,
|
||||
action='create',
|
||||
before_data=None,
|
||||
after_data=after,
|
||||
operator_name=now_operator,
|
||||
request_id=request_id,
|
||||
)
|
||||
db.session.commit()
|
||||
return serialize_device(device)
|
||||
|
||||
|
||||
def update_device(device_id: int, data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""更新设备台账,并写入审计日志。"""
|
||||
device = db.session.get(MaintenanceDevice, device_id)
|
||||
if not device:
|
||||
raise NotFoundError('Device not found')
|
||||
values = _normalize_payload(data)
|
||||
exists = db.session.query(MaintenanceDevice).filter(
|
||||
MaintenanceDevice.device_code == values['device_code'],
|
||||
MaintenanceDevice.id != device_id,
|
||||
).first()
|
||||
if exists:
|
||||
raise ConflictError('deviceCode exists', code='MAINTENANCE.DEVICE_CODE_EXISTS')
|
||||
before = _device_to_audit_dict(device)
|
||||
for key, value in values.items():
|
||||
setattr(device, key, value)
|
||||
device.updated_by = _operator_name(operator)
|
||||
db.session.flush()
|
||||
after = _device_to_audit_dict(device)
|
||||
_write_audit(
|
||||
object_type='device',
|
||||
object_id=device.id,
|
||||
action='update',
|
||||
before_data=before,
|
||||
after_data=after,
|
||||
operator_name=_operator_name(operator),
|
||||
request_id=request_id,
|
||||
)
|
||||
db.session.commit()
|
||||
return serialize_device(device)
|
||||
|
||||
|
||||
def build_import_template() -> bytes:
|
||||
"""生成设备台账导入模板 Excel。"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = '设备台账导入'
|
||||
ws.append(TEMPLATE_COLUMNS)
|
||||
ws.append(['A022700978', '注塑件自动冲切水口机', 'ML-ZS030', '注塑部', '二期车间一楼注塑区', '在用', '昆山开发区盟荣机械厂', '2021-06-18', '2021-05-20', '2021-06-18', '张三', '按需维修', 120000, 12000, '和信', '示例行,可删除'])
|
||||
header_fill = PatternFill(fill_type='solid', fgColor='D9EAF7')
|
||||
for col in range(1, len(TEMPLATE_COLUMNS) + 1):
|
||||
cell = ws.cell(row=1, column=col)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = header_fill
|
||||
ws.column_dimensions[cell.column_letter].width = 18
|
||||
out = BytesIO()
|
||||
wb.save(out)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def import_devices_from_excel(file_obj: Any, *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
从 Excel 模板导入设备台账。
|
||||
Args:
|
||||
file_obj: Flask upload file object。
|
||||
operator: 当前登录用户。
|
||||
request_id: 请求 ID。
|
||||
Returns:
|
||||
导入统计,含行级错误。
|
||||
"""
|
||||
filename = (getattr(file_obj, 'filename', '') or '').lower()
|
||||
if not filename.endswith('.xlsx'):
|
||||
raise ValidationError('Only .xlsx template is supported')
|
||||
try:
|
||||
wb = load_workbook(file_obj, data_only=True)
|
||||
except Exception as exc:
|
||||
raise ValidationError('Invalid Excel file') from exc
|
||||
ws = wb.active
|
||||
headers = [str(cell.value or '').strip() for cell in ws[1]]
|
||||
missing = [name for name in ('设备编号', '设备名称') if name not in headers]
|
||||
if missing:
|
||||
raise ValidationError('Template columns missing', details={'missing': missing})
|
||||
idx = {name: headers.index(name) for name in headers if name}
|
||||
result = ImportResult(errors=[])
|
||||
operator_name = _operator_name(operator)
|
||||
|
||||
for row_no, row in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
|
||||
if not any(row):
|
||||
continue
|
||||
result.total += 1
|
||||
raw = {}
|
||||
for header, field in HEADER_MAP.items():
|
||||
if header in idx and idx[header] < len(row):
|
||||
raw[field] = row[idx[header]]
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
values = _normalize_payload(raw)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
before = _device_to_audit_dict(device)
|
||||
for key, value in values.items():
|
||||
setattr(device, key, value)
|
||||
device.updated_by = operator_name
|
||||
db.session.flush()
|
||||
_write_audit(
|
||||
object_type='device',
|
||||
object_id=device.id,
|
||||
action='import_update',
|
||||
before_data=before,
|
||||
after_data=_device_to_audit_dict(device),
|
||||
operator_name=operator_name,
|
||||
request_id=request_id,
|
||||
)
|
||||
result.updated += 1
|
||||
else:
|
||||
device = MaintenanceDevice(**values, created_by=operator_name, updated_by=operator_name)
|
||||
db.session.add(device)
|
||||
db.session.flush()
|
||||
_write_audit(
|
||||
object_type='device',
|
||||
object_id=device.id,
|
||||
action='import_create',
|
||||
before_data=None,
|
||||
after_data=_device_to_audit_dict(device),
|
||||
operator_name=operator_name,
|
||||
request_id=request_id,
|
||||
)
|
||||
result.created += 1
|
||||
except Exception as exc:
|
||||
result.failed += 1
|
||||
result.errors.append({'row': row_no, 'message': str(getattr(exc, 'message', None) or exc)})
|
||||
db.session.commit()
|
||||
return {
|
||||
'total': result.total,
|
||||
'created': result.created,
|
||||
'updated': result.updated,
|
||||
'failed': result.failed,
|
||||
'errors': result.errors or [],
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
backend/app/services/maintenance_record_service.py
|
||||
|
||||
用途:设备维修记录查询与新增业务编排。
|
||||
依赖:MaintenanceRecord/MaintenanceDevice、统一 AppError、审计日志写入。
|
||||
逻辑:新增记录时按设备编号带出台账快照;查询结果供 Agent 会话和右侧面板复用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import MaintenanceDevice, MaintenanceRecord
|
||||
from app.services.maintenance_ledger_service import _operator_name, _parse_date, _write_audit
|
||||
|
||||
REPAIR_STATUS_VALUES = {'pending', 'processing', 'done', 'cancelled'}
|
||||
REPAIR_STATUS_LABELS = {
|
||||
'pending': '待维修',
|
||||
'processing': '维修中',
|
||||
'done': '已完成',
|
||||
'cancelled': '已取消',
|
||||
}
|
||||
|
||||
|
||||
def _clean_text(value: Any) -> str | None:
|
||||
text = str(value or '').strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def serialize_record(record: MaintenanceRecord) -> dict[str, Any]:
|
||||
"""维修记录 ORM 转 API dict。"""
|
||||
return {
|
||||
'id': record.id,
|
||||
'deviceId': record.device_id,
|
||||
'deviceCode': record.device_code,
|
||||
'deviceName': record.device_name,
|
||||
'modelSpec': record.model_spec,
|
||||
'installLocation': record.install_location,
|
||||
'reportDate': record.report_date.isoformat() if record.report_date else None,
|
||||
'repairCategory': record.repair_category,
|
||||
'faultDescription': record.fault_description,
|
||||
'reporter': record.reporter,
|
||||
'approver': record.approver,
|
||||
'repairStatus': record.repair_status,
|
||||
'repairDate': record.repair_date.isoformat() if record.repair_date else None,
|
||||
'repairUnit': record.repair_unit,
|
||||
'repairer': record.repairer,
|
||||
'repairCost': record.repair_cost,
|
||||
'repairHours': record.repair_hours,
|
||||
'repairDescription': record.repair_description,
|
||||
'sourceOrderNo': record.source_order_no,
|
||||
'createdAt': record.created_at.isoformat() if record.created_at else None,
|
||||
'updatedAt': record.updated_at.isoformat() if record.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _record_to_audit_dict(record: MaintenanceRecord) -> dict[str, Any]:
|
||||
"""维修记录 ORM 转审计快照。"""
|
||||
return serialize_record(record)
|
||||
|
||||
|
||||
def _normalize_payload(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
标准化维修记录入参。
|
||||
Args:
|
||||
data: 前端 JSON。
|
||||
Returns:
|
||||
可写入 MaintenanceRecord 的 snake_case dict。
|
||||
Raises:
|
||||
ValidationError: 必填字段缺失或日期/状态非法。
|
||||
"""
|
||||
device_code = _clean_text(data.get('deviceCode') or data.get('device_code'))
|
||||
fault_description = _clean_text(data.get('faultDescription') or data.get('fault_description'))
|
||||
if not device_code:
|
||||
raise ValidationError('deviceCode is required')
|
||||
if not fault_description:
|
||||
raise ValidationError('faultDescription is required')
|
||||
status = _clean_text(data.get('repairStatus') or data.get('repair_status')) or 'pending'
|
||||
status_map = {'待维修': 'pending', '维修中': 'processing', '已完成': 'done', '已取消': 'cancelled'}
|
||||
status = status_map.get(status, status)
|
||||
if status not in REPAIR_STATUS_VALUES:
|
||||
raise ValidationError('repairStatus is invalid')
|
||||
report_date = _parse_date(data.get('reportDate') or data.get('report_date') or date.today().isoformat(), 'reportDate')
|
||||
if not report_date:
|
||||
raise ValidationError('reportDate is required')
|
||||
return {
|
||||
'device_code': device_code,
|
||||
'report_date': report_date,
|
||||
'repair_category': _clean_text(data.get('repairCategory') or data.get('repair_category')),
|
||||
'fault_description': fault_description,
|
||||
'reporter': _clean_text(data.get('reporter')),
|
||||
'approver': _clean_text(data.get('approver')),
|
||||
'repair_status': status,
|
||||
'repair_date': _parse_date(data.get('repairDate') or data.get('repair_date'), 'repairDate'),
|
||||
'repair_unit': _clean_text(data.get('repairUnit') or data.get('repair_unit')),
|
||||
'repairer': _clean_text(data.get('repairer')),
|
||||
'repair_cost': _clean_text(data.get('repairCost') or data.get('repair_cost')),
|
||||
'repair_hours': _clean_text(data.get('repairHours') or data.get('repair_hours')),
|
||||
'repair_description': _clean_text(data.get('repairDescription') or data.get('repair_description')),
|
||||
'source_order_no': _clean_text(data.get('sourceOrderNo') or data.get('source_order_no')),
|
||||
}
|
||||
|
||||
|
||||
def list_records(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
device_code: str | None = None,
|
||||
status: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""分页查询维修记录。"""
|
||||
query = _records_query(keyword=keyword, device_code=device_code, status=status)
|
||||
total = query.count()
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(200, page_size))
|
||||
items = (
|
||||
query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {'items': [serialize_record(item) for item in items], 'total': total, 'page': page, 'pageSize': page_size}
|
||||
|
||||
|
||||
def _records_query(*, keyword: str | None = None, device_code: str | None = None, status: str | None = None):
|
||||
"""构造维修记录查询,供列表和导出复用。"""
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
if device_code:
|
||||
query = query.filter(MaintenanceRecord.device_code == device_code)
|
||||
if status:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
keyword = _clean_text(keyword)
|
||||
if keyword:
|
||||
like = f'%{keyword}%'
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceRecord.device_code.ilike(like),
|
||||
MaintenanceRecord.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
def build_records_export(*, keyword: str | None = None, device_code: str | None = None, status: str | None = None) -> bytes:
|
||||
"""按当前筛选条件导出维修记录 Excel。"""
|
||||
rows = (
|
||||
_records_query(keyword=keyword, device_code=device_code, status=status)
|
||||
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
|
||||
.limit(5000)
|
||||
.all()
|
||||
)
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = '维修记录'
|
||||
headers = [
|
||||
'设备编号',
|
||||
'设备名称',
|
||||
'型号规格',
|
||||
'设备位置',
|
||||
'报修日期',
|
||||
'维修类别',
|
||||
'故障描述',
|
||||
'维修状态',
|
||||
'维修日期',
|
||||
'维修单位',
|
||||
'维修人',
|
||||
'维修费用',
|
||||
'维修工时',
|
||||
'维修说明',
|
||||
'报修人',
|
||||
'审批人',
|
||||
'来源工单号',
|
||||
]
|
||||
ws.append(headers)
|
||||
for item in rows:
|
||||
ws.append(
|
||||
[
|
||||
item.device_code,
|
||||
item.device_name,
|
||||
item.model_spec,
|
||||
item.install_location,
|
||||
item.report_date.isoformat() if item.report_date else '',
|
||||
item.repair_category,
|
||||
item.fault_description,
|
||||
REPAIR_STATUS_LABELS.get(item.repair_status, item.repair_status),
|
||||
item.repair_date.isoformat() if item.repair_date else '',
|
||||
item.repair_unit,
|
||||
item.repairer,
|
||||
item.repair_cost,
|
||||
item.repair_hours,
|
||||
item.repair_description,
|
||||
item.reporter,
|
||||
item.approver,
|
||||
item.source_order_no,
|
||||
]
|
||||
)
|
||||
header_fill = PatternFill(fill_type='solid', fgColor='D9EAF7')
|
||||
for col in range(1, len(headers) + 1):
|
||||
cell = ws.cell(row=1, column=col)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = header_fill
|
||||
ws.column_dimensions[cell.column_letter].width = 18
|
||||
out = BytesIO()
|
||||
wb.save(out)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def get_record(record_id: int) -> dict[str, Any]:
|
||||
"""读取维修记录详情。"""
|
||||
record = db.session.get(MaintenanceRecord, record_id)
|
||||
if not record:
|
||||
raise NotFoundError('Maintenance record not found')
|
||||
return serialize_record(record)
|
||||
|
||||
|
||||
def create_record(data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""新增维修记录,并写入审计日志。"""
|
||||
values = _normalize_payload(data)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
operator_name = _operator_name(operator)
|
||||
record = MaintenanceRecord(**values, created_by=operator_name, updated_by=operator_name)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
_write_audit(
|
||||
object_type='record',
|
||||
object_id=record.id,
|
||||
action='create',
|
||||
before_data=None,
|
||||
after_data=_record_to_audit_dict(record),
|
||||
operator_name=operator_name,
|
||||
request_id=request_id,
|
||||
)
|
||||
db.session.commit()
|
||||
return serialize_record(record)
|
||||
|
||||
|
||||
def update_record(record_id: int, data: dict[str, Any], *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""更新维修记录,并重新按设备编号刷新台账快照。"""
|
||||
record = db.session.get(MaintenanceRecord, record_id)
|
||||
if not record:
|
||||
raise NotFoundError('Maintenance record not found')
|
||||
before = _record_to_audit_dict(record)
|
||||
values = _normalize_payload(data)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id if device else None,
|
||||
'device_name': device.device_name if device else None,
|
||||
'model_spec': device.model_spec if device else None,
|
||||
'install_location': device.install_location if device else None,
|
||||
}
|
||||
)
|
||||
for key, value in values.items():
|
||||
setattr(record, key, value)
|
||||
operator_name = _operator_name(operator)
|
||||
record.updated_by = operator_name
|
||||
db.session.flush()
|
||||
_write_audit(
|
||||
object_type='record',
|
||||
object_id=record.id,
|
||||
action='update',
|
||||
before_data=before,
|
||||
after_data=_record_to_audit_dict(record),
|
||||
operator_name=operator_name,
|
||||
request_id=request_id,
|
||||
)
|
||||
db.session.commit()
|
||||
return serialize_record(record)
|
||||
|
||||
|
||||
def delete_record(record_id: int, *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""删除维修记录,并写入删除审计。"""
|
||||
record = db.session.get(MaintenanceRecord, record_id)
|
||||
if not record:
|
||||
raise NotFoundError('Maintenance record not found')
|
||||
before = _record_to_audit_dict(record)
|
||||
operator_name = _operator_name(operator)
|
||||
_write_audit(
|
||||
object_type='record',
|
||||
object_id=record.id,
|
||||
action='delete',
|
||||
before_data=before,
|
||||
after_data=None,
|
||||
operator_name=operator_name,
|
||||
request_id=request_id,
|
||||
)
|
||||
db.session.delete(record)
|
||||
db.session.commit()
|
||||
return {'deleted': True, 'id': record_id}
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/services/maintenance_tools/__init__.py
|
||||
|
||||
用途:设备维保 Dify Tool 服务包入口。
|
||||
依赖:openapi_spec 等子模块。
|
||||
逻辑:api/maintenance_tools.py 通过本包导入 OpenAPI 构建能力,后续可继续扩展工具编排。
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
backend/app/services/maintenance_tools/openapi_spec.py
|
||||
|
||||
用途:构建设备维保助手 Dify Tool API 的 OpenAPI 描述。
|
||||
依赖:标准 typing。
|
||||
逻辑:/api/maintenance/tools/openapi.json 调用本模块;Dify 导入后可调用只读设备台账与维修记录查询工具。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _str_prop(description: str) -> dict[str, Any]:
|
||||
"""构造字符串字段描述。"""
|
||||
return {"type": "string", "description": description}
|
||||
|
||||
|
||||
def _bool_prop(description: str, *, default: bool = False) -> dict[str, Any]:
|
||||
"""构造布尔字段描述。"""
|
||||
return {"type": "boolean", "description": description, "default": default}
|
||||
|
||||
|
||||
def _int_prop(description: str, *, default: int | None = None) -> dict[str, Any]:
|
||||
"""构造整数字段描述。"""
|
||||
prop: dict[str, Any] = {"type": "integer", "description": description}
|
||||
if default is not None:
|
||||
prop["default"] = default
|
||||
return prop
|
||||
|
||||
|
||||
def _post_op(
|
||||
operation_id: str,
|
||||
summary: str,
|
||||
properties: dict[str, Any],
|
||||
*,
|
||||
required: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造 Dify Tool 兼容的 POST OpenAPI 操作。"""
|
||||
schema: dict[str, Any] = {"type": "object", "properties": properties}
|
||||
if required:
|
||||
schema["required"] = required
|
||||
return {
|
||||
"post": {
|
||||
"operationId": operation_id,
|
||||
"summary": summary,
|
||||
"description": summary,
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {"application/json": {"schema": schema}},
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response. ok=true 表示调用成功;matched=false 表示未匹配到设备或记录。",
|
||||
"content": {"application/json": {"schema": {"type": "object"}}},
|
||||
}
|
||||
},
|
||||
"security": [{"BearerAuth": []}, {"IntegrationKey": []}],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def build_maintenance_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"""
|
||||
构建设备维保 Dify Tool OpenAPI。
|
||||
Args:
|
||||
base_url: HXOPS 对外 Tool API 根地址。
|
||||
Returns:
|
||||
OpenAPI 3.0 dict。
|
||||
"""
|
||||
server = str(base_url or "").strip().rstrip("/")
|
||||
if not server.endswith("/api/maintenance"):
|
||||
server = f"{server}/api/maintenance" if server else "/api/maintenance"
|
||||
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "Maintenance Tools",
|
||||
"version": "1.0.0",
|
||||
"description": (
|
||||
"设备维保助手只读 Tool API。适合 Dify 处理复杂自然语言问法时查询设备台账、最近维修记录;"
|
||||
"新增、编辑、删除等配置动作不得通过 Dify Tool 执行,应由 HXOPS 右侧管理面板完成。"
|
||||
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||
),
|
||||
},
|
||||
"servers": [{"url": server, "description": "HXOPS_TOOLS_API_BASE"}],
|
||||
"paths": {
|
||||
"/tools/query_device": _post_op(
|
||||
"queryMaintenanceDevice",
|
||||
"查询设备台账信息,可附带最近维修记录",
|
||||
{
|
||||
"keyword": _str_prop("设备编号或设备名称,例如 A022700978 或 注塑件自动冲切水口机"),
|
||||
"include_records": _bool_prop("是否返回最近维修记录", default=True),
|
||||
"record_limit": _int_prop("最多返回几条最近维修记录,建议 3-10", default=5),
|
||||
},
|
||||
required=["keyword"],
|
||||
),
|
||||
"/tools/query_records": _post_op(
|
||||
"queryMaintenanceRecords",
|
||||
"查询设备维修记录",
|
||||
{
|
||||
"keyword": _str_prop("设备编号或设备名称关键词"),
|
||||
"status": _str_prop("维修状态,可选:pending、processing、done、cancelled"),
|
||||
"limit": _int_prop("最多返回记录数,建议 5-20", default=10),
|
||||
},
|
||||
required=["keyword"],
|
||||
),
|
||||
},
|
||||
"components": {
|
||||
"securitySchemes": {
|
||||
"BearerAuth": {"type": "http", "scheme": "bearer"},
|
||||
"IntegrationKey": {
|
||||
"type": "apiKey",
|
||||
"in": "header",
|
||||
"name": "X-Integration-Key",
|
||||
"description": "与 Bearer 二选一",
|
||||
},
|
||||
}
|
||||
},
|
||||
"security": [{"BearerAuth": []}, {"IntegrationKey": []}],
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""add maintenance ledger tables
|
||||
|
||||
Revision ID: fd4e5f6a7b8c
|
||||
Revises: fc3d4e5f6a7b
|
||||
Create Date: 2026-07-03 09:30:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'fd4e5f6a7b8c'
|
||||
down_revision = 'fc3d4e5f6a7b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'maintenance_devices',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('device_code', sa.String(length=80), nullable=False),
|
||||
sa.Column('device_name', sa.String(length=200), nullable=False),
|
||||
sa.Column('model_spec', sa.String(length=200), nullable=True),
|
||||
sa.Column('department', sa.String(length=120), nullable=True),
|
||||
sa.Column('install_location', sa.String(length=255), nullable=True),
|
||||
sa.Column('device_status', sa.String(length=30), nullable=False),
|
||||
sa.Column('manufacturer', sa.String(length=200), nullable=True),
|
||||
sa.Column('entry_date', sa.Date(), nullable=True),
|
||||
sa.Column('production_date', sa.Date(), nullable=True),
|
||||
sa.Column('start_date', sa.Date(), nullable=True),
|
||||
sa.Column('responsible_user', sa.String(length=120), nullable=True),
|
||||
sa.Column('maintenance_cycle', sa.String(length=80), nullable=True),
|
||||
sa.Column('original_value', sa.Numeric(14, 2), nullable=True),
|
||||
sa.Column('residual_value', sa.Numeric(14, 2), nullable=True),
|
||||
sa.Column('account_set', sa.String(length=40), nullable=True),
|
||||
sa.Column('remark', sa.Text(), nullable=True),
|
||||
sa.Column('created_by', sa.String(length=120), nullable=True),
|
||||
sa.Column('updated_by', sa.String(length=120), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('device_code', name='uq_maintenance_devices_device_code'),
|
||||
)
|
||||
op.create_index('ix_maintenance_devices_location', 'maintenance_devices', ['install_location'], unique=False)
|
||||
op.create_index('ix_maintenance_devices_name', 'maintenance_devices', ['device_name'], unique=False)
|
||||
|
||||
op.create_table(
|
||||
'maintenance_audit_logs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('object_type', sa.String(length=40), nullable=False),
|
||||
sa.Column('object_id', sa.Integer(), nullable=True),
|
||||
sa.Column('action', sa.String(length=40), nullable=False),
|
||||
sa.Column('before_data', sa.Text(), nullable=True),
|
||||
sa.Column('after_data', sa.Text(), nullable=True),
|
||||
sa.Column('operator_name', sa.String(length=120), nullable=True),
|
||||
sa.Column('request_id', sa.String(length=80), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
'maintenance_records',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('device_id', sa.Integer(), nullable=True),
|
||||
sa.Column('device_code', sa.String(length=80), nullable=False),
|
||||
sa.Column('device_name', sa.String(length=200), nullable=True),
|
||||
sa.Column('model_spec', sa.String(length=200), nullable=True),
|
||||
sa.Column('install_location', sa.String(length=255), nullable=True),
|
||||
sa.Column('report_date', sa.Date(), nullable=False),
|
||||
sa.Column('repair_category', sa.String(length=80), nullable=True),
|
||||
sa.Column('fault_description', sa.Text(), nullable=False),
|
||||
sa.Column('reporter', sa.String(length=120), nullable=True),
|
||||
sa.Column('approver', sa.String(length=120), nullable=True),
|
||||
sa.Column('repair_status', sa.String(length=30), nullable=False),
|
||||
sa.Column('repair_date', sa.Date(), nullable=True),
|
||||
sa.Column('repair_unit', sa.String(length=200), nullable=True),
|
||||
sa.Column('repairer', sa.String(length=120), nullable=True),
|
||||
sa.Column('repair_cost', sa.String(length=40), nullable=True),
|
||||
sa.Column('repair_hours', sa.String(length=40), nullable=True),
|
||||
sa.Column('repair_description', sa.Text(), nullable=True),
|
||||
sa.Column('source_order_no', sa.String(length=120), nullable=True),
|
||||
sa.Column('created_by', sa.String(length=120), nullable=True),
|
||||
sa.Column('updated_by', sa.String(length=120), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_maintenance_records_device_code', 'maintenance_records', ['device_code'], unique=False)
|
||||
op.create_index('ix_maintenance_records_report_date', 'maintenance_records', ['report_date'], unique=False)
|
||||
op.create_index('ix_maintenance_records_status', 'maintenance_records', ['repair_status'], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('ix_maintenance_records_status', table_name='maintenance_records')
|
||||
op.drop_index('ix_maintenance_records_report_date', table_name='maintenance_records')
|
||||
op.drop_index('ix_maintenance_records_device_code', table_name='maintenance_records')
|
||||
op.drop_table('maintenance_records')
|
||||
op.drop_table('maintenance_audit_logs')
|
||||
op.drop_index('ix_maintenance_devices_name', table_name='maintenance_devices')
|
||||
op.drop_index('ix_maintenance_devices_location', table_name='maintenance_devices')
|
||||
op.drop_table('maintenance_devices')
|
||||
@@ -1,5 +1,14 @@
|
||||
# 智能HR请假管理需求
|
||||
|
||||
## 设备维保助手补充需求
|
||||
|
||||
- 查询方式:用户通过 `设备维保助手` 会话查询设备维护/维修记录,系统支持按设备编号、设备名称、故障描述、维修说明、维修人和状态筛选记录。
|
||||
- 管理方式:新增维修记录、设备台账配置属于固定管理人员操作,不通过会话消息承载;在聊天输入区底部以按钮进入右侧固定面板,面板顶部可关闭。
|
||||
- 台账配置:右侧固定面板包含“设备列表”和“设备配置”两个 Tab,设备字段包含设备编号、设备名称、型号规格、使用部门、安装地点、设备状态、制造厂家、进厂日期、生产日期、启用日期、责任人用户名、维护周期和备注。
|
||||
- Excel 导入:设备台账支持下载模板并从 Excel 批量导入,按设备编号判断新增或更新。
|
||||
- 责任人规则:`responsible_user` 存储用户名文本,当前阶段不与用户表建立外键关联。
|
||||
- 范围裁剪:不提供维修字典配置功能,不在底部按钮中展示该入口。
|
||||
|
||||
## 1. 项目背景
|
||||
|
||||
当前系统已经具备以下基础能力:
|
||||
|
||||
@@ -1,5 +1,19 @@
|
||||
# 智能HR请假管理功能清单
|
||||
|
||||
## 设备维保助手
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 会话式维修记录查询 | 后端已实现 | 新增 `/api/maintenance/records` 查询接口,支持按设备编号、设备名称、维修状态筛选,供 Agent 会话查询和前端结果复用 |
|
||||
| 会话式设备台账卡片 | 已实现 | 明确设备编号/名称查询由 HXOPS 后端本地直答,返回设备台账信息卡片和最近维修记录 |
|
||||
| Dify 设备维保查询 Tool | 已实现 | 新增 `/api/maintenance/tools/*` 只读 Tool API 与 `/api/maintenance/tools/openapi.json`,供 Dify 处理复杂问法时查询设备台账和维修记录 |
|
||||
| 维修记录管理 | 已实现 | `设备维保助手` 聊天输入栏底部提供“维修记录”按钮,右侧固定面板支持维修记录查询、新增、编辑、删除 |
|
||||
| 设备台账配置 | 已实现 | `设备维保助手` 聊天输入栏底部提供“台账配置”按钮,右侧固定面板包含“设备列表 / 设备配置”两个 Tab |
|
||||
| Excel 导入设备台账 | 已实现 | 支持下载设备台账模板并通过 Excel 批量导入,按设备编号新增或更新 |
|
||||
| 设备财务字段配置 | 已实现 | 设备台账支持原值、残值和账套字段;账套固定选项为和信、科技、电子、和宏智 |
|
||||
| 责任人字段 | 已实现 | 设备台账责任人字段使用 `responsible_user` / `responsibleUser` 用户名文本,不关联用户表 |
|
||||
| 维修字典配置 | 不纳入范围 | 底部按钮和正式功能中不提供“配置维修字典”入口 |
|
||||
|
||||
## 通用意见反馈
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+15
@@ -911,3 +911,18 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth;
|
||||
- Web 进程压力下降,系统稳定性提升
|
||||
- 失败任务可重试,进度展示更清晰
|
||||
- 整体知识库链路更适合后续扩展为高并发、多批次处理模式
|
||||
# 设备维保助手技术设计补充
|
||||
|
||||
## 数据模型
|
||||
|
||||
- `maintenance_devices`:设备台账主表,保存设备基础信息、进厂日期、生产日期、启用日期、责任人、原值、残值、账套等字段。
|
||||
- `maintenance_records`:设备维修记录表,保存报修日期、维修状态、故障描述、维修人、维修费用、维修工时等字段;新增记录时按设备编号快照设备名称、型号和安装地点。
|
||||
- `maintenance_audit_logs`:台账和维修记录写操作审计表,记录对象类型、操作类型、操作前后快照、操作人和请求 ID。
|
||||
|
||||
## 接口与前端
|
||||
|
||||
- 后端新增 `backend/app/api/maintenance.py`,统一挂载在 `/api/maintenance`。
|
||||
- 台账接口:`/api/maintenance/ledger/devices`、`/api/maintenance/ledger/import-template`、`/api/maintenance/ledger/import`。
|
||||
- 维修记录接口:`/api/maintenance/records`,支持查询详情、分页查询和新增。
|
||||
- 前端新增 `features/maintenance` 业务域,包含台账 API、维修记录 API、类型定义和右侧固定面板组件。
|
||||
- 聊天页仅当当前 Agent 名称为 `设备维保助手` 时显示底部管理按钮;查询继续走会话,配置类操作进入右侧固定面板。
|
||||
@@ -39,6 +39,7 @@ const props = defineProps<{
|
||||
isUploadingAttachments: boolean;
|
||||
canSendMessage: boolean;
|
||||
isShippingNoticeAgent: boolean;
|
||||
isMaintenanceAgent?: boolean;
|
||||
shippingSuggestedPrompt: string;
|
||||
shippingFocusTaskNo?: string;
|
||||
shippingFocusReason?: string;
|
||||
@@ -56,6 +57,8 @@ const emit = defineEmits<{
|
||||
'add-remote-url': [url: string];
|
||||
'shipping-inventory-selected': [event: Event];
|
||||
'use-shipping-suggested-prompt': [];
|
||||
'maintenance-ledger-config': [];
|
||||
'maintenance-create-record': [];
|
||||
'clear-shipping-focus': [];
|
||||
}>();
|
||||
|
||||
@@ -253,6 +256,27 @@ watch(
|
||||
<span>点发送开始处理</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isMaintenanceAgent"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-default bg-surface-soft px-3 py-1 font-medium text-secondary transition-colors hover:bg-surface-soft/70"
|
||||
@click="emit('maintenance-create-record')"
|
||||
>
|
||||
{{ $t('maintenance.panel.recordTitle') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-brand-200 bg-brand-50 px-3 py-1 font-medium text-brand-700 transition-colors hover:bg-brand-100"
|
||||
@click="emit('maintenance-ledger-config')"
|
||||
>
|
||||
▦ {{ $t('maintenance.panel.ledgerTitle') }}
|
||||
</button>
|
||||
<span>{{ $t('maintenance.panel.adminOnly') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { Loader2 } from 'lucide-vue-next';
|
||||
import { Maximize2, Minimize2, Loader2 } from 'lucide-vue-next';
|
||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
|
||||
import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
|
||||
@@ -16,17 +16,63 @@ import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
|
||||
import ShippingBatchWorkspaceDrawer from '@/features/chat/components/ShippingBatchWorkspaceDrawer.vue';
|
||||
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
|
||||
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
|
||||
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { matchesTrainingAgent } from '@/features/chat/composables/useTrainingWorkspace';
|
||||
|
||||
const page = useChatPageContext();
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
const isMaintenanceAgentPage = computed(() => {
|
||||
const name = String(page.currentAgent?.name || '').trim();
|
||||
return name === '设备维保助手' || (name.includes('设备维保') && name.includes('助手'));
|
||||
});
|
||||
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
|
||||
const isTrainingWorkspaceExpanded = ref(false);
|
||||
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
|
||||
const maintenancePanelWidth = ref(560);
|
||||
const isMaintenancePanelFullscreen = ref(false);
|
||||
const isMaintenancePanelResizing = ref(false);
|
||||
const maintenancePanelStyle = computed(() => {
|
||||
if (isMaintenancePanelFullscreen.value) {
|
||||
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
|
||||
}
|
||||
return {
|
||||
width: `${maintenancePanelWidth.value}px`,
|
||||
minWidth: '420px',
|
||||
maxWidth: '82vw',
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* 开始拖拽设备维保右侧面板左边缘,允许管理员按表格内容临时调宽。
|
||||
* @param event - 鼠标按下事件。
|
||||
*/
|
||||
const startMaintenancePanelResize = (event: MouseEvent): void => {
|
||||
if (isMaintenancePanelFullscreen.value) return;
|
||||
event.preventDefault();
|
||||
isMaintenancePanelResizing.value = true;
|
||||
const startX = event.clientX;
|
||||
const startWidth = maintenancePanelWidth.value;
|
||||
const handleMove = (moveEvent: MouseEvent) => {
|
||||
const nextWidth = startWidth + (startX - moveEvent.clientX);
|
||||
const maxWidth = Math.max(420, Math.floor(window.innerWidth * 0.82));
|
||||
maintenancePanelWidth.value = Math.min(maxWidth, Math.max(420, nextWidth));
|
||||
};
|
||||
const stopResize = () => {
|
||||
isMaintenancePanelResizing.value = false;
|
||||
window.removeEventListener('mousemove', handleMove);
|
||||
window.removeEventListener('mouseup', stopResize);
|
||||
};
|
||||
window.addEventListener('mousemove', handleMove);
|
||||
window.addEventListener('mouseup', stopResize);
|
||||
};
|
||||
|
||||
// 切换 Agent 时,重置工作区展开状态,确保每次进入都是收起状态(聊天优先)
|
||||
watch(() => page.currentAgentId, () => {
|
||||
isTrainingWorkspaceExpanded.value = false;
|
||||
maintenancePanel.value = null;
|
||||
isMaintenancePanelFullscreen.value = false;
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -170,6 +216,7 @@ watch(() => page.currentAgentId, () => {
|
||||
:is-uploading-attachments="page.isUploadingAttachments"
|
||||
:can-send-message="page.canSendMessage"
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
:is-maintenance-agent="isMaintenanceAgentPage"
|
||||
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
||||
:shipping-focus-task-no="page.focusedShippingTaskNo"
|
||||
:shipping-focus-reason="page.shippingFocusReason"
|
||||
@@ -183,10 +230,63 @@ watch(() => page.currentAgentId, () => {
|
||||
@add-remote-url="page.addRemoteUrlAttachment"
|
||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
||||
@maintenance-ledger-config="maintenancePanel = 'ledger'"
|
||||
@maintenance-create-record="maintenancePanel = 'record'"
|
||||
@clear-shipping-focus="page.clearShippingFocus"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<aside
|
||||
v-if="isMaintenanceAgentPage && maintenancePanel"
|
||||
class="relative flex flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.06)]"
|
||||
:class="[
|
||||
isMaintenancePanelFullscreen ? 'absolute inset-y-0 right-0 z-30' : '',
|
||||
isMaintenancePanelResizing ? 'select-none' : '',
|
||||
]"
|
||||
:style="maintenancePanelStyle"
|
||||
>
|
||||
<button
|
||||
v-if="!isMaintenancePanelFullscreen"
|
||||
type="button"
|
||||
class="absolute inset-y-0 left-[-4px] z-10 w-2 cursor-col-resize bg-transparent hover:bg-brand-200/60"
|
||||
:title="$t('maintenance.panel.resizeTitle')"
|
||||
@mousedown="startMaintenancePanelResize"
|
||||
/>
|
||||
<div class="flex items-start justify-between gap-3 border-b border-default px-4 py-3">
|
||||
<div>
|
||||
<h2 class="text-base font-semibold text-primary">
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerTitle') : $t('maintenance.panel.recordTitle') }}
|
||||
</h2>
|
||||
<p class="mt-1 text-xs text-secondary">
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerSubtitle') : $t('maintenance.panel.recordSubtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-secondary hover:bg-surface-soft"
|
||||
:title="isMaintenancePanelFullscreen ? $t('maintenance.panel.exitFullscreen') : $t('maintenance.panel.fullscreen')"
|
||||
@click="isMaintenancePanelFullscreen = !isMaintenancePanelFullscreen"
|
||||
>
|
||||
<Minimize2 v-if="isMaintenancePanelFullscreen" class="h-4 w-4" />
|
||||
<Maximize2 v-else class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-sm text-secondary hover:bg-surface-soft"
|
||||
:title="$t('maintenance.panel.close')"
|
||||
@click="maintenancePanel = null"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||
<LedgerConfigPanel v-if="maintenancePanel === 'ledger'" />
|
||||
<MaintenanceRecordManagerPanel v-else />
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<ChatBrowserPanel
|
||||
v-model:open="page.browserPanelOpen"
|
||||
v-model:draft-url="page.browserDraftUrl"
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
||||
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
||||
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
|
||||
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
|
||||
@@ -603,6 +604,10 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:action-button-class="handlers.shippingActionButtonClass"
|
||||
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
|
||||
/>
|
||||
<MaintenanceDeviceResultCard
|
||||
v-else-if="message.type === 'maintenance-device-result'"
|
||||
:message="message"
|
||||
/>
|
||||
<TrainingExamQuestionMessage
|
||||
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
|
||||
:question="trainingHandlers.getQuestion()!"
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* features/chat/components/messages/MaintenanceDeviceResultCard.vue
|
||||
* 用途:设备维保助手会话中的设备台账查询结果卡片。
|
||||
* 依赖:chat.types、ledger/record 类型、vue-i18n。
|
||||
* 逻辑:后端返回 maintenance-device-result payload 后,本组件按原型展示设备基础信息、匹配状态和快捷操作。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ChatMessage } from '../../types/chat.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
interface MaintenanceDeviceResultPayload {
|
||||
matched?: boolean;
|
||||
device?: MaintenanceDevice;
|
||||
records?: MaintenanceRecord[];
|
||||
actions?: Array<{ id: string; label: string }>;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
message: ChatMessage;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
|
||||
const raw = props.message.payload;
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return raw as MaintenanceDeviceResultPayload;
|
||||
});
|
||||
|
||||
const device = computed(() => payload.value?.device || null);
|
||||
const records = computed(() => payload.value?.records || []);
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
const status = device.value?.deviceStatus;
|
||||
if (status === 'in_use') return t('maintenance.ledger.status.inUse');
|
||||
if (status === 'disabled') return t('maintenance.ledger.status.disabled');
|
||||
if (status === 'scrapped') return t('maintenance.ledger.status.scrapped');
|
||||
if (status === 'sold') return t('maintenance.ledger.status.sold');
|
||||
return status || '-';
|
||||
});
|
||||
|
||||
const rows = computed(() => {
|
||||
const item = device.value;
|
||||
if (!item) return [];
|
||||
return [
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.deviceCode'), value: item.deviceCode },
|
||||
{ label: t('maintenance.ledger.fields.deviceName'), value: item.deviceName },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.modelSpec'), value: item.modelSpec },
|
||||
{ label: t('maintenance.ledger.fields.department'), value: item.department },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.devicePosition'), value: item.installLocation },
|
||||
{ label: t('maintenance.ledger.fields.deviceStatus'), value: statusLabel.value },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.manufacturer'), value: item.manufacturer },
|
||||
{ label: t('maintenance.ledger.fields.startDate'), value: item.startDate },
|
||||
],
|
||||
];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="device" class="mt-3 rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-800 shadow-sm">
|
||||
<div class="flex items-center justify-between gap-3 rounded-t-lg border border-slate-200 bg-slate-50 px-3 py-2">
|
||||
<h3 class="font-semibold">{{ t('maintenance.chat.deviceLedgerInfo') }}</h3>
|
||||
<span class="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-semibold text-emerald-700">
|
||||
{{ t('maintenance.chat.matched') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="overflow-hidden border-x border-b border-slate-200">
|
||||
<table class="w-full table-fixed text-sm">
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in rows" :key="rowIndex" class="border-t border-slate-200 first:border-t-0">
|
||||
<template v-for="cell in row" :key="cell.label">
|
||||
<th class="w-[16%] bg-slate-100 px-3 py-2 text-left font-semibold text-slate-700">{{ cell.label }}</th>
|
||||
<td class="w-[34%] px-3 py-2 text-slate-800">{{ cell.value || '-' }}</td>
|
||||
</template>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="records.length" class="mt-3 overflow-hidden rounded-lg border border-slate-200">
|
||||
<div class="bg-slate-50 px-3 py-2 text-xs font-semibold text-slate-600">
|
||||
{{ t('maintenance.chat.recentRecords', { count: records.length }) }}
|
||||
</div>
|
||||
<table class="w-full text-left text-xs">
|
||||
<thead class="bg-slate-50 text-slate-500">
|
||||
<tr>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.reportDate') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.faultDescription') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairer') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="record in records.slice(0, 3)" :key="record.id" class="border-t border-slate-200">
|
||||
<td class="px-3 py-2">{{ record.reportDate || '-' }}</td>
|
||||
<td class="max-w-[260px] truncate px-3 py-2">{{ record.faultDescription || '-' }}</td>
|
||||
<td class="px-3 py-2">{{ record.repairer || '-' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white">
|
||||
{{ t('maintenance.chat.viewRepairHistory') }}
|
||||
</button>
|
||||
<button type="button" class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700">
|
||||
{{ t('maintenance.chat.addRepairRecord') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -21,7 +21,7 @@ export interface RetrieverResource {
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result';
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
|
||||
retriever_resources?: RetrieverResource[];
|
||||
attribution_parts?: string[];
|
||||
chat_log_id?: number;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* features/maintenance/api/maintenanceLedger.api.ts
|
||||
* 用途:设备维保台账配置 HTTP API 封装。
|
||||
* 依赖:shared/api/client、shared/utils/auth、ledger.types。
|
||||
* 逻辑:右侧固定面板通过本模块加载列表、保存设备、下载模板和导入 Excel。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
MaintenanceDevice,
|
||||
MaintenanceDeviceImportResult,
|
||||
MaintenanceDeviceListResult,
|
||||
MaintenanceDevicePayload,
|
||||
} from '@/features/maintenance/types/ledger.types';
|
||||
|
||||
const API_BASE = '/api/maintenance/ledger';
|
||||
|
||||
export interface ListMaintenanceDevicesParams {
|
||||
keyword?: string;
|
||||
status?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
const jsonHeaders = () => ({
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
|
||||
export const listMaintenanceDevices = (params: ListMaintenanceDevicesParams = {}) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params.keyword) sp.set('keyword', params.keyword);
|
||||
if (params.status) sp.set('status', params.status);
|
||||
if (params.page) sp.set('page', String(params.page));
|
||||
if (params.pageSize) sp.set('page_size', String(params.pageSize));
|
||||
const qs = sp.toString();
|
||||
return requestJson<MaintenanceDeviceListResult>(`${API_BASE}/devices${qs ? `?${qs}` : ''}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
};
|
||||
|
||||
export const getMaintenanceDevice = (id: number) => {
|
||||
return requestJson<MaintenanceDevice>(`${API_BASE}/devices/${id}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
};
|
||||
|
||||
export const createMaintenanceDevice = (payload: MaintenanceDevicePayload) => {
|
||||
return requestJson<MaintenanceDevice>(`${API_BASE}/devices`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
};
|
||||
|
||||
export const updateMaintenanceDevice = (id: number, payload: MaintenanceDevicePayload) => {
|
||||
return requestJson<MaintenanceDevice>(`${API_BASE}/devices/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
};
|
||||
|
||||
export const maintenanceLedgerImportTemplateUrl = `${API_BASE}/import-template`;
|
||||
|
||||
export const importMaintenanceDevices = (file: File) => {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return requestJson<MaintenanceDeviceImportResult>(`${API_BASE}/import`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: form,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* features/maintenance/api/maintenanceRecord.api.ts
|
||||
* 用途:设备维修记录 HTTP API 封装。
|
||||
* 依赖:shared/api/client、shared/utils/auth、record.types。
|
||||
* 逻辑:右侧固定面板通过本模块新增记录和查询最近记录;会话查询也可复用同一后端接口。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
MaintenanceRecord,
|
||||
MaintenanceRecordListResult,
|
||||
MaintenanceRecordPayload,
|
||||
} from '@/features/maintenance/types/record.types';
|
||||
|
||||
const API_BASE = '/api/maintenance/records';
|
||||
|
||||
export interface ListMaintenanceRecordsParams {
|
||||
keyword?: string;
|
||||
deviceCode?: string;
|
||||
status?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
const jsonHeaders = () => ({
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
|
||||
export const listMaintenanceRecords = (params: ListMaintenanceRecordsParams = {}) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params.keyword) sp.set('keyword', params.keyword);
|
||||
if (params.deviceCode) sp.set('deviceCode', params.deviceCode);
|
||||
if (params.status) sp.set('status', params.status);
|
||||
if (params.page) sp.set('page', String(params.page));
|
||||
if (params.pageSize) sp.set('page_size', String(params.pageSize));
|
||||
const qs = sp.toString();
|
||||
return requestJson<MaintenanceRecordListResult>(`${API_BASE}${qs ? `?${qs}` : ''}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
};
|
||||
|
||||
export const getMaintenanceRecord = (id: number) => {
|
||||
return requestJson<MaintenanceRecord>(`${API_BASE}/${id}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
};
|
||||
|
||||
export const createMaintenanceRecord = (payload: MaintenanceRecordPayload) => {
|
||||
return requestJson<MaintenanceRecord>(API_BASE, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
};
|
||||
|
||||
export const updateMaintenanceRecord = (id: number, payload: MaintenanceRecordPayload) => {
|
||||
return requestJson<MaintenanceRecord>(`${API_BASE}/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteMaintenanceRecord = (id: number) => {
|
||||
return requestJson<{ deleted: boolean; id: number }>(`${API_BASE}/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
};
|
||||
|
||||
export const exportMaintenanceRecords = async (params: ListMaintenanceRecordsParams = {}) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params.keyword) sp.set('keyword', params.keyword);
|
||||
if (params.deviceCode) sp.set('deviceCode', params.deviceCode);
|
||||
if (params.status) sp.set('status', params.status);
|
||||
const qs = sp.toString();
|
||||
const response = await fetch(`${API_BASE}/export${qs ? `?${qs}` : ''}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
return response.blob();
|
||||
};
|
||||
@@ -0,0 +1,459 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/maintenance/components/LedgerConfigPanel.vue
|
||||
* 用途:设备维保助手右侧固定面板中的“台账配置”页面,包含设备列表与设备配置两个 Tab。
|
||||
* 依赖:maintenanceLedger.api、PaginationBar、useMessage。
|
||||
* 逻辑:列表 Tab 负责查询/导入/选择设备;配置 Tab 负责新增或编辑设备台账,保存后刷新列表。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
createMaintenanceDevice,
|
||||
importMaintenanceDevices,
|
||||
listMaintenanceDevices,
|
||||
maintenanceLedgerImportTemplateUrl,
|
||||
updateMaintenanceDevice,
|
||||
} from '@/features/maintenance/api/maintenanceLedger.api';
|
||||
import type {
|
||||
MaintenanceDevice,
|
||||
MaintenanceDeviceImportResult,
|
||||
MaintenanceDevicePayload,
|
||||
MaintenanceDeviceStatus,
|
||||
} from '@/features/maintenance/types/ledger.types';
|
||||
|
||||
type TabName = 'list' | 'form';
|
||||
|
||||
const msg = useMessage();
|
||||
const { t } = useI18n();
|
||||
const activeTab = ref<TabName>('list');
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const importing = ref(false);
|
||||
const devices = ref<MaintenanceDevice[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(10);
|
||||
const keyword = ref('');
|
||||
const status = ref('');
|
||||
const editingId = ref<number | null>(null);
|
||||
const importResult = ref<MaintenanceDeviceImportResult | null>(null);
|
||||
const MAX_IMPORT_FILE_SIZE = 10 * 1024 * 1024;
|
||||
const DEFAULT_ACCOUNT_SET = '和信';
|
||||
const accountSetOptions = ['和信', '科技', '电子', '和宏智'];
|
||||
|
||||
const form = reactive<MaintenanceDevicePayload>({
|
||||
deviceCode: '',
|
||||
deviceName: '',
|
||||
modelSpec: '',
|
||||
department: '',
|
||||
installLocation: '',
|
||||
deviceStatus: 'in_use',
|
||||
manufacturer: '',
|
||||
entryDate: '',
|
||||
productionDate: '',
|
||||
startDate: '',
|
||||
responsibleUser: '',
|
||||
maintenanceCycle: '',
|
||||
originalValue: '',
|
||||
residualValue: '',
|
||||
accountSet: DEFAULT_ACCOUNT_SET,
|
||||
remark: '',
|
||||
});
|
||||
|
||||
const statusOptions: Array<{ value: MaintenanceDeviceStatus | ''; label: string }> = [
|
||||
{ value: '', label: 'maintenance.ledger.status.all' },
|
||||
{ value: 'in_use', label: 'maintenance.ledger.status.inUse' },
|
||||
{ value: 'disabled', label: 'maintenance.ledger.status.disabled' },
|
||||
{ value: 'scrapped', label: 'maintenance.ledger.status.scrapped' },
|
||||
{ value: 'sold', label: 'maintenance.ledger.status.sold' },
|
||||
];
|
||||
|
||||
const formTitle = computed(() => t(editingId.value ? 'maintenance.ledger.formTitle.edit' : 'maintenance.ledger.formTitle.create'));
|
||||
|
||||
/**
|
||||
* 将后端状态值转换为中文展示。
|
||||
* @param value - 设备状态值。
|
||||
* @returns 中文状态。
|
||||
*/
|
||||
const formatStatus = (value: string): string => {
|
||||
const item = statusOptions.find((option) => option.value === value);
|
||||
return item?.label ? t(item.label) : value || '-';
|
||||
};
|
||||
|
||||
/**
|
||||
* 从表单状态生成 API payload,集中裁剪字符串。
|
||||
* @returns 设备保存入参。
|
||||
*/
|
||||
const buildPayload = (): MaintenanceDevicePayload => ({
|
||||
deviceCode: form.deviceCode.trim(),
|
||||
deviceName: form.deviceName.trim(),
|
||||
modelSpec: form.modelSpec?.trim(),
|
||||
department: form.department?.trim(),
|
||||
installLocation: form.installLocation?.trim(),
|
||||
deviceStatus: form.deviceStatus,
|
||||
manufacturer: form.manufacturer?.trim(),
|
||||
entryDate: form.entryDate || undefined,
|
||||
productionDate: form.productionDate || undefined,
|
||||
startDate: form.startDate || undefined,
|
||||
responsibleUser: form.responsibleUser?.trim(),
|
||||
maintenanceCycle: form.maintenanceCycle?.trim(),
|
||||
originalValue: form.originalValue?.trim(),
|
||||
residualValue: form.residualValue?.trim(),
|
||||
accountSet: form.accountSet?.trim(),
|
||||
remark: form.remark?.trim(),
|
||||
});
|
||||
|
||||
/**
|
||||
* 加载设备台账分页列表。
|
||||
* 核心逻辑:根据当前 keyword/status/page/pageSize 调用后端,刷新列表 Tab。
|
||||
*/
|
||||
const loadDevices = async (): Promise<void> => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await listMaintenanceDevices({
|
||||
keyword: keyword.value.trim(),
|
||||
status: status.value,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
});
|
||||
devices.value = result.items;
|
||||
total.value = result.total;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.ledger.messages.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 重置表单并切换到新增模式。
|
||||
*/
|
||||
const startCreate = (): void => {
|
||||
editingId.value = null;
|
||||
Object.assign(form, {
|
||||
deviceCode: '',
|
||||
deviceName: '',
|
||||
modelSpec: '',
|
||||
department: '',
|
||||
installLocation: '',
|
||||
deviceStatus: 'in_use',
|
||||
manufacturer: '',
|
||||
entryDate: '',
|
||||
productionDate: '',
|
||||
startDate: '',
|
||||
responsibleUser: '',
|
||||
maintenanceCycle: '',
|
||||
originalValue: '',
|
||||
residualValue: '',
|
||||
accountSet: DEFAULT_ACCOUNT_SET,
|
||||
remark: '',
|
||||
});
|
||||
activeTab.value = 'form';
|
||||
};
|
||||
|
||||
/**
|
||||
* 将选中设备带入表单并切换到配置 Tab。
|
||||
* @param device - 列表中选中的设备。
|
||||
*/
|
||||
const startEdit = (device: MaintenanceDevice): void => {
|
||||
editingId.value = device.id;
|
||||
Object.assign(form, {
|
||||
deviceCode: device.deviceCode || '',
|
||||
deviceName: device.deviceName || '',
|
||||
modelSpec: device.modelSpec || '',
|
||||
department: device.department || '',
|
||||
installLocation: device.installLocation || '',
|
||||
deviceStatus: device.deviceStatus,
|
||||
manufacturer: device.manufacturer || '',
|
||||
entryDate: device.entryDate || '',
|
||||
productionDate: device.productionDate || '',
|
||||
startDate: device.startDate || '',
|
||||
responsibleUser: device.responsibleUser || '',
|
||||
maintenanceCycle: device.maintenanceCycle || '',
|
||||
originalValue: device.originalValue != null ? String(device.originalValue) : '',
|
||||
residualValue: device.residualValue != null ? String(device.residualValue) : '',
|
||||
accountSet: device.accountSet || '',
|
||||
remark: device.remark || '',
|
||||
});
|
||||
activeTab.value = 'form';
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存设备台账配置。
|
||||
* 核心逻辑:新增/编辑共用同一表单;保存成功后刷新列表并回到设备列表 Tab。
|
||||
*/
|
||||
const saveDevice = async (): Promise<void> => {
|
||||
const payload = buildPayload();
|
||||
if (!payload.deviceCode || !payload.deviceName) {
|
||||
msg.warning(t('maintenance.ledger.messages.required'));
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
if (editingId.value) {
|
||||
await updateMaintenanceDevice(editingId.value, payload);
|
||||
} else {
|
||||
await createMaintenanceDevice(payload);
|
||||
}
|
||||
msg.success(t('maintenance.ledger.messages.saved'));
|
||||
activeTab.value = 'list';
|
||||
await loadDevices();
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.ledger.messages.saveFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验设备台账导入文件,避免明显不符合要求的文件进入后端解析。
|
||||
* @param file - 用户选择的 Excel 文件。
|
||||
* @returns 校验是否通过。
|
||||
*/
|
||||
const validateImportFile = (file: File): boolean => {
|
||||
const fileName = file.name.toLowerCase();
|
||||
if (!fileName.endsWith('.xlsx')) {
|
||||
msg.warning(t('maintenance.ledger.messages.invalidFormat'));
|
||||
return false;
|
||||
}
|
||||
if (file.size > MAX_IMPORT_FILE_SIZE) {
|
||||
msg.warning(t('maintenance.ledger.messages.fileTooLarge'));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 上传 Excel 模板并导入设备台账。
|
||||
* @param event - 文件选择事件。
|
||||
*/
|
||||
const onImportFileChange = async (event: Event): Promise<void> => {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = '';
|
||||
if (!file) return;
|
||||
if (!validateImportFile(file)) return;
|
||||
importing.value = true;
|
||||
try {
|
||||
importResult.value = await importMaintenanceDevices(file);
|
||||
msg.success(t('maintenance.ledger.messages.importDone'));
|
||||
await loadDevices();
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.ledger.messages.importFailed'));
|
||||
} finally {
|
||||
importing.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(loadDevices);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex h-full min-h-0 flex-col">
|
||||
<div class="mb-4 rounded-xl border border-sky-200 bg-sky-50 px-3 py-2 text-sm text-sky-800">
|
||||
{{ t('maintenance.ledger.notice') }}
|
||||
</div>
|
||||
|
||||
<div class="mb-4 flex rounded-xl border border-default bg-muted/30 p-1">
|
||||
<button
|
||||
type="button"
|
||||
class="relative flex-1 cursor-pointer rounded-lg border px-3 py-2 text-sm font-semibold transition-all hover:bg-surface hover:text-brand"
|
||||
:class="activeTab === 'list' ? 'border-brand-300 bg-surface text-brand shadow-sm after:absolute after:inset-x-6 after:bottom-0 after:h-0.5 after:rounded-full after:bg-brand' : 'border-transparent text-secondary'"
|
||||
:aria-selected="activeTab === 'list'"
|
||||
@click="activeTab = 'list'"
|
||||
>
|
||||
{{ t('maintenance.ledger.tabs.list') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="relative flex-1 cursor-pointer rounded-lg border px-3 py-2 text-sm font-semibold transition-all hover:bg-surface hover:text-brand"
|
||||
:class="activeTab === 'form' ? 'border-brand-300 bg-surface text-brand shadow-sm after:absolute after:inset-x-6 after:bottom-0 after:h-0.5 after:rounded-full after:bg-brand' : 'border-transparent text-secondary'"
|
||||
:aria-selected="activeTab === 'form'"
|
||||
@click="activeTab = 'form'"
|
||||
>
|
||||
{{ t('maintenance.ledger.tabs.form') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="activeTab === 'list'" class="flex min-h-0 flex-1 flex-col gap-4">
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<input
|
||||
v-model="keyword"
|
||||
class="admin-table-filter-input w-full md:w-[360px] lg:w-[420px]"
|
||||
:placeholder="t('maintenance.ledger.filters.keywordPlaceholder')"
|
||||
@keyup.enter="page = 1; loadDevices()"
|
||||
/>
|
||||
<select v-model="status" class="admin-table-filter-input w-full md:w-[150px]" @change="page = 1; loadDevices()">
|
||||
<option v-for="item in statusOptions" :key="item.value || 'all'" :value="item.value">
|
||||
{{ t(item.label) }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="button" class="admin-report-page-btn admin-report-page-btn--active" @click="page = 1; loadDevices()">
|
||||
{{ t('maintenance.ledger.actions.search') }}
|
||||
</button>
|
||||
<button type="button" class="admin-report-page-btn" @click="startCreate">
|
||||
{{ t('maintenance.ledger.actions.create') }}
|
||||
</button>
|
||||
<a class="admin-report-page-btn" :href="maintenanceLedgerImportTemplateUrl" target="_blank">
|
||||
{{ t('maintenance.ledger.actions.downloadTemplate') }}
|
||||
</a>
|
||||
<label class="admin-report-page-btn cursor-pointer">
|
||||
{{ importing ? t('maintenance.ledger.actions.importing') : t('maintenance.ledger.actions.importExcel') }}
|
||||
<input type="file" class="hidden" accept=".xlsx" :disabled="importing" @change="onImportFileChange" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div v-if="importResult" class="rounded-xl border border-default bg-surface px-3 py-2 text-sm">
|
||||
{{ t('maintenance.ledger.importResult', importResult) }}
|
||||
<div v-if="importResult.errors.length" class="mt-2 text-danger">
|
||||
<div v-for="err in importResult.errors.slice(0, 5)" :key="`${err.row}-${err.message}`">
|
||||
{{ t('maintenance.ledger.importErrorRow', err) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 overflow-auto rounded-xl border border-default bg-surface">
|
||||
<table class="min-w-full text-left text-sm">
|
||||
<thead class="bg-muted/50 text-secondary">
|
||||
<tr>
|
||||
<th class="px-3 py-2">{{ t('maintenance.ledger.table.deviceCode') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.ledger.table.deviceName') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.ledger.table.modelSpec') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.ledger.table.manufacturer') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.ledger.table.status') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.ledger.table.operation') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="6" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.ledger.table.loading') }}</td>
|
||||
</tr>
|
||||
<tr v-else-if="!devices.length">
|
||||
<td colspan="6" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.ledger.table.empty') }}</td>
|
||||
</tr>
|
||||
<tr v-for="device in devices" v-else :key="device.id" class="border-t border-default">
|
||||
<td class="px-3 py-2 font-semibold">{{ device.deviceCode }}</td>
|
||||
<td class="px-3 py-2">{{ device.deviceName }}</td>
|
||||
<td class="px-3 py-2">{{ device.modelSpec || '-' }}</td>
|
||||
<td class="px-3 py-2">{{ device.manufacturer || '-' }}</td>
|
||||
<td class="px-3 py-2">{{ formatStatus(device.deviceStatus) }}</td>
|
||||
<td class="px-3 py-2">
|
||||
<button type="button" class="admin-report-page-btn" @click="startEdit(device)">
|
||||
{{ t('maintenance.ledger.actions.edit') }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<PaginationBar
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="total"
|
||||
@update:page="loadDevices"
|
||||
@update:page-size="loadDevices"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else class="min-h-0 flex-1 overflow-auto">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h3 class="text-base font-semibold text-primary">{{ formTitle }}</h3>
|
||||
<button type="button" class="admin-report-page-btn" @click="activeTab = 'list'">{{ t('maintenance.ledger.actions.backToList') }}</button>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.deviceCode') }} *
|
||||
<input v-model="form.deviceCode" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.deviceName') }} *
|
||||
<input v-model="form.deviceName" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.modelSpec') }}
|
||||
<input v-model="form.modelSpec" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.manufacturer') }}
|
||||
<input v-model="form.manufacturer" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.devicePosition') }}
|
||||
<input v-model="form.installLocation" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.deviceStatus') }}
|
||||
<select v-model="form.deviceStatus" class="admin-table-filter-input">
|
||||
<option value="in_use">{{ t('maintenance.ledger.status.inUse') }}</option>
|
||||
<option value="disabled">{{ t('maintenance.ledger.status.disabled') }}</option>
|
||||
<option value="scrapped">{{ t('maintenance.ledger.status.scrapped') }}</option>
|
||||
<option value="sold">{{ t('maintenance.ledger.status.sold') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.department') }}
|
||||
<input v-model="form.department" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.responsibleUser') }}
|
||||
<input v-model="form.responsibleUser" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.productionDate') }}
|
||||
<input v-model="form.productionDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.entryDate') }}
|
||||
<input v-model="form.entryDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.startDate') }}
|
||||
<input v-model="form.startDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.maintenanceCycle') }}
|
||||
<input v-model="form.maintenanceCycle" class="admin-table-filter-input" :placeholder="t('maintenance.ledger.placeholder.maintenanceCycle')" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.originalValue') }}
|
||||
<input v-model="form.originalValue" type="number" min="0" step="0.01" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.residualValue') }}
|
||||
<input v-model="form.residualValue" type="number" min="0" step="0.01" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.ledger.fields.accountSet') }}
|
||||
<select v-model="form.accountSet" class="admin-table-filter-input">
|
||||
<option v-for="item in accountSetOptions" :key="item" :value="item">
|
||||
{{ item }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
|
||||
{{ t('maintenance.ledger.fields.remark') }}
|
||||
<textarea v-model="form.remark" class="admin-table-filter-input min-h-24" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<button type="button" class="admin-report-page-btn" @click="activeTab = 'list'">{{ t('maintenance.ledger.actions.cancel') }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="admin-report-page-btn admin-report-page-btn--active"
|
||||
:disabled="saving"
|
||||
@click="saveDevice"
|
||||
>
|
||||
{{ saving ? t('maintenance.ledger.actions.saving') : t('maintenance.ledger.actions.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,484 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/maintenance/components/MaintenanceRecordManagerPanel.vue
|
||||
* 用途:设备维保助手右侧固定面板中的维修记录管理页,覆盖查询、新增、编辑和删除。
|
||||
* 依赖:maintenanceRecord.api、maintenanceLedger.api、PaginationBar、useMessage。
|
||||
* 逻辑:列表 Tab 按设备编号/名称和维修状态筛选;配置 Tab 复用同一表单新增或修改记录。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
|
||||
import {
|
||||
createMaintenanceRecord,
|
||||
deleteMaintenanceRecord,
|
||||
exportMaintenanceRecords,
|
||||
listMaintenanceRecords,
|
||||
updateMaintenanceRecord,
|
||||
} from '@/features/maintenance/api/maintenanceRecord.api';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type {
|
||||
MaintenanceRecord,
|
||||
MaintenanceRecordPayload,
|
||||
MaintenanceRepairStatus,
|
||||
} from '@/features/maintenance/types/record.types';
|
||||
|
||||
type TabName = 'list' | 'form';
|
||||
|
||||
const msg = useMessage();
|
||||
const { t } = useI18n();
|
||||
const activeTab = ref<TabName>('list');
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const deviceLoading = ref(false);
|
||||
const deletingId = ref<number | null>(null);
|
||||
const exporting = ref(false);
|
||||
const records = ref<MaintenanceRecord[]>([]);
|
||||
const matchedDevice = ref<MaintenanceDevice | null>(null);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(10);
|
||||
const keyword = ref('');
|
||||
const status = ref('');
|
||||
const editingId = ref<number | null>(null);
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
|
||||
const form = reactive<MaintenanceRecordPayload>({
|
||||
deviceCode: '',
|
||||
reportDate: today,
|
||||
repairCategory: '',
|
||||
faultDescription: '',
|
||||
reporter: '',
|
||||
approver: '',
|
||||
repairStatus: 'pending',
|
||||
repairDate: '',
|
||||
repairUnit: '',
|
||||
repairer: '',
|
||||
repairCost: '',
|
||||
repairHours: '',
|
||||
repairDescription: '',
|
||||
sourceOrderNo: '',
|
||||
});
|
||||
|
||||
const statusOptions: Array<{ value: MaintenanceRepairStatus | ''; label: string }> = [
|
||||
{ value: '', label: 'maintenance.record.status.all' },
|
||||
{ value: 'pending', label: 'maintenance.record.status.pending' },
|
||||
{ value: 'processing', label: 'maintenance.record.status.processing' },
|
||||
{ value: 'done', label: 'maintenance.record.status.done' },
|
||||
{ value: 'cancelled', label: 'maintenance.record.status.cancelled' },
|
||||
];
|
||||
|
||||
const formTitle = computed(() => t(editingId.value ? 'maintenance.record.formTitle.edit' : 'maintenance.record.formTitle.create'));
|
||||
|
||||
/**
|
||||
* 将维修状态枚举转为中文展示。
|
||||
* @param value - 后端状态枚举。
|
||||
* @returns 中文状态文案。
|
||||
*/
|
||||
const formatStatus = (value: string): string => {
|
||||
const option = statusOptions.find((item) => item.value === value);
|
||||
return option ? t(option.label) : value || '-';
|
||||
};
|
||||
|
||||
/**
|
||||
* 从表单生成保存 payload,统一裁剪字符串并保留可空日期。
|
||||
* @returns 保存维修记录入参。
|
||||
*/
|
||||
const buildPayload = (): MaintenanceRecordPayload => ({
|
||||
deviceCode: form.deviceCode.trim(),
|
||||
reportDate: form.reportDate,
|
||||
repairCategory: form.repairCategory?.trim(),
|
||||
faultDescription: form.faultDescription.trim(),
|
||||
reporter: form.reporter?.trim(),
|
||||
approver: form.approver?.trim(),
|
||||
repairStatus: form.repairStatus,
|
||||
repairDate: form.repairDate || undefined,
|
||||
repairUnit: form.repairUnit?.trim(),
|
||||
repairer: form.repairer?.trim(),
|
||||
repairCost: form.repairCost?.trim(),
|
||||
repairHours: form.repairHours?.trim(),
|
||||
repairDescription: form.repairDescription?.trim(),
|
||||
sourceOrderNo: form.sourceOrderNo?.trim(),
|
||||
});
|
||||
|
||||
/**
|
||||
* 查询维修记录列表,仅按设备编号/设备名称和状态筛选。
|
||||
*/
|
||||
const loadRecords = async (): Promise<void> => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const result = await listMaintenanceRecords({
|
||||
keyword: keyword.value.trim(),
|
||||
status: status.value,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
});
|
||||
records.value = result.items;
|
||||
total.value = result.total;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 导出当前筛选条件下的维修记录 Excel。
|
||||
*/
|
||||
const exportRecords = async (): Promise<void> => {
|
||||
exporting.value = true;
|
||||
try {
|
||||
const blob = await exportMaintenanceRecords({
|
||||
keyword: keyword.value.trim(),
|
||||
status: status.value,
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `maintenance_records_${new Date().toISOString().slice(0, 10)}.xlsx`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
msg.success(t('maintenance.record.messages.exported'));
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.exportFailed'));
|
||||
} finally {
|
||||
exporting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 查询设备台账快照,帮助管理员确认维修记录归属。
|
||||
*/
|
||||
const loadDeviceSnapshot = async (): Promise<void> => {
|
||||
const code = form.deviceCode.trim();
|
||||
matchedDevice.value = null;
|
||||
if (!code) return;
|
||||
deviceLoading.value = true;
|
||||
try {
|
||||
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
|
||||
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || result.items[0] || null;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.deviceLoadFailed'));
|
||||
} finally {
|
||||
deviceLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 重置表单并进入新增模式。
|
||||
*/
|
||||
const startCreate = (): void => {
|
||||
editingId.value = null;
|
||||
Object.assign(form, {
|
||||
deviceCode: '',
|
||||
reportDate: today,
|
||||
repairCategory: '',
|
||||
faultDescription: '',
|
||||
reporter: '',
|
||||
approver: '',
|
||||
repairStatus: 'pending',
|
||||
repairDate: '',
|
||||
repairUnit: '',
|
||||
repairer: '',
|
||||
repairCost: '',
|
||||
repairHours: '',
|
||||
repairDescription: '',
|
||||
sourceOrderNo: '',
|
||||
});
|
||||
matchedDevice.value = null;
|
||||
activeTab.value = 'form';
|
||||
};
|
||||
|
||||
/**
|
||||
* 将选中的维修记录带入表单并进入编辑模式。
|
||||
* @param record - 列表中选中的维修记录。
|
||||
*/
|
||||
const startEdit = (record: MaintenanceRecord): void => {
|
||||
editingId.value = record.id;
|
||||
Object.assign(form, {
|
||||
deviceCode: record.deviceCode || '',
|
||||
reportDate: record.reportDate || today,
|
||||
repairCategory: record.repairCategory || '',
|
||||
faultDescription: record.faultDescription || '',
|
||||
reporter: record.reporter || '',
|
||||
approver: record.approver || '',
|
||||
repairStatus: record.repairStatus,
|
||||
repairDate: record.repairDate || '',
|
||||
repairUnit: record.repairUnit || '',
|
||||
repairer: record.repairer || '',
|
||||
repairCost: record.repairCost || '',
|
||||
repairHours: record.repairHours || '',
|
||||
repairDescription: record.repairDescription || '',
|
||||
sourceOrderNo: record.sourceOrderNo || '',
|
||||
});
|
||||
matchedDevice.value = record.deviceCode
|
||||
? {
|
||||
id: record.deviceId || 0,
|
||||
deviceCode: record.deviceCode,
|
||||
deviceName: record.deviceName || '',
|
||||
modelSpec: record.modelSpec || '',
|
||||
installLocation: record.installLocation || '',
|
||||
deviceStatus: 'in_use',
|
||||
} as MaintenanceDevice
|
||||
: null;
|
||||
activeTab.value = 'form';
|
||||
};
|
||||
|
||||
/**
|
||||
* 新增或更新维修记录,并回到列表刷新结果。
|
||||
*/
|
||||
const saveRecord = async (): Promise<void> => {
|
||||
const payload = buildPayload();
|
||||
if (!payload.deviceCode || !payload.reportDate || !payload.faultDescription) {
|
||||
msg.warning(t('maintenance.record.messages.required'));
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
if (editingId.value) {
|
||||
await updateMaintenanceRecord(editingId.value, payload);
|
||||
msg.success(t('maintenance.record.messages.updated'));
|
||||
} else {
|
||||
await createMaintenanceRecord(payload);
|
||||
msg.success(t('maintenance.record.messages.created'));
|
||||
keyword.value = payload.deviceCode;
|
||||
}
|
||||
activeTab.value = 'list';
|
||||
await loadRecords();
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.saveFailed'));
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除维修记录。
|
||||
* @param record - 待删除的维修记录。
|
||||
*/
|
||||
const removeRecord = async (record: MaintenanceRecord): Promise<void> => {
|
||||
if (!window.confirm(t('maintenance.record.messages.deleteConfirm', { deviceCode: record.deviceCode }))) return;
|
||||
deletingId.value = record.id;
|
||||
try {
|
||||
await deleteMaintenanceRecord(record.id);
|
||||
msg.success(t('maintenance.record.messages.deleted'));
|
||||
await loadRecords();
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.deleteFailed'));
|
||||
} finally {
|
||||
deletingId.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(loadRecords);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex h-full min-h-0 flex-col">
|
||||
<div class="mb-4 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
|
||||
{{ t('maintenance.record.notice') }}
|
||||
</div>
|
||||
|
||||
<div class="mb-4 flex rounded-xl border border-default bg-muted/30 p-1">
|
||||
<button
|
||||
type="button"
|
||||
class="relative flex-1 cursor-pointer rounded-lg border px-3 py-2 text-sm font-semibold transition-all hover:bg-surface hover:text-brand"
|
||||
:class="activeTab === 'list' ? 'border-brand-300 bg-surface text-brand shadow-sm after:absolute after:inset-x-6 after:bottom-0 after:h-0.5 after:rounded-full after:bg-brand' : 'border-transparent text-secondary'"
|
||||
:aria-selected="activeTab === 'list'"
|
||||
@click="activeTab = 'list'"
|
||||
>
|
||||
{{ t('maintenance.record.tabs.list') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="relative flex-1 cursor-pointer rounded-lg border px-3 py-2 text-sm font-semibold transition-all hover:bg-surface hover:text-brand"
|
||||
:class="activeTab === 'form' ? 'border-brand-300 bg-surface text-brand shadow-sm after:absolute after:inset-x-6 after:bottom-0 after:h-0.5 after:rounded-full after:bg-brand' : 'border-transparent text-secondary'"
|
||||
:aria-selected="activeTab === 'form'"
|
||||
@click="activeTab = 'form'"
|
||||
>
|
||||
{{ t('maintenance.record.tabs.form') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="activeTab === 'list'" class="flex min-h-0 flex-1 flex-col gap-4">
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<input
|
||||
v-model="keyword"
|
||||
class="admin-table-filter-input w-full md:w-[360px] lg:w-[420px]"
|
||||
:placeholder="t('maintenance.record.filters.keywordPlaceholder')"
|
||||
@keyup.enter="page = 1; loadRecords()"
|
||||
/>
|
||||
<select v-model="status" class="admin-table-filter-input w-full md:w-[150px]" @change="page = 1; loadRecords()">
|
||||
<option v-for="item in statusOptions" :key="item.value || 'all'" :value="item.value">
|
||||
{{ t(item.label) }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button type="button" class="admin-report-page-btn admin-report-page-btn--active" @click="page = 1; loadRecords()">
|
||||
{{ t('maintenance.record.actions.search') }}
|
||||
</button>
|
||||
<button type="button" class="admin-report-page-btn" @click="startCreate">
|
||||
{{ t('maintenance.record.actions.create') }}
|
||||
</button>
|
||||
<button type="button" class="admin-report-page-btn" :disabled="exporting" @click="exportRecords">
|
||||
{{ exporting ? t('maintenance.record.actions.exporting') : t('maintenance.record.actions.export') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 overflow-auto rounded-xl border border-default bg-surface">
|
||||
<table class="min-w-full text-left text-sm">
|
||||
<thead class="bg-muted/50 text-secondary">
|
||||
<tr>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceCode') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.table.deviceName') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.table.modelSpec') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.table.faultDescription') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.table.status') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.table.repairer') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.table.operation') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="7" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.loading') }}</td>
|
||||
</tr>
|
||||
<tr v-else-if="!records.length">
|
||||
<td colspan="7" class="px-3 py-8 text-center text-secondary">{{ t('maintenance.record.table.empty') }}</td>
|
||||
</tr>
|
||||
<tr v-for="record in records" v-else :key="record.id" class="border-t border-default">
|
||||
<td class="px-3 py-2 font-semibold">{{ record.deviceCode }}</td>
|
||||
<td class="px-3 py-2">{{ record.deviceName || '-' }}</td>
|
||||
<td class="px-3 py-2">{{ record.modelSpec || '-' }}</td>
|
||||
<td class="max-w-[260px] truncate px-3 py-2">{{ record.faultDescription }}</td>
|
||||
<td class="px-3 py-2">{{ formatStatus(record.repairStatus) }}</td>
|
||||
<td class="px-3 py-2">{{ record.repairer || '-' }}</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="flex gap-2">
|
||||
<button type="button" class="admin-report-page-btn" @click="startEdit(record)">{{ t('maintenance.record.actions.edit') }}</button>
|
||||
<button
|
||||
type="button"
|
||||
class="admin-report-page-btn"
|
||||
:disabled="deletingId === record.id"
|
||||
@click="removeRecord(record)"
|
||||
>
|
||||
{{ deletingId === record.id ? t('maintenance.record.actions.deleting') : t('maintenance.record.actions.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<PaginationBar
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="total"
|
||||
@update:page="loadRecords"
|
||||
@update:page-size="loadRecords"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<form v-else class="min-h-0 flex-1 overflow-auto" @submit.prevent="saveRecord">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h3 class="text-base font-semibold text-primary">{{ formTitle }}</h3>
|
||||
<button type="button" class="admin-report-page-btn" @click="activeTab = 'list'">{{ t('maintenance.record.actions.backToList') }}</button>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.deviceCode') }} *
|
||||
<input
|
||||
v-model="form.deviceCode"
|
||||
class="admin-table-filter-input"
|
||||
:placeholder="t('maintenance.record.placeholder.deviceCode')"
|
||||
@blur="loadDeviceSnapshot"
|
||||
@keyup.enter.prevent="loadDeviceSnapshot"
|
||||
/>
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.reportDate') }} *
|
||||
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.repairCategory') }}
|
||||
<input v-model="form.repairCategory" class="admin-table-filter-input" :placeholder="t('maintenance.record.placeholder.repairCategory')" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.repairStatus') }}
|
||||
<select v-model="form.repairStatus" class="admin-table-filter-input">
|
||||
<option value="pending">{{ t('maintenance.record.status.pending') }}</option>
|
||||
<option value="processing">{{ t('maintenance.record.status.processing') }}</option>
|
||||
<option value="done">{{ t('maintenance.record.status.done') }}</option>
|
||||
<option value="cancelled">{{ t('maintenance.record.status.cancelled') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm">
|
||||
<div v-if="deviceLoading" class="text-secondary">{{ t('maintenance.record.deviceSnapshot.loading') }}</div>
|
||||
<div v-else-if="matchedDevice" class="grid gap-1 text-secondary">
|
||||
<div class="font-semibold text-primary">{{ matchedDevice.deviceName }}({{ matchedDevice.deviceCode }})</div>
|
||||
<div>{{ t('maintenance.record.deviceSnapshot.position') }}:{{ matchedDevice.installLocation || '-' }} | {{ t('maintenance.record.deviceSnapshot.department') }}:{{ matchedDevice.department || '-' }}</div>
|
||||
<div>{{ t('maintenance.record.deviceSnapshot.responsibleUser') }}:{{ matchedDevice.responsibleUser || '-' }} | {{ t('maintenance.record.deviceSnapshot.status') }}:{{ matchedDevice.deviceStatus }}</div>
|
||||
</div>
|
||||
<div v-else class="text-secondary">{{ t('maintenance.record.deviceSnapshot.empty') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid gap-4 md:grid-cols-2">
|
||||
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
|
||||
{{ t('maintenance.record.fields.faultDescription') }} *
|
||||
<textarea v-model="form.faultDescription" class="admin-table-filter-input min-h-24" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.reporter') }}
|
||||
<input v-model="form.reporter" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.approver') }}
|
||||
<input v-model="form.approver" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.repairDate') }}
|
||||
<input v-model="form.repairDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.sourceOrderNo') }}
|
||||
<input v-model="form.sourceOrderNo" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.repairUnit') }}
|
||||
<input v-model="form.repairUnit" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.repairer') }}
|
||||
<input v-model="form.repairer" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.repairCost') }}
|
||||
<input v-model="form.repairCost" class="admin-table-filter-input" :placeholder="t('maintenance.record.placeholder.repairCost')" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
{{ t('maintenance.record.fields.repairHours') }}
|
||||
<input v-model="form.repairHours" class="admin-table-filter-input" :placeholder="t('maintenance.record.placeholder.repairHours')" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
|
||||
{{ t('maintenance.record.fields.repairDescription') }}
|
||||
<textarea v-model="form.repairDescription" class="admin-table-filter-input min-h-24" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="sticky bottom-0 mt-5 flex justify-end gap-2 border-t border-default bg-surface py-3">
|
||||
<button type="button" class="admin-report-page-btn" @click="activeTab = 'list'">{{ t('maintenance.record.actions.cancel') }}</button>
|
||||
<button type="submit" class="admin-report-page-btn admin-report-page-btn--active" :disabled="saving">
|
||||
{{ saving ? t('maintenance.record.actions.saving') : t('maintenance.record.actions.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,316 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/maintenance/components/MaintenanceRecordPanel.vue
|
||||
* 用途:设备维保助手右侧固定面板中的“新增维修记录”页面。
|
||||
* 依赖:maintenanceRecord.api、maintenanceLedger.api、useMessage。
|
||||
* 逻辑:管理员通过按钮进入固定面板后填写维修记录;设备编号失焦时查询台账快照,保存后刷新最近记录用于确认。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
|
||||
import {
|
||||
createMaintenanceRecord,
|
||||
listMaintenanceRecords,
|
||||
} from '@/features/maintenance/api/maintenanceRecord.api';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type {
|
||||
MaintenanceRecord,
|
||||
MaintenanceRecordPayload,
|
||||
MaintenanceRepairStatus,
|
||||
} from '@/features/maintenance/types/record.types';
|
||||
|
||||
const msg = useMessage();
|
||||
const saving = ref(false);
|
||||
const deviceLoading = ref(false);
|
||||
const recentLoading = ref(false);
|
||||
const matchedDevice = ref<MaintenanceDevice | null>(null);
|
||||
const recentRecords = ref<MaintenanceRecord[]>([]);
|
||||
const recordKeyword = ref('');
|
||||
const recordStatus = ref('');
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
|
||||
const form = reactive<MaintenanceRecordPayload>({
|
||||
deviceCode: '',
|
||||
reportDate: today,
|
||||
repairCategory: '',
|
||||
faultDescription: '',
|
||||
reporter: '',
|
||||
approver: '',
|
||||
repairStatus: 'pending',
|
||||
repairDate: '',
|
||||
repairUnit: '',
|
||||
repairer: '',
|
||||
repairCost: '',
|
||||
repairHours: '',
|
||||
repairDescription: '',
|
||||
sourceOrderNo: '',
|
||||
});
|
||||
|
||||
const statusOptions: Array<{ value: MaintenanceRepairStatus | ''; label: string }> = [
|
||||
{ value: '', label: '全部状态' },
|
||||
{ value: 'pending', label: '待维修' },
|
||||
{ value: 'processing', label: '维修中' },
|
||||
{ value: 'done', label: '已完成' },
|
||||
{ value: 'cancelled', label: '已取消' },
|
||||
];
|
||||
|
||||
const selectedStatusLabel = computed(() => {
|
||||
return statusOptions.find((item) => item.value === form.repairStatus)?.label || form.repairStatus;
|
||||
});
|
||||
|
||||
/**
|
||||
* 将状态值转换为中文展示。
|
||||
* @param value - 后端状态枚举。
|
||||
* @returns 页面展示文案。
|
||||
*/
|
||||
const formatStatus = (value: string): string => {
|
||||
return statusOptions.find((item) => item.value === value)?.label || value || '-';
|
||||
};
|
||||
|
||||
/**
|
||||
* 从表单状态生成新增维修记录 payload,统一处理空字符串。
|
||||
* @returns 新增维修记录入参。
|
||||
*/
|
||||
const buildPayload = (): MaintenanceRecordPayload => ({
|
||||
deviceCode: form.deviceCode.trim(),
|
||||
reportDate: form.reportDate,
|
||||
repairCategory: form.repairCategory?.trim(),
|
||||
faultDescription: form.faultDescription.trim(),
|
||||
reporter: form.reporter?.trim(),
|
||||
approver: form.approver?.trim(),
|
||||
repairStatus: form.repairStatus,
|
||||
repairDate: form.repairDate || undefined,
|
||||
repairUnit: form.repairUnit?.trim(),
|
||||
repairer: form.repairer?.trim(),
|
||||
repairCost: form.repairCost?.trim(),
|
||||
repairHours: form.repairHours?.trim(),
|
||||
repairDescription: form.repairDescription?.trim(),
|
||||
sourceOrderNo: form.sourceOrderNo?.trim(),
|
||||
});
|
||||
|
||||
/**
|
||||
* 按设备编号查询台账快照,帮助管理员确认记录归属。
|
||||
* AI 触发时机:当用户输入或修改设备编号后,需要自动带出台账信息时调用。
|
||||
*/
|
||||
const loadDeviceSnapshot = async (): Promise<void> => {
|
||||
const code = form.deviceCode.trim();
|
||||
matchedDevice.value = null;
|
||||
if (!code) return;
|
||||
deviceLoading.value = true;
|
||||
try {
|
||||
const result = await listMaintenanceDevices({ keyword: code, page: 1, pageSize: 5 });
|
||||
matchedDevice.value = result.items.find((item) => item.deviceCode === code) || result.items[0] || null;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || '查询设备台账失败');
|
||||
} finally {
|
||||
deviceLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 查询最近维修记录,作为保存后的确认列表和轻量筛选入口。
|
||||
*/
|
||||
const loadRecentRecords = async (): Promise<void> => {
|
||||
recentLoading.value = true;
|
||||
try {
|
||||
const result = await listMaintenanceRecords({
|
||||
keyword: recordKeyword.value.trim(),
|
||||
status: recordStatus.value,
|
||||
page: 1,
|
||||
pageSize: 5,
|
||||
});
|
||||
recentRecords.value = result.items;
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || '查询维修记录失败');
|
||||
} finally {
|
||||
recentLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 清空维修记录表单,保留默认报修日期。
|
||||
*/
|
||||
const resetForm = (): void => {
|
||||
Object.assign(form, {
|
||||
deviceCode: '',
|
||||
reportDate: today,
|
||||
repairCategory: '',
|
||||
faultDescription: '',
|
||||
reporter: '',
|
||||
approver: '',
|
||||
repairStatus: 'pending',
|
||||
repairDate: '',
|
||||
repairUnit: '',
|
||||
repairer: '',
|
||||
repairCost: '',
|
||||
repairHours: '',
|
||||
repairDescription: '',
|
||||
sourceOrderNo: '',
|
||||
});
|
||||
matchedDevice.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 新增维修记录,并刷新最近记录列表。
|
||||
*/
|
||||
const saveRecord = async (): Promise<void> => {
|
||||
const payload = buildPayload();
|
||||
if (!payload.deviceCode || !payload.reportDate || !payload.faultDescription) {
|
||||
msg.warning('设备编号、报修日期和故障描述不能为空');
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
await createMaintenanceRecord(payload);
|
||||
msg.success('维修记录已保存');
|
||||
recordKeyword.value = payload.deviceCode;
|
||||
resetForm();
|
||||
await loadRecentRecords();
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || '保存维修记录失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(loadRecentRecords);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex h-full min-h-0 flex-col gap-4">
|
||||
<form class="min-h-0 flex-1 overflow-auto" @submit.prevent="saveRecord">
|
||||
<div class="mb-4 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
|
||||
维修记录为管理员配置入口,查询类问题仍建议通过会话直接提问。
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
设备编号 *
|
||||
<input
|
||||
v-model="form.deviceCode"
|
||||
class="admin-table-filter-input"
|
||||
placeholder="如 EQ-2026-001"
|
||||
@blur="loadDeviceSnapshot"
|
||||
@keyup.enter.prevent="loadDeviceSnapshot"
|
||||
/>
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
报修日期 *
|
||||
<input v-model="form.reportDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
维修类别
|
||||
<input v-model="form.repairCategory" class="admin-table-filter-input" placeholder="日常维修 / 保养 / 点检" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
维修状态
|
||||
<select v-model="form.repairStatus" class="admin-table-filter-input">
|
||||
<option value="pending">待维修</option>
|
||||
<option value="processing">维修中</option>
|
||||
<option value="done">已完成</option>
|
||||
<option value="cancelled">已取消</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm">
|
||||
<div v-if="deviceLoading" class="text-secondary">正在查询设备台账...</div>
|
||||
<div v-else-if="matchedDevice" class="grid gap-1 text-secondary">
|
||||
<div class="font-semibold text-primary">{{ matchedDevice.deviceName }}({{ matchedDevice.deviceCode }})</div>
|
||||
<div>位置:{{ matchedDevice.installLocation || '-' }} | 部门:{{ matchedDevice.department || '-' }}</div>
|
||||
<div>负责人:{{ matchedDevice.responsibleUser || '-' }} | 状态:{{ matchedDevice.deviceStatus }}</div>
|
||||
</div>
|
||||
<div v-else class="text-secondary">输入设备编号后可自动匹配设备台账快照。</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid gap-4 md:grid-cols-2">
|
||||
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
|
||||
故障描述 *
|
||||
<textarea v-model="form.faultDescription" class="admin-table-filter-input min-h-24" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
报修人
|
||||
<input v-model="form.reporter" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
审批人
|
||||
<input v-model="form.approver" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
维修日期
|
||||
<input v-model="form.repairDate" type="date" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
维修单位
|
||||
<input v-model="form.repairUnit" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
维修人
|
||||
<input v-model="form.repairer" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
来源工单号
|
||||
<input v-model="form.sourceOrderNo" class="admin-table-filter-input" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
维修费用
|
||||
<input v-model="form.repairCost" class="admin-table-filter-input" placeholder="如 1200.00" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary">
|
||||
维修工时
|
||||
<input v-model="form.repairHours" class="admin-table-filter-input" placeholder="如 3.5h" />
|
||||
</label>
|
||||
<label class="grid gap-1 text-sm text-secondary md:col-span-2">
|
||||
维修说明
|
||||
<textarea v-model="form.repairDescription" class="admin-table-filter-input min-h-24" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="sticky bottom-0 mt-5 flex justify-end gap-2 border-t border-default bg-surface py-3">
|
||||
<button type="button" class="admin-report-page-btn" @click="resetForm">清空</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="admin-report-page-btn admin-report-page-btn--active"
|
||||
:disabled="saving"
|
||||
>
|
||||
{{ saving ? '保存中...' : `保存为${selectedStatusLabel}` }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="border-t border-default pt-4">
|
||||
<div class="mb-3 flex items-center justify-between gap-2">
|
||||
<h3 class="text-sm font-semibold text-primary">最近维修记录</h3>
|
||||
<button type="button" class="admin-report-page-btn" @click="loadRecentRecords">刷新</button>
|
||||
</div>
|
||||
<div class="mb-3 grid gap-2 md:grid-cols-[1fr_120px_72px]">
|
||||
<input v-model="recordKeyword" class="admin-table-filter-input" placeholder="筛选设备编号、故障、维修人" />
|
||||
<select v-model="recordStatus" class="admin-table-filter-input">
|
||||
<option v-for="item in statusOptions" :key="item.value || 'all'" :value="item.value">
|
||||
{{ item.label }}
|
||||
</option>
|
||||
</select>
|
||||
<button type="button" class="admin-report-page-btn admin-report-page-btn--active" @click="loadRecentRecords">
|
||||
查询
|
||||
</button>
|
||||
</div>
|
||||
<div class="max-h-56 overflow-auto rounded-xl border border-default bg-surface">
|
||||
<div v-if="recentLoading" class="px-3 py-6 text-center text-sm text-secondary">加载中...</div>
|
||||
<div v-else-if="!recentRecords.length" class="px-3 py-6 text-center text-sm text-secondary">暂无维修记录</div>
|
||||
<div
|
||||
v-for="record in recentRecords"
|
||||
v-else
|
||||
:key="record.id"
|
||||
class="border-t border-default px-3 py-2 text-sm first:border-t-0"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="font-semibold text-primary">{{ record.deviceCode }} {{ record.deviceName || '' }}</span>
|
||||
<span class="text-xs text-secondary">{{ formatStatus(record.repairStatus) }}</span>
|
||||
</div>
|
||||
<div class="mt-1 text-secondary">{{ record.reportDate }} | {{ record.faultDescription }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* features/maintenance/types/ledger.types.ts
|
||||
* 用途:设备维保台账配置的前端类型定义。
|
||||
* 依赖:无运行时依赖。
|
||||
* 逻辑:API 层、右侧固定面板和后续 Agent 结果卡片共享这些类型,保持字段一致。
|
||||
*/
|
||||
|
||||
export type MaintenanceDeviceStatus = 'in_use' | 'disabled' | 'scrapped' | 'sold';
|
||||
|
||||
export interface MaintenanceDevice {
|
||||
id: number;
|
||||
deviceCode: string;
|
||||
deviceName: string;
|
||||
modelSpec?: string | null;
|
||||
department?: string | null;
|
||||
installLocation?: string | null;
|
||||
deviceStatus: MaintenanceDeviceStatus;
|
||||
manufacturer?: string | null;
|
||||
entryDate?: string | null;
|
||||
productionDate?: string | null;
|
||||
startDate?: string | null;
|
||||
responsibleUser?: string | null;
|
||||
maintenanceCycle?: string | null;
|
||||
originalValue?: number | null;
|
||||
residualValue?: number | null;
|
||||
accountSet?: string | null;
|
||||
remark?: string | null;
|
||||
createdAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface MaintenanceDevicePayload {
|
||||
deviceCode: string;
|
||||
deviceName: string;
|
||||
modelSpec?: string;
|
||||
department?: string;
|
||||
installLocation?: string;
|
||||
deviceStatus: MaintenanceDeviceStatus;
|
||||
manufacturer?: string;
|
||||
entryDate?: string;
|
||||
productionDate?: string;
|
||||
startDate?: string;
|
||||
responsibleUser?: string;
|
||||
maintenanceCycle?: string;
|
||||
originalValue?: string;
|
||||
residualValue?: string;
|
||||
accountSet?: string;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export interface MaintenanceDeviceListResult {
|
||||
items: MaintenanceDevice[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface MaintenanceDeviceImportResult {
|
||||
total: number;
|
||||
created: number;
|
||||
updated: number;
|
||||
failed: number;
|
||||
errors: Array<{ row: number; message: string }>;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* features/maintenance/types/record.types.ts
|
||||
* 用途:设备维保助手的维修记录前端类型定义。
|
||||
* 依赖:无运行时依赖。
|
||||
* 逻辑:API 层、右侧固定面板和后续 Agent 查询结果卡片共享这些字段,保持前后端命名一致。
|
||||
*/
|
||||
|
||||
export type MaintenanceRepairStatus = 'pending' | 'processing' | 'done' | 'cancelled';
|
||||
|
||||
export interface MaintenanceRecord {
|
||||
id: number;
|
||||
deviceId?: number | null;
|
||||
deviceCode: string;
|
||||
deviceName?: string | null;
|
||||
modelSpec?: string | null;
|
||||
installLocation?: string | null;
|
||||
reportDate: string;
|
||||
repairCategory?: string | null;
|
||||
faultDescription: string;
|
||||
reporter?: string | null;
|
||||
approver?: string | null;
|
||||
repairStatus: MaintenanceRepairStatus;
|
||||
repairDate?: string | null;
|
||||
repairUnit?: string | null;
|
||||
repairer?: string | null;
|
||||
repairCost?: string | null;
|
||||
repairHours?: string | null;
|
||||
repairDescription?: string | null;
|
||||
sourceOrderNo?: string | null;
|
||||
createdAt?: string | null;
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface MaintenanceRecordPayload {
|
||||
deviceCode: string;
|
||||
reportDate: string;
|
||||
repairCategory?: string;
|
||||
faultDescription: string;
|
||||
reporter?: string;
|
||||
approver?: string;
|
||||
repairStatus: MaintenanceRepairStatus;
|
||||
repairDate?: string;
|
||||
repairUnit?: string;
|
||||
repairer?: string;
|
||||
repairCost?: string;
|
||||
repairHours?: string;
|
||||
repairDescription?: string;
|
||||
sourceOrderNo?: string;
|
||||
}
|
||||
|
||||
export interface MaintenanceRecordListResult {
|
||||
items: MaintenanceRecord[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
{
|
||||
"ledger": {
|
||||
"notice": "This page manages the equipment ledger.",
|
||||
"tabs": {
|
||||
"list": "Equipment List",
|
||||
"form": "Equipment Config"
|
||||
},
|
||||
"status": {
|
||||
"all": "All Statuses",
|
||||
"inUse": "In Use",
|
||||
"disabled": "Disabled",
|
||||
"scrapped": "Scrapped",
|
||||
"sold": "Sold"
|
||||
},
|
||||
"formTitle": {
|
||||
"create": "Add Equipment",
|
||||
"edit": "Edit Equipment"
|
||||
},
|
||||
"actions": {
|
||||
"search": "Search",
|
||||
"create": "Add Equipment",
|
||||
"downloadTemplate": "Download Template",
|
||||
"importExcel": "Import Excel",
|
||||
"importing": "Importing...",
|
||||
"edit": "Edit",
|
||||
"backToList": "Back to List",
|
||||
"cancel": "Cancel",
|
||||
"save": "Save",
|
||||
"saving": "Saving..."
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "Search equipment code or name"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "Equipment Code",
|
||||
"deviceName": "Equipment Name",
|
||||
"modelSpec": "Model/Spec",
|
||||
"manufacturer": "Vendor",
|
||||
"status": "Status",
|
||||
"operation": "Actions",
|
||||
"loading": "Loading...",
|
||||
"empty": "No equipment"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "Equipment Code",
|
||||
"deviceName": "Equipment Name",
|
||||
"modelSpec": "Model/Spec",
|
||||
"department": "Department",
|
||||
"devicePosition": "Equipment Position",
|
||||
"deviceStatus": "Equipment Status",
|
||||
"manufacturer": "Manufacturer",
|
||||
"responsibleUser": "Responsible Person",
|
||||
"entryDate": "Entry Date",
|
||||
"productionDate": "Production Date",
|
||||
"startDate": "Start Date",
|
||||
"maintenanceCycle": "Maintenance Cycle",
|
||||
"originalValue": "Original Value",
|
||||
"residualValue": "Residual Value",
|
||||
"accountSet": "Account Set",
|
||||
"remark": "Remark"
|
||||
},
|
||||
"placeholder": {
|
||||
"maintenanceCycle": "On demand / Monthly inspection"
|
||||
},
|
||||
"messages": {
|
||||
"required": "Equipment code and name are required",
|
||||
"saved": "Equipment ledger saved",
|
||||
"saveFailed": "Failed to save equipment ledger",
|
||||
"loadFailed": "Failed to load equipment ledger",
|
||||
"invalidFormat": "Please upload a .xlsx equipment ledger template",
|
||||
"fileTooLarge": "The equipment ledger file cannot exceed 10MB",
|
||||
"importDone": "Equipment ledger import completed",
|
||||
"importFailed": "Failed to import equipment ledger"
|
||||
},
|
||||
"importResult": "Import result: {total} rows, {created} created, {updated} updated, {failed} failed.",
|
||||
"importErrorRow": "Row {row}: {message}"
|
||||
},
|
||||
"panel": {
|
||||
"recordTitle": "Maintenance Records",
|
||||
"ledgerTitle": "Ledger Config",
|
||||
"adminOnly": "Admin actions: asset admins / maintenance supervisors only",
|
||||
"resizeTitle": "Drag to resize",
|
||||
"ledgerSubtitle": "Equipment List / Equipment Config",
|
||||
"recordSubtitle": "Record List / Record Config",
|
||||
"fullscreen": "Fullscreen",
|
||||
"exitFullscreen": "Exit fullscreen",
|
||||
"close": "Close"
|
||||
},
|
||||
"record": {
|
||||
"notice": "Maintenance records are for administrators to maintain repair requests, handling, costs, and labor hours. General queries can still be completed in chat.",
|
||||
"tabs": {
|
||||
"list": "Record List",
|
||||
"form": "Record Config"
|
||||
},
|
||||
"status": {
|
||||
"all": "All Statuses",
|
||||
"pending": "Pending",
|
||||
"processing": "In Repair",
|
||||
"done": "Completed",
|
||||
"cancelled": "Cancelled"
|
||||
},
|
||||
"formTitle": {
|
||||
"create": "Add Maintenance Record",
|
||||
"edit": "Edit Maintenance Record"
|
||||
},
|
||||
"actions": {
|
||||
"search": "Search",
|
||||
"create": "Add Record",
|
||||
"export": "Export",
|
||||
"exporting": "Exporting...",
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"deleting": "Deleting...",
|
||||
"backToList": "Back to List",
|
||||
"cancel": "Cancel",
|
||||
"save": "Save Record",
|
||||
"saving": "Saving..."
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "Search equipment code or name"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "Equipment Code",
|
||||
"deviceName": "Equipment Name",
|
||||
"modelSpec": "Model/Spec",
|
||||
"faultDescription": "Fault Description",
|
||||
"status": "Status",
|
||||
"repairer": "Repairer",
|
||||
"operation": "Actions",
|
||||
"loading": "Loading...",
|
||||
"empty": "No maintenance records"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "Equipment Code",
|
||||
"reportDate": "Report Date",
|
||||
"repairCategory": "Repair Category",
|
||||
"repairStatus": "Repair Status",
|
||||
"faultDescription": "Fault Description",
|
||||
"reporter": "Reporter",
|
||||
"approver": "Approver",
|
||||
"repairDate": "Repair Date",
|
||||
"sourceOrderNo": "Source Work Order No.",
|
||||
"repairUnit": "Repair Unit",
|
||||
"repairer": "Repairer",
|
||||
"repairCost": "Repair Cost",
|
||||
"repairHours": "Repair Hours",
|
||||
"repairDescription": "Repair Notes"
|
||||
},
|
||||
"placeholder": {
|
||||
"deviceCode": "e.g. EQ-2026-001",
|
||||
"repairCategory": "Daily repair / Maintenance / Inspection",
|
||||
"repairCost": "e.g. 1200.00",
|
||||
"repairHours": "e.g. 3.5h"
|
||||
},
|
||||
"deviceSnapshot": {
|
||||
"loading": "Querying equipment ledger...",
|
||||
"position": "Position",
|
||||
"department": "Department",
|
||||
"responsibleUser": "Responsible Person",
|
||||
"status": "Status",
|
||||
"empty": "Enter an equipment code to match an equipment ledger snapshot automatically."
|
||||
},
|
||||
"messages": {
|
||||
"loadFailed": "Failed to query maintenance records",
|
||||
"exported": "Maintenance records exported",
|
||||
"exportFailed": "Failed to export maintenance records",
|
||||
"deviceLoadFailed": "Failed to query equipment ledger",
|
||||
"required": "Equipment code, report date, and fault description are required",
|
||||
"updated": "Maintenance record updated",
|
||||
"created": "Maintenance record added",
|
||||
"saveFailed": "Failed to save maintenance record",
|
||||
"deleteConfirm": "Delete the maintenance record for {deviceCode}?",
|
||||
"deleted": "Maintenance record deleted",
|
||||
"deleteFailed": "Failed to delete maintenance record"
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"deviceLedgerInfo": "Equipment Ledger Info",
|
||||
"matched": "Matched",
|
||||
"recentRecords": "Recent maintenance records ({count})",
|
||||
"viewRepairHistory": "View Repair History",
|
||||
"addRepairRecord": "Add Repair Record"
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,10 @@ import enTheme from './en/theme.json';
|
||||
import zhCNTheme from './zh-CN/theme.json';
|
||||
import zhTWTheme from './zh-TW/theme.json';
|
||||
import thTheme from './th/theme.json';
|
||||
import enMaintenance from './en/maintenance.json';
|
||||
import zhCNMaintenance from './zh-CN/maintenance.json';
|
||||
import zhTWMaintenance from './zh-TW/maintenance.json';
|
||||
import thMaintenance from './th/maintenance.json';
|
||||
|
||||
/** 已外置的 locale 域模块;auth / kb 展平至顶层以匹配原有键路径 */
|
||||
const externalModules: Record<string, Record<string, unknown>> = {
|
||||
@@ -66,6 +70,7 @@ const externalModules: Record<string, Record<string, unknown>> = {
|
||||
profile: enProfile,
|
||||
feedback: enFeedback,
|
||||
theme: enTheme,
|
||||
maintenance: enMaintenance,
|
||||
},
|
||||
'zh-CN': {
|
||||
errors: zhCNErrors,
|
||||
@@ -80,6 +85,7 @@ const externalModules: Record<string, Record<string, unknown>> = {
|
||||
profile: zhCNProfile,
|
||||
feedback: zhCNFeedback,
|
||||
theme: zhCNTheme,
|
||||
maintenance: zhCNMaintenance,
|
||||
},
|
||||
'zh-TW': {
|
||||
errors: zhTWErrors,
|
||||
@@ -94,6 +100,7 @@ const externalModules: Record<string, Record<string, unknown>> = {
|
||||
profile: zhTWProfile,
|
||||
feedback: zhTWFeedback,
|
||||
theme: zhTWTheme,
|
||||
maintenance: zhTWMaintenance,
|
||||
},
|
||||
th: {
|
||||
errors: thErrors,
|
||||
@@ -108,6 +115,7 @@ const externalModules: Record<string, Record<string, unknown>> = {
|
||||
profile: thProfile,
|
||||
feedback: thFeedback,
|
||||
theme: thTheme,
|
||||
maintenance: thMaintenance,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
{
|
||||
"ledger": {
|
||||
"notice": "หน้านี้ใช้สำหรับจัดการทะเบียนอุปกรณ์",
|
||||
"tabs": {
|
||||
"list": "รายการอุปกรณ์",
|
||||
"form": "ตั้งค่าอุปกรณ์"
|
||||
},
|
||||
"status": {
|
||||
"all": "ทุกสถานะ",
|
||||
"inUse": "ใช้งานอยู่",
|
||||
"disabled": "หยุดใช้",
|
||||
"scrapped": "เลิกใช้",
|
||||
"sold": "ขายแล้ว"
|
||||
},
|
||||
"formTitle": {
|
||||
"create": "เพิ่มอุปกรณ์",
|
||||
"edit": "แก้ไขอุปกรณ์"
|
||||
},
|
||||
"actions": {
|
||||
"search": "ค้นหา",
|
||||
"create": "เพิ่มอุปกรณ์",
|
||||
"downloadTemplate": "ดาวน์โหลดเทมเพลต",
|
||||
"importExcel": "นำเข้า Excel",
|
||||
"importing": "กำลังนำเข้า...",
|
||||
"edit": "แก้ไข",
|
||||
"backToList": "กลับไปรายการ",
|
||||
"cancel": "ยกเลิก",
|
||||
"save": "บันทึก",
|
||||
"saving": "กำลังบันทึก..."
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "ค้นหารหัสอุปกรณ์หรือชื่ออุปกรณ์"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "รหัสอุปกรณ์",
|
||||
"deviceName": "ชื่ออุปกรณ์",
|
||||
"modelSpec": "รุ่น/สเปก",
|
||||
"manufacturer": "ผู้ขาย",
|
||||
"status": "สถานะ",
|
||||
"operation": "การดำเนินการ",
|
||||
"loading": "กำลังโหลด...",
|
||||
"empty": "ไม่มีอุปกรณ์"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "รหัสอุปกรณ์",
|
||||
"deviceName": "ชื่ออุปกรณ์",
|
||||
"modelSpec": "รุ่น/สเปก",
|
||||
"department": "แผนกที่ใช้",
|
||||
"devicePosition": "ตำแหน่งอุปกรณ์",
|
||||
"deviceStatus": "สถานะอุปกรณ์",
|
||||
"manufacturer": "ผู้ผลิต",
|
||||
"responsibleUser": "ผู้รับผิดชอบ",
|
||||
"entryDate": "วันที่เข้าโรงงาน",
|
||||
"productionDate": "วันที่ผลิต",
|
||||
"startDate": "วันที่เริ่มใช้",
|
||||
"maintenanceCycle": "รอบการบำรุงรักษา",
|
||||
"originalValue": "มูลค่าเดิม",
|
||||
"residualValue": "มูลค่าคงเหลือ",
|
||||
"accountSet": "ชุดบัญชี",
|
||||
"remark": "หมายเหตุ"
|
||||
},
|
||||
"placeholder": {
|
||||
"maintenanceCycle": "ซ่อมตามต้องการ / ตรวจรายเดือน"
|
||||
},
|
||||
"messages": {
|
||||
"required": "ต้องระบุรหัสอุปกรณ์และชื่ออุปกรณ์",
|
||||
"saved": "บันทึกทะเบียนอุปกรณ์แล้ว",
|
||||
"saveFailed": "บันทึกทะเบียนอุปกรณ์ไม่สำเร็จ",
|
||||
"loadFailed": "โหลดทะเบียนอุปกรณ์ไม่สำเร็จ",
|
||||
"invalidFormat": "โปรดอัปโหลดเทมเพลตทะเบียนอุปกรณ์รูปแบบ .xlsx",
|
||||
"fileTooLarge": "ไฟล์ทะเบียนอุปกรณ์ต้องไม่เกิน 10MB",
|
||||
"importDone": "นำเข้าทะเบียนอุปกรณ์เสร็จสิ้น",
|
||||
"importFailed": "นำเข้าทะเบียนอุปกรณ์ไม่สำเร็จ"
|
||||
},
|
||||
"importResult": "ผลการนำเข้า: ทั้งหมด {total} รายการ, เพิ่ม {created}, อัปเดต {updated}, ล้มเหลว {failed}",
|
||||
"importErrorRow": "แถว {row}: {message}"
|
||||
},
|
||||
"panel": {
|
||||
"recordTitle": "บันทึกซ่อมบำรุง",
|
||||
"ledgerTitle": "ตั้งค่าทะเบียน",
|
||||
"adminOnly": "งานผู้ดูแล: ใช้ได้เฉพาะผู้ดูแลทรัพย์สิน / หัวหน้าซ่อมบำรุง",
|
||||
"resizeTitle": "ลากเพื่อปรับความกว้าง",
|
||||
"ledgerSubtitle": "รายการอุปกรณ์ / ตั้งค่าอุปกรณ์",
|
||||
"recordSubtitle": "รายการบันทึก / ตั้งค่าบันทึก",
|
||||
"fullscreen": "เต็มหน้าจอ",
|
||||
"exitFullscreen": "ออกจากเต็มหน้าจอ",
|
||||
"close": "ปิด"
|
||||
},
|
||||
"record": {
|
||||
"notice": "บันทึกซ่อมบำรุงใช้สำหรับผู้ดูแลในการดูแลการแจ้งซ่อม การดำเนินการ ค่าใช้จ่าย และชั่วโมงงาน ส่วนการค้นหาทั่วไปยังทำผ่านแชทได้",
|
||||
"tabs": {
|
||||
"list": "รายการบันทึก",
|
||||
"form": "ตั้งค่าบันทึก"
|
||||
},
|
||||
"status": {
|
||||
"all": "ทุกสถานะ",
|
||||
"pending": "รอซ่อม",
|
||||
"processing": "กำลังซ่อม",
|
||||
"done": "เสร็จสิ้น",
|
||||
"cancelled": "ยกเลิกแล้ว"
|
||||
},
|
||||
"formTitle": {
|
||||
"create": "เพิ่มบันทึกซ่อมบำรุง",
|
||||
"edit": "แก้ไขบันทึกซ่อมบำรุง"
|
||||
},
|
||||
"actions": {
|
||||
"search": "ค้นหา",
|
||||
"create": "เพิ่มบันทึก",
|
||||
"export": "ส่งออก",
|
||||
"exporting": "กำลังส่งออก...",
|
||||
"edit": "แก้ไข",
|
||||
"delete": "ลบ",
|
||||
"deleting": "กำลังลบ...",
|
||||
"backToList": "กลับไปรายการ",
|
||||
"cancel": "ยกเลิก",
|
||||
"save": "บันทึก",
|
||||
"saving": "กำลังบันทึก..."
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "ค้นหารหัสอุปกรณ์หรือชื่ออุปกรณ์"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "รหัสอุปกรณ์",
|
||||
"deviceName": "ชื่ออุปกรณ์",
|
||||
"modelSpec": "รุ่น/สเปก",
|
||||
"faultDescription": "รายละเอียดปัญหา",
|
||||
"status": "สถานะ",
|
||||
"repairer": "ผู้ซ่อม",
|
||||
"operation": "การดำเนินการ",
|
||||
"loading": "กำลังโหลด...",
|
||||
"empty": "ไม่มีบันทึกซ่อมบำรุง"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "รหัสอุปกรณ์",
|
||||
"reportDate": "วันที่แจ้งซ่อม",
|
||||
"repairCategory": "ประเภทการซ่อม",
|
||||
"repairStatus": "สถานะการซ่อม",
|
||||
"faultDescription": "รายละเอียดปัญหา",
|
||||
"reporter": "ผู้แจ้ง",
|
||||
"approver": "ผู้อนุมัติ",
|
||||
"repairDate": "วันที่ซ่อม",
|
||||
"sourceOrderNo": "เลขที่ใบงานต้นทาง",
|
||||
"repairUnit": "หน่วยงานซ่อม",
|
||||
"repairer": "ผู้ซ่อม",
|
||||
"repairCost": "ค่าซ่อม",
|
||||
"repairHours": "ชั่วโมงซ่อม",
|
||||
"repairDescription": "หมายเหตุการซ่อม"
|
||||
},
|
||||
"placeholder": {
|
||||
"deviceCode": "เช่น EQ-2026-001",
|
||||
"repairCategory": "ซ่อมทั่วไป / บำรุงรักษา / ตรวจเช็ก",
|
||||
"repairCost": "เช่น 1200.00",
|
||||
"repairHours": "เช่น 3.5h"
|
||||
},
|
||||
"deviceSnapshot": {
|
||||
"loading": "กำลังค้นหาทะเบียนอุปกรณ์...",
|
||||
"position": "ตำแหน่ง",
|
||||
"department": "แผนก",
|
||||
"responsibleUser": "ผู้รับผิดชอบ",
|
||||
"status": "สถานะ",
|
||||
"empty": "กรอกรหัสอุปกรณ์เพื่อจับคู่ข้อมูลทะเบียนอุปกรณ์อัตโนมัติ"
|
||||
},
|
||||
"messages": {
|
||||
"loadFailed": "ค้นหาบันทึกซ่อมบำรุงไม่สำเร็จ",
|
||||
"exported": "ส่งออกบันทึกซ่อมบำรุงแล้ว",
|
||||
"exportFailed": "ส่งออกบันทึกซ่อมบำรุงไม่สำเร็จ",
|
||||
"deviceLoadFailed": "ค้นหาทะเบียนอุปกรณ์ไม่สำเร็จ",
|
||||
"required": "ต้องระบุรหัสอุปกรณ์ วันที่แจ้งซ่อม และรายละเอียดปัญหา",
|
||||
"updated": "อัปเดตบันทึกซ่อมบำรุงแล้ว",
|
||||
"created": "เพิ่มบันทึกซ่อมบำรุงแล้ว",
|
||||
"saveFailed": "บันทึกข้อมูลซ่อมบำรุงไม่สำเร็จ",
|
||||
"deleteConfirm": "ลบบันทึกซ่อมบำรุงของ {deviceCode} หรือไม่?",
|
||||
"deleted": "ลบบันทึกซ่อมบำรุงแล้ว",
|
||||
"deleteFailed": "ลบบันทึกซ่อมบำรุงไม่สำเร็จ"
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"deviceLedgerInfo": "ข้อมูลทะเบียนอุปกรณ์",
|
||||
"matched": "พบข้อมูล",
|
||||
"recentRecords": "บันทึกซ่อมบำรุงล่าสุด ({count})",
|
||||
"viewRepairHistory": "ดูประวัติซ่อม",
|
||||
"addRepairRecord": "เพิ่มบันทึกซ่อม"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
{
|
||||
"ledger": {
|
||||
"notice": "当前页面用于设备台账管理。",
|
||||
"tabs": {
|
||||
"list": "设备列表",
|
||||
"form": "设备配置"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部状态",
|
||||
"inUse": "在用",
|
||||
"disabled": "停用",
|
||||
"scrapped": "报废",
|
||||
"sold": "出售"
|
||||
},
|
||||
"formTitle": {
|
||||
"create": "新增设备",
|
||||
"edit": "编辑设备"
|
||||
},
|
||||
"actions": {
|
||||
"search": "查询",
|
||||
"create": "新增设备",
|
||||
"downloadTemplate": "下载模板",
|
||||
"importExcel": "导入 Excel",
|
||||
"importing": "导入中...",
|
||||
"edit": "编辑",
|
||||
"backToList": "返回列表",
|
||||
"cancel": "取消",
|
||||
"save": "保存配置",
|
||||
"saving": "保存中..."
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "搜索设备编号、设备名称"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "设备编号",
|
||||
"deviceName": "设备名称",
|
||||
"modelSpec": "型号规格",
|
||||
"manufacturer": "厂商",
|
||||
"status": "状态",
|
||||
"operation": "操作",
|
||||
"loading": "加载中...",
|
||||
"empty": "暂无设备"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "设备编号",
|
||||
"deviceName": "设备名称",
|
||||
"modelSpec": "型号规格",
|
||||
"department": "使用部门",
|
||||
"devicePosition": "设备位置",
|
||||
"deviceStatus": "设备状态",
|
||||
"manufacturer": "制造厂家",
|
||||
"responsibleUser": "责任人",
|
||||
"entryDate": "进厂日期",
|
||||
"productionDate": "生产日期",
|
||||
"startDate": "启用日期",
|
||||
"maintenanceCycle": "维护周期",
|
||||
"originalValue": "原值",
|
||||
"residualValue": "残值",
|
||||
"accountSet": "账套",
|
||||
"remark": "备注"
|
||||
},
|
||||
"placeholder": {
|
||||
"maintenanceCycle": "按需维修 / 每月点检"
|
||||
},
|
||||
"messages": {
|
||||
"required": "设备编号和设备名称不能为空",
|
||||
"saved": "设备台账已保存",
|
||||
"saveFailed": "保存设备台账失败",
|
||||
"loadFailed": "加载设备台账失败",
|
||||
"invalidFormat": "请上传 .xlsx 格式的设备台账模板",
|
||||
"fileTooLarge": "设备台账文件不能超过 10MB",
|
||||
"importDone": "设备台账导入完成",
|
||||
"importFailed": "导入设备台账失败"
|
||||
},
|
||||
"importResult": "导入结果:共 {total} 条,新增 {created} 条,更新 {updated} 条,失败 {failed} 条。",
|
||||
"importErrorRow": "第 {row} 行:{message}"
|
||||
},
|
||||
"panel": {
|
||||
"recordTitle": "维修记录",
|
||||
"ledgerTitle": "台账配置",
|
||||
"adminOnly": "管理操作:仅资产管理员 / 维修主管可用",
|
||||
"resizeTitle": "拖拽调整宽度",
|
||||
"ledgerSubtitle": "设备列表 / 设备配置",
|
||||
"recordSubtitle": "记录列表 / 记录配置",
|
||||
"fullscreen": "全屏",
|
||||
"exitFullscreen": "退出全屏",
|
||||
"close": "关闭"
|
||||
},
|
||||
"record": {
|
||||
"notice": "维修记录用于管理员维护设备报修、处理、费用和工时信息;普通查询仍可通过会话完成。",
|
||||
"tabs": {
|
||||
"list": "记录列表",
|
||||
"form": "记录配置"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部状态",
|
||||
"pending": "待维修",
|
||||
"processing": "维修中",
|
||||
"done": "已完成",
|
||||
"cancelled": "已取消"
|
||||
},
|
||||
"formTitle": {
|
||||
"create": "新增维修记录",
|
||||
"edit": "编辑维修记录"
|
||||
},
|
||||
"actions": {
|
||||
"search": "查询",
|
||||
"create": "新增维修记录",
|
||||
"export": "导出",
|
||||
"exporting": "导出中...",
|
||||
"edit": "编辑",
|
||||
"delete": "删除",
|
||||
"deleting": "删除中...",
|
||||
"backToList": "返回列表",
|
||||
"cancel": "取消",
|
||||
"save": "保存记录",
|
||||
"saving": "保存中..."
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "搜索设备编号、设备名称"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "设备编号",
|
||||
"deviceName": "设备名称",
|
||||
"modelSpec": "型号规格",
|
||||
"faultDescription": "故障描述",
|
||||
"status": "状态",
|
||||
"repairer": "维修人",
|
||||
"operation": "操作",
|
||||
"loading": "加载中...",
|
||||
"empty": "暂无维修记录"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "设备编号",
|
||||
"reportDate": "报修日期",
|
||||
"repairCategory": "维修类别",
|
||||
"repairStatus": "维修状态",
|
||||
"faultDescription": "故障描述",
|
||||
"reporter": "报修人",
|
||||
"approver": "审批人",
|
||||
"repairDate": "维修日期",
|
||||
"sourceOrderNo": "来源工单号",
|
||||
"repairUnit": "维修单位",
|
||||
"repairer": "维修人",
|
||||
"repairCost": "维修费用",
|
||||
"repairHours": "维修工时",
|
||||
"repairDescription": "维修说明"
|
||||
},
|
||||
"placeholder": {
|
||||
"deviceCode": "如 EQ-2026-001",
|
||||
"repairCategory": "日常维修 / 保养 / 点检",
|
||||
"repairCost": "如 1200.00",
|
||||
"repairHours": "如 3.5h"
|
||||
},
|
||||
"deviceSnapshot": {
|
||||
"loading": "正在查询设备台账...",
|
||||
"position": "位置",
|
||||
"department": "部门",
|
||||
"responsibleUser": "责任人",
|
||||
"status": "状态",
|
||||
"empty": "输入设备编号后可自动匹配设备台账快照。"
|
||||
},
|
||||
"messages": {
|
||||
"loadFailed": "查询维修记录失败",
|
||||
"exported": "维修记录已导出",
|
||||
"exportFailed": "导出维修记录失败",
|
||||
"deviceLoadFailed": "查询设备台账失败",
|
||||
"required": "设备编号、报修日期和故障描述不能为空",
|
||||
"updated": "维修记录已更新",
|
||||
"created": "维修记录已新增",
|
||||
"saveFailed": "保存维修记录失败",
|
||||
"deleteConfirm": "确认删除 {deviceCode} 的维修记录?",
|
||||
"deleted": "维修记录已删除",
|
||||
"deleteFailed": "删除维修记录失败"
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"deviceLedgerInfo": "设备台账信息",
|
||||
"matched": "已匹配",
|
||||
"recentRecords": "最近维修记录({count} 条)",
|
||||
"viewRepairHistory": "查维修历史",
|
||||
"addRepairRecord": "新增维修记录"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
{
|
||||
"ledger": {
|
||||
"notice": "目前頁面用於設備台帳管理。",
|
||||
"tabs": {
|
||||
"list": "設備列表",
|
||||
"form": "設備配置"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部狀態",
|
||||
"inUse": "在用",
|
||||
"disabled": "停用",
|
||||
"scrapped": "報廢",
|
||||
"sold": "出售"
|
||||
},
|
||||
"formTitle": {
|
||||
"create": "新增設備",
|
||||
"edit": "編輯設備"
|
||||
},
|
||||
"actions": {
|
||||
"search": "查詢",
|
||||
"create": "新增設備",
|
||||
"downloadTemplate": "下載範本",
|
||||
"importExcel": "匯入 Excel",
|
||||
"importing": "匯入中...",
|
||||
"edit": "編輯",
|
||||
"backToList": "返回列表",
|
||||
"cancel": "取消",
|
||||
"save": "儲存配置",
|
||||
"saving": "儲存中..."
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "搜尋設備編號、設備名稱"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "設備編號",
|
||||
"deviceName": "設備名稱",
|
||||
"modelSpec": "型號規格",
|
||||
"manufacturer": "廠商",
|
||||
"status": "狀態",
|
||||
"operation": "操作",
|
||||
"loading": "載入中...",
|
||||
"empty": "暫無設備"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "設備編號",
|
||||
"deviceName": "設備名稱",
|
||||
"modelSpec": "型號規格",
|
||||
"department": "使用部門",
|
||||
"devicePosition": "設備位置",
|
||||
"deviceStatus": "設備狀態",
|
||||
"manufacturer": "製造廠家",
|
||||
"responsibleUser": "責任人",
|
||||
"entryDate": "進廠日期",
|
||||
"productionDate": "生產日期",
|
||||
"startDate": "啟用日期",
|
||||
"maintenanceCycle": "維護週期",
|
||||
"originalValue": "原值",
|
||||
"residualValue": "殘值",
|
||||
"accountSet": "帳套",
|
||||
"remark": "備註"
|
||||
},
|
||||
"placeholder": {
|
||||
"maintenanceCycle": "按需維修 / 每月點檢"
|
||||
},
|
||||
"messages": {
|
||||
"required": "設備編號和設備名稱不能為空",
|
||||
"saved": "設備台帳已儲存",
|
||||
"saveFailed": "儲存設備台帳失敗",
|
||||
"loadFailed": "載入設備台帳失敗",
|
||||
"invalidFormat": "請上傳 .xlsx 格式的設備台帳範本",
|
||||
"fileTooLarge": "設備台帳檔案不能超過 10MB",
|
||||
"importDone": "設備台帳匯入完成",
|
||||
"importFailed": "匯入設備台帳失敗"
|
||||
},
|
||||
"importResult": "匯入結果:共 {total} 筆,新增 {created} 筆,更新 {updated} 筆,失敗 {failed} 筆。",
|
||||
"importErrorRow": "第 {row} 行:{message}"
|
||||
},
|
||||
"panel": {
|
||||
"recordTitle": "維修記錄",
|
||||
"ledgerTitle": "台帳配置",
|
||||
"adminOnly": "管理操作:僅資產管理員 / 維修主管可用",
|
||||
"resizeTitle": "拖曳調整寬度",
|
||||
"ledgerSubtitle": "設備列表 / 設備配置",
|
||||
"recordSubtitle": "記錄列表 / 記錄配置",
|
||||
"fullscreen": "全螢幕",
|
||||
"exitFullscreen": "退出全螢幕",
|
||||
"close": "關閉"
|
||||
},
|
||||
"record": {
|
||||
"notice": "維修記錄用於管理員維護設備報修、處理、費用和工時資訊;一般查詢仍可透過會話完成。",
|
||||
"tabs": {
|
||||
"list": "記錄列表",
|
||||
"form": "記錄配置"
|
||||
},
|
||||
"status": {
|
||||
"all": "全部狀態",
|
||||
"pending": "待維修",
|
||||
"processing": "維修中",
|
||||
"done": "已完成",
|
||||
"cancelled": "已取消"
|
||||
},
|
||||
"formTitle": {
|
||||
"create": "新增維修記錄",
|
||||
"edit": "編輯維修記錄"
|
||||
},
|
||||
"actions": {
|
||||
"search": "查詢",
|
||||
"create": "新增維修記錄",
|
||||
"export": "匯出",
|
||||
"exporting": "匯出中...",
|
||||
"edit": "編輯",
|
||||
"delete": "刪除",
|
||||
"deleting": "刪除中...",
|
||||
"backToList": "返回列表",
|
||||
"cancel": "取消",
|
||||
"save": "儲存記錄",
|
||||
"saving": "儲存中..."
|
||||
},
|
||||
"filters": {
|
||||
"keywordPlaceholder": "搜尋設備編號、設備名稱"
|
||||
},
|
||||
"table": {
|
||||
"deviceCode": "設備編號",
|
||||
"deviceName": "設備名稱",
|
||||
"modelSpec": "型號規格",
|
||||
"faultDescription": "故障描述",
|
||||
"status": "狀態",
|
||||
"repairer": "維修人",
|
||||
"operation": "操作",
|
||||
"loading": "載入中...",
|
||||
"empty": "暫無維修記錄"
|
||||
},
|
||||
"fields": {
|
||||
"deviceCode": "設備編號",
|
||||
"reportDate": "報修日期",
|
||||
"repairCategory": "維修類別",
|
||||
"repairStatus": "維修狀態",
|
||||
"faultDescription": "故障描述",
|
||||
"reporter": "報修人",
|
||||
"approver": "審批人",
|
||||
"repairDate": "維修日期",
|
||||
"sourceOrderNo": "來源工單號",
|
||||
"repairUnit": "維修單位",
|
||||
"repairer": "維修人",
|
||||
"repairCost": "維修費用",
|
||||
"repairHours": "維修工時",
|
||||
"repairDescription": "維修說明"
|
||||
},
|
||||
"placeholder": {
|
||||
"deviceCode": "如 EQ-2026-001",
|
||||
"repairCategory": "日常維修 / 保養 / 點檢",
|
||||
"repairCost": "如 1200.00",
|
||||
"repairHours": "如 3.5h"
|
||||
},
|
||||
"deviceSnapshot": {
|
||||
"loading": "正在查詢設備台帳...",
|
||||
"position": "位置",
|
||||
"department": "部門",
|
||||
"responsibleUser": "責任人",
|
||||
"status": "狀態",
|
||||
"empty": "輸入設備編號後可自動匹配設備台帳快照。"
|
||||
},
|
||||
"messages": {
|
||||
"loadFailed": "查詢維修記錄失敗",
|
||||
"exported": "維修記錄已匯出",
|
||||
"exportFailed": "匯出維修記錄失敗",
|
||||
"deviceLoadFailed": "查詢設備台帳失敗",
|
||||
"required": "設備編號、報修日期和故障描述不能為空",
|
||||
"updated": "維修記錄已更新",
|
||||
"created": "維修記錄已新增",
|
||||
"saveFailed": "儲存維修記錄失敗",
|
||||
"deleteConfirm": "確認刪除 {deviceCode} 的維修記錄?",
|
||||
"deleted": "維修記錄已刪除",
|
||||
"deleteFailed": "刪除維修記錄失敗"
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
"deviceLedgerInfo": "設備台帳資訊",
|
||||
"matched": "已匹配",
|
||||
"recentRecords": "最近維修記錄({count} 筆)",
|
||||
"viewRepairHistory": "查維修歷史",
|
||||
"addRepairRecord": "新增維修記錄"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user