feat(equipment-maintenance): 设备维保助手意图识别
A (cherry picked from commit 2c7883567358b3787f2bba55332fb6887392d80d)
This commit is contained in:
1 parent
95f3906779
commit
76d5778c3b
18 files changed
+881
-87
No files matched your search
@@ -109,3 +109,6 @@ SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=xxxx
|
||||
@@ -59,4 +59,8 @@ MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=xxxx
|
||||
@@ -112,4 +112,8 @@ SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=xxxx
|
||||
@@ -23,10 +23,12 @@ from app.services.maintenance_ledger_service import (
|
||||
update_device,
|
||||
)
|
||||
from app.services.maintenance_record_service import (
|
||||
build_records_import_template,
|
||||
build_records_export,
|
||||
create_record,
|
||||
delete_record,
|
||||
get_record,
|
||||
import_records_from_excel,
|
||||
list_records,
|
||||
update_record,
|
||||
)
|
||||
@@ -153,6 +155,29 @@ def export_maintenance_records():
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/import-template', methods=['GET'])
|
||||
def download_records_import_template():
|
||||
"""下载维修记录 Excel 导入模板。"""
|
||||
_require_ledger_admin()
|
||||
return send_file(
|
||||
BytesIO(build_records_import_template()),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_record_history_template.xls',
|
||||
mimetype='application/vnd.ms-excel',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/import', methods=['POST'])
|
||||
def import_maintenance_records():
|
||||
"""上传 Excel 模板并批量新增维修记录。"""
|
||||
user = _require_ledger_admin()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
result = import_records_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['POST'])
|
||||
def create_maintenance_record():
|
||||
"""新增设备维修记录,仅固定管理角色可用。"""
|
||||
|
||||
@@ -342,6 +342,102 @@ def build_import_template() -> bytes:
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _load_import_workbook(file_obj: Any, *, filename: str):
|
||||
"""
|
||||
Load an Excel workbook for maintenance imports.
|
||||
Args:
|
||||
file_obj: Flask upload file object.
|
||||
filename: Original upload filename. Supports .xlsx and legacy .xls.
|
||||
Returns:
|
||||
openpyxl Workbook instance. .xls is converted in memory with xlrd first.
|
||||
Raises:
|
||||
ValidationError: File type is unsupported or content cannot be parsed.
|
||||
"""
|
||||
normalized_name = (filename or '').lower()
|
||||
if not normalized_name.endswith(('.xlsx', '.xls')):
|
||||
raise ValidationError('Only .xls/.xlsx template is supported', details={'filename': filename})
|
||||
parser = 'xlrd' if normalized_name.endswith('.xls') else 'openpyxl'
|
||||
magic = ''
|
||||
try:
|
||||
if hasattr(file_obj, 'seek'):
|
||||
file_obj.seek(0)
|
||||
first_bytes = file_obj.read(8) if hasattr(file_obj, 'read') else b''
|
||||
magic = first_bytes.hex(' ')
|
||||
if hasattr(file_obj, 'seek'):
|
||||
file_obj.seek(0)
|
||||
if normalized_name.endswith('.xls'):
|
||||
return _load_xls_workbook(file_obj)
|
||||
return load_workbook(file_obj, data_only=True)
|
||||
except ValidationError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ValidationError(
|
||||
'Invalid Excel file',
|
||||
details={
|
||||
'filename': filename,
|
||||
'parser': parser,
|
||||
'magic': magic,
|
||||
'error_type': type(exc).__name__,
|
||||
'error': str(exc)[:500],
|
||||
},
|
||||
) from exc
|
||||
|
||||
|
||||
def _load_xls_workbook(file_obj: Any):
|
||||
"""
|
||||
Convert a legacy .xls workbook into an in-memory openpyxl workbook.
|
||||
Args:
|
||||
file_obj: Flask upload file object whose pointer is at the beginning.
|
||||
Returns:
|
||||
openpyxl Workbook instance.
|
||||
"""
|
||||
import xlrd
|
||||
|
||||
content = file_obj.read()
|
||||
if not content:
|
||||
raise ValidationError('Invalid Excel file', details={'reason': 'empty file'})
|
||||
book = xlrd.open_workbook(file_contents=content)
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active)
|
||||
used_titles: set[str] = set()
|
||||
for sheet_index in range(book.nsheets):
|
||||
sheet = book.sheet_by_index(sheet_index)
|
||||
title = str(sheet.name or f'Sheet{sheet_index + 1}')[:31]
|
||||
base_title = title
|
||||
suffix = 1
|
||||
while title in used_titles:
|
||||
suffix += 1
|
||||
title = f'{base_title[:28]}-{suffix}'[:31]
|
||||
used_titles.add(title)
|
||||
ws = wb.create_sheet(title=title)
|
||||
for row_index in range(sheet.nrows):
|
||||
ws.append([
|
||||
_xls_cell_value(book, sheet.cell(row_index, col_index))
|
||||
for col_index in range(sheet.ncols)
|
||||
])
|
||||
return wb
|
||||
|
||||
|
||||
def _xls_cell_value(book: Any, cell: Any) -> Any:
|
||||
"""
|
||||
Normalize an xlrd cell value before handing it to existing import parsers.
|
||||
Args:
|
||||
book: xlrd workbook, used for the workbook date mode.
|
||||
cell: xlrd cell object.
|
||||
Returns:
|
||||
Python value close to what openpyxl returns for .xlsx.
|
||||
"""
|
||||
import xlrd
|
||||
|
||||
if cell.ctype == xlrd.XL_CELL_EMPTY:
|
||||
return None
|
||||
if cell.ctype == xlrd.XL_CELL_DATE:
|
||||
return xlrd.xldate_as_datetime(cell.value, book.datemode)
|
||||
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
|
||||
return int(cell.value)
|
||||
return cell.value
|
||||
|
||||
|
||||
def import_devices_from_excel(file_obj: Any, *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
从 Excel 模板导入设备台账。
|
||||
@@ -352,13 +448,8 @@ def import_devices_from_excel(file_obj: Any, *, operator: Any | None = None, req
|
||||
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
|
||||
filename = getattr(file_obj, 'filename', '') or ''
|
||||
wb = _load_import_workbook(file_obj, filename=filename)
|
||||
ws = wb.active
|
||||
headers = [str(cell.value or '').strip() for cell in ws[1]]
|
||||
missing = [name for name in ('设备编号', '设备名称') if name not in headers]
|
||||
|
||||
@@ -12,14 +12,17 @@ from datetime import date, datetime
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
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
|
||||
from app.path_utils import backend_dir
|
||||
from app.services.maintenance_ledger_service import _load_import_workbook, _operator_name, _parse_date, _write_audit
|
||||
|
||||
REPAIR_STATUS_VALUES = {'pending', 'processing', 'done', 'cancelled'}
|
||||
REPAIR_STATUS_LABELS = {
|
||||
@@ -29,6 +32,40 @@ REPAIR_STATUS_LABELS = {
|
||||
'cancelled': '已取消',
|
||||
}
|
||||
|
||||
RECORD_TEMPLATE_COLUMNS = [
|
||||
'设备编号',
|
||||
'报修日期',
|
||||
'故障描述',
|
||||
'维修类别',
|
||||
'维修状态',
|
||||
'维修日期',
|
||||
'维修单位',
|
||||
'维修人',
|
||||
'维修费用',
|
||||
'维修工时',
|
||||
'维修说明',
|
||||
'报修人',
|
||||
'审批人',
|
||||
'来源工单号',
|
||||
]
|
||||
|
||||
RECORD_HEADER_MAP = {
|
||||
'设备编号': 'device_code',
|
||||
'报修日期': 'report_date',
|
||||
'故障描述': 'fault_description',
|
||||
'维修类别': 'repair_category',
|
||||
'维修状态': 'repair_status',
|
||||
'维修日期': 'repair_date',
|
||||
'维修单位': 'repair_unit',
|
||||
'维修人': 'repairer',
|
||||
'维修费用': 'repair_cost',
|
||||
'维修工时': 'repair_hours',
|
||||
'维修说明': 'repair_description',
|
||||
'报修人': 'reporter',
|
||||
'审批人': 'approver',
|
||||
'来源工单号': 'source_order_no',
|
||||
}
|
||||
|
||||
|
||||
def _clean_text(value: Any) -> str | None:
|
||||
text = str(value or '').strip()
|
||||
@@ -150,8 +187,152 @@ def _records_query(*, keyword: str | None = None, device_code: str | None = None
|
||||
return query
|
||||
|
||||
|
||||
def _safe_sheet_title(value: str) -> str:
|
||||
"""生成 Excel Sheet 安全名称。"""
|
||||
title = str(value or '维修履历').strip() or '维修履历'
|
||||
for ch in r'[]:*?/\\':
|
||||
title = title.replace(ch, '-')
|
||||
return title[:31]
|
||||
|
||||
|
||||
def _format_date(value: date | None) -> str:
|
||||
"""格式化导出日期。"""
|
||||
return value.isoformat() if value else ''
|
||||
|
||||
|
||||
def _parse_cost(value: str | None) -> float:
|
||||
"""把维修费用字符串转为可合计金额。"""
|
||||
text = str(value or '').replace(',', '').strip()
|
||||
if not text:
|
||||
return 0.0
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError:
|
||||
return 0.0
|
||||
|
||||
|
||||
def _device_for_records(records: list[MaintenanceRecord]) -> MaintenanceDevice | None:
|
||||
"""根据维修记录关联的设备编号读取台账快照。"""
|
||||
code = str(records[0].device_code or '').strip() if records else ''
|
||||
if not code:
|
||||
return None
|
||||
return db.session.query(MaintenanceDevice).filter(MaintenanceDevice.device_code == code).first()
|
||||
|
||||
|
||||
def _fill_history_sheet(ws, records: list[MaintenanceRecord]) -> None:
|
||||
"""按设备维修保养履历模板填充单个 Sheet。"""
|
||||
device = _device_for_records(records)
|
||||
first = records[0] if records else None
|
||||
thin = Side(style='thin', color='000000')
|
||||
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
||||
header_fill = PatternFill(fill_type='solid', fgColor='D9EAF7')
|
||||
label_fill = PatternFill(fill_type='solid', fgColor='EAF2F8')
|
||||
note_fill = PatternFill(fill_type='solid', fgColor='F4CCCC')
|
||||
|
||||
ws.sheet_view.showGridLines = False
|
||||
widths = [8, 13, 16, 14, 14, 14, 14, 26]
|
||||
for idx, width in enumerate(widths, start=1):
|
||||
ws.column_dimensions[get_column_letter(idx)].width = width
|
||||
for row in range(1, 31):
|
||||
ws.row_dimensions[row].height = 24
|
||||
|
||||
ws.merge_cells('A1:H1')
|
||||
ws.merge_cells('A2:H2')
|
||||
ws.merge_cells('A3:H3')
|
||||
ws['A1'] = '和泰科技(浙江)有限公司'
|
||||
ws['A2'] = '惠州和宏智精密科技有限公司'
|
||||
ws['A3'] = '设备维修保养履历 表单编号:GL-001-00'
|
||||
for cell in ('A1', 'A2', 'A3'):
|
||||
ws[cell].font = Font(name='Microsoft YaHei', bold=True, size=12 if cell != 'A3' else 14)
|
||||
ws[cell].alignment = Alignment(horizontal='center', vertical='center')
|
||||
|
||||
info_rows = [
|
||||
('A4', '固定资产编号', 'C4', first.device_code if first else ''),
|
||||
('D4', '设备名称', 'F4', (device.device_name if device else None) or (first.device_name if first else '')),
|
||||
('A5', '设备型号', 'C5', (device.model_spec if device else None) or (first.model_spec if first else '')),
|
||||
('D5', '制造厂商', 'F5', device.manufacturer if device else ''),
|
||||
('A6', '安装地点', 'C6', (device.install_location if device else None) or (first.install_location if first else '')),
|
||||
('D6', '原值 / 残值', 'F6', f"{float(device.original_value):.2f} / {float(device.residual_value):.2f}" if device and device.original_value is not None and device.residual_value is not None else ''),
|
||||
]
|
||||
for label_cell, label, value_cell, value in info_rows:
|
||||
ws[label_cell] = label
|
||||
ws[value_cell] = value or ''
|
||||
ws[label_cell].fill = label_fill
|
||||
ws[label_cell].font = Font(name='Microsoft YaHei', bold=True)
|
||||
ws[value_cell].font = Font(name='Microsoft YaHei')
|
||||
|
||||
for merge_range in ('C4:C4', 'F4:H4', 'C5:C5', 'F5:H5', 'C6:C6', 'F6:H6'):
|
||||
ws.merge_cells(merge_range)
|
||||
for row in ws.iter_rows(min_row=4, max_row=6, min_col=1, max_col=8):
|
||||
for cell in row:
|
||||
cell.border = border
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
|
||||
|
||||
headers = ['序号', '日期', '故障内容', '维修内容', '维修费用', '维修人员', '维修方式', '备注']
|
||||
for col, header in enumerate(headers, start=1):
|
||||
cell = ws.cell(row=7, column=col, value=header)
|
||||
cell.fill = header_fill
|
||||
cell.font = Font(name='Microsoft YaHei', bold=True)
|
||||
cell.border = border
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
|
||||
|
||||
detail_start = 8
|
||||
detail_rows = max(12, len(records))
|
||||
total_cost = 0.0
|
||||
for index in range(detail_rows):
|
||||
row_no = detail_start + index
|
||||
record = records[index] if index < len(records) else None
|
||||
values = [
|
||||
index + 1 if record else '',
|
||||
_format_date(record.repair_date or record.report_date) if record else '',
|
||||
record.fault_description if record else '',
|
||||
record.repair_description or record.repair_category or REPAIR_STATUS_LABELS.get(record.repair_status, record.repair_status) if record else '',
|
||||
record.repair_cost if record else '',
|
||||
record.repairer if record else '',
|
||||
record.repair_unit if record else '',
|
||||
record.source_order_no or record.reporter or '' if record else '',
|
||||
]
|
||||
total_cost += _parse_cost(record.repair_cost if record else None)
|
||||
for col, value in enumerate(values, start=1):
|
||||
cell = ws.cell(row=row_no, column=col, value=value)
|
||||
cell.border = border
|
||||
cell.font = Font(name='Microsoft YaHei', size=10)
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
|
||||
ws.row_dimensions[row_no].height = 32
|
||||
|
||||
footer_row = detail_start + detail_rows
|
||||
ws.merge_cells(start_row=footer_row, start_column=1, end_row=footer_row, end_column=3)
|
||||
ws.cell(footer_row, 1, '故障维修需用红色字体备注')
|
||||
ws.cell(footer_row, 6, '合计:')
|
||||
ws.cell(footer_row, 7, total_cost)
|
||||
ws.cell(footer_row, 7).number_format = '#,##0.00'
|
||||
for col in range(1, 9):
|
||||
cell = ws.cell(footer_row, col)
|
||||
cell.border = border
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center')
|
||||
cell.font = Font(name='Microsoft YaHei', bold=col in (6, 7), color='C00000' if col == 1 else '000000')
|
||||
if col == 1:
|
||||
cell.fill = note_fill
|
||||
|
||||
sign_row = footer_row + 1
|
||||
labels = [('A', '标准'), ('D', '审核'), ('F', '制表人:'), ('G', '文新峰')]
|
||||
for col_letter, value in labels:
|
||||
cell = ws[f'{col_letter}{sign_row}']
|
||||
cell.value = value
|
||||
cell.font = Font(name='Microsoft YaHei', bold=col_letter in ('A', 'D', 'F'))
|
||||
cell.alignment = Alignment(horizontal='center', vertical='center')
|
||||
for col in range(1, 9):
|
||||
ws.cell(sign_row, col).border = border
|
||||
|
||||
ws.freeze_panes = 'A8'
|
||||
ws.page_setup.orientation = 'landscape'
|
||||
ws.page_setup.fitToWidth = 1
|
||||
ws.page_setup.fitToHeight = 0
|
||||
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
||||
|
||||
|
||||
def build_records_export(*, keyword: str | None = None, device_code: str | None = None, status: str | None = None) -> bytes:
|
||||
"""按当前筛选条件导出维修记录 Excel。"""
|
||||
"""按设备维修保养履历模板导出维修记录 Excel。"""
|
||||
rows = (
|
||||
_records_query(keyword=keyword, device_code=device_code, status=status)
|
||||
.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc())
|
||||
@@ -159,61 +340,296 @@ def build_records_export(*, keyword: str | None = None, device_code: str | None
|
||||
.all()
|
||||
)
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = '维修记录'
|
||||
headers = [
|
||||
'设备编号',
|
||||
'设备名称',
|
||||
'型号规格',
|
||||
'设备位置',
|
||||
'报修日期',
|
||||
'维修类别',
|
||||
'故障描述',
|
||||
'维修状态',
|
||||
'维修日期',
|
||||
'维修单位',
|
||||
'维修人',
|
||||
'维修费用',
|
||||
'维修工时',
|
||||
'维修说明',
|
||||
'报修人',
|
||||
'审批人',
|
||||
'来源工单号',
|
||||
]
|
||||
ws.append(headers)
|
||||
wb.remove(wb.active)
|
||||
if not rows:
|
||||
ws = wb.create_sheet('维修履历')
|
||||
_fill_history_sheet(ws, [])
|
||||
grouped: dict[str, list[MaintenanceRecord]] = {}
|
||||
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
|
||||
grouped.setdefault(item.device_code or '未编号设备', []).append(item)
|
||||
used_titles: set[str] = set()
|
||||
for code, records in grouped.items():
|
||||
base_title = _safe_sheet_title(code)
|
||||
title = base_title
|
||||
suffix = 1
|
||||
while title in used_titles:
|
||||
suffix += 1
|
||||
title = _safe_sheet_title(f'{base_title}-{suffix}')
|
||||
used_titles.add(title)
|
||||
ws = wb.create_sheet(title)
|
||||
_fill_history_sheet(ws, records)
|
||||
out = BytesIO()
|
||||
wb.save(out)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def build_records_import_template() -> bytes:
|
||||
"""读取维修履历导入模板,保持用户提供的 .xls 版式。"""
|
||||
template_path = backend_dir() / 'templates' / 'maintenance_record_history_template.xls'
|
||||
if not template_path.is_file():
|
||||
raise ValidationError('Maintenance record template file is missing')
|
||||
return template_path.read_bytes()
|
||||
|
||||
|
||||
def _cell_text(ws: Any, row: int, column: int) -> str | None:
|
||||
"""读取单元格文本,空值返回 None。"""
|
||||
return _clean_text(ws.cell(row=row, column=column).value)
|
||||
|
||||
|
||||
def _parse_history_pair_value(text: str | None, label: str) -> str | None:
|
||||
"""
|
||||
从履历模板中可能合并在同一格的“标签 值”文本里提取值。
|
||||
Args:
|
||||
text: 单元格文本。
|
||||
label: 要剥离的标签。
|
||||
Returns:
|
||||
标签后的值,若没有值则返回 None。
|
||||
"""
|
||||
raw = str(text or '').replace('\u3000', ' ').strip()
|
||||
if not raw:
|
||||
return None
|
||||
compact_label = ''.join(str(label or '').split())
|
||||
compact_raw = ''.join(raw.split())
|
||||
if compact_label and compact_raw.startswith(compact_label):
|
||||
return compact_raw[len(compact_label):].strip(' ::')
|
||||
return raw
|
||||
|
||||
|
||||
def _parse_history_date(value: Any) -> date | None:
|
||||
"""解析履历模板中的日期,兼容 Excel 序列号和常规日期字符串。"""
|
||||
if isinstance(value, (int, float)):
|
||||
try:
|
||||
import xlrd
|
||||
|
||||
return xlrd.xldate_as_datetime(float(value), 0).date()
|
||||
except Exception:
|
||||
return None
|
||||
return _parse_date(value, 'repairDate')
|
||||
|
||||
|
||||
def _is_history_template(ws: Any) -> bool:
|
||||
"""判断工作表是否为设备维修保养履历模板。"""
|
||||
device_code = _find_history_device_code(ws)
|
||||
if not device_code:
|
||||
return False
|
||||
# 老 .xls 可能存在中文编码异常,因此用固定版式特征识别:8 列以内、设备编号在上方、下方存在明细区。
|
||||
for row_no in range(6, min(ws.max_row, 10) + 1):
|
||||
first_cell = _cell_text(ws, row_no, 1)
|
||||
second_value = ws.cell(row=row_no, column=2).value
|
||||
third_cell = _cell_text(ws, row_no, 3)
|
||||
fourth_cell = _cell_text(ws, row_no, 4)
|
||||
if _looks_like_sequence(first_cell) and second_value not in (None, '') and (third_cell or fourth_cell):
|
||||
return True
|
||||
return ws.max_column <= 8 and ws.max_row >= 7
|
||||
|
||||
|
||||
def _looks_like_sequence(value: Any) -> bool:
|
||||
"""判断单元格是否像履历明细序号。"""
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
return False
|
||||
try:
|
||||
return float(text).is_integer()
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _find_history_device_code(ws: Any) -> str | None:
|
||||
"""从履历模板固定信息区读取设备编号,兼容有/无第一行公司名的版本。"""
|
||||
for row_no in (3, 4):
|
||||
code = _cell_text(ws, row_no, 3)
|
||||
if code:
|
||||
return code
|
||||
return None
|
||||
|
||||
|
||||
def _history_record_payloads(ws: Any) -> list[dict[str, Any]]:
|
||||
"""
|
||||
解析“设备维修保养履历”模板格式。
|
||||
Args:
|
||||
ws: openpyxl worksheet,来自 .xls 转换或 .xlsx 读取。
|
||||
Returns:
|
||||
可传给 _normalize_payload 的维修记录 payload 列表。
|
||||
Raises:
|
||||
ValidationError: 文件不是履历格式或缺少设备编号。
|
||||
"""
|
||||
device_code = _find_history_device_code(ws)
|
||||
info_row = 4 if _cell_text(ws, 4, 3) else 3
|
||||
device_name = _parse_history_pair_value(_cell_text(ws, info_row, 4), '设备名称')
|
||||
model_spec = _parse_history_pair_value(_cell_text(ws, info_row, 6), '型号')
|
||||
if not device_code:
|
||||
raise ValidationError('History template device code is required')
|
||||
|
||||
payloads: list[dict[str, Any]] = []
|
||||
for row_no in range(6, ws.max_row + 1):
|
||||
seq = _cell_text(ws, row_no, 1)
|
||||
raw_report_date = ws.cell(row=row_no, column=2).value
|
||||
fault_description = _cell_text(ws, row_no, 3)
|
||||
repair_description = _cell_text(ws, row_no, 4)
|
||||
raw_repair_date = ws.cell(row=row_no, column=5).value
|
||||
repair_unit = _cell_text(ws, row_no, 6)
|
||||
repair_cost = ws.cell(row=row_no, column=7).value
|
||||
remark = _cell_text(ws, row_no, 8)
|
||||
if not any([seq, raw_report_date, fault_description, repair_description, raw_repair_date, repair_cost, repair_unit, remark]):
|
||||
continue
|
||||
if not _looks_like_sequence(seq):
|
||||
continue
|
||||
if str(seq or '').strip() in {'合计', '标准'}:
|
||||
continue
|
||||
if not fault_description and not repair_description:
|
||||
continue
|
||||
report_date = _parse_history_date(raw_report_date) or date.today()
|
||||
repair_date = _parse_history_date(raw_repair_date) or report_date
|
||||
payloads.append(
|
||||
{
|
||||
'device_code': device_code,
|
||||
'report_date': report_date,
|
||||
'repair_date': repair_date,
|
||||
'fault_description': fault_description or repair_description,
|
||||
'repair_description': repair_description,
|
||||
'repair_cost': repair_cost,
|
||||
'repair_unit': repair_unit,
|
||||
'source_order_no': remark,
|
||||
'repair_status': 'done',
|
||||
'repair_category': '维修履历',
|
||||
'_device_name': device_name,
|
||||
'_model_spec': model_spec,
|
||||
'_row_no': row_no,
|
||||
}
|
||||
)
|
||||
return payloads
|
||||
|
||||
|
||||
def import_records_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 ''
|
||||
wb = _load_import_workbook(file_obj, filename=filename)
|
||||
ws = wb.active
|
||||
is_history_template = _is_history_template(ws)
|
||||
current_app.logger.info(
|
||||
'Maintenance record import workbook loaded filename=%s sheet=%s rows=%s cols=%s history_template=%s',
|
||||
filename,
|
||||
ws.title,
|
||||
ws.max_row,
|
||||
ws.max_column,
|
||||
is_history_template,
|
||||
)
|
||||
if is_history_template:
|
||||
return _import_history_records(ws, operator=operator, request_id=request_id)
|
||||
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 = {'total': 0, 'created': 0, 'failed': 0, '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 RECORD_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:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
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='import_create',
|
||||
before_data=None,
|
||||
after_data=_record_to_audit_dict(record),
|
||||
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 result
|
||||
|
||||
|
||||
def _import_history_records(ws: Any, *, operator: Any | None = None, request_id: str | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
按维修履历模板导入记录。
|
||||
Args:
|
||||
ws: 履历模板 worksheet。
|
||||
operator: 当前登录用户。
|
||||
request_id: 请求 ID。
|
||||
Returns:
|
||||
导入统计,维修记录只新增不覆盖。
|
||||
"""
|
||||
payloads = _history_record_payloads(ws)
|
||||
result = {'total': len(payloads), 'created': 0, 'failed': 0, 'errors': []}
|
||||
operator_name = _operator_name(operator)
|
||||
for raw in payloads:
|
||||
row_no = raw.pop('_row_no', None)
|
||||
device_name = raw.pop('_device_name', None)
|
||||
model_spec = raw.pop('_model_spec', None)
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
values = _normalize_payload(raw)
|
||||
device = db.session.query(MaintenanceDevice).filter_by(device_code=values['device_code']).first()
|
||||
if device:
|
||||
values.update(
|
||||
{
|
||||
'device_id': device.id,
|
||||
'device_name': device.device_name,
|
||||
'model_spec': device.model_spec,
|
||||
'install_location': device.install_location,
|
||||
}
|
||||
)
|
||||
else:
|
||||
values.update(
|
||||
{
|
||||
'device_name': device_name,
|
||||
'model_spec': model_spec,
|
||||
}
|
||||
)
|
||||
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='import_create',
|
||||
before_data=None,
|
||||
after_data=_record_to_audit_dict(record),
|
||||
operator_name=operator_name,
|
||||
request_id=request_id,
|
||||
)
|
||||
result['created'] += 1
|
||||
except Exception as exc:
|
||||
result['failed'] += 1
|
||||
result['errors'].append({'row': row_no or 0, 'message': str(getattr(exc, 'message', None) or exc)})
|
||||
db.session.commit()
|
||||
return result
|
||||
|
||||
|
||||
def get_record(record_id: int) -> dict[str, Any]:
|
||||
"""读取维修记录详情。"""
|
||||
record = db.session.get(MaintenanceRecord, record_id)
|
||||
|
||||
Binary file not shown.
@@ -260,13 +260,6 @@ watch(
|
||||
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"
|
||||
@@ -274,6 +267,13 @@ watch(
|
||||
>
|
||||
▦ {{ $t('maintenance.panel.ledgerTitle') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-brand-200 bg-brand-50 px-3 py-1 font-medium text-brand-700 transition-colors hover:bg-brand-100"
|
||||
@click="emit('maintenance-create-record')"
|
||||
>
|
||||
{{ $t('maintenance.panel.recordTitle') }}
|
||||
</button>
|
||||
<span>{{ $t('maintenance.panel.adminOnly') }}</span>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
* 逻辑:右侧固定面板通过本模块加载列表、保存设备、下载模板和导入 Excel。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
MaintenanceDevice,
|
||||
@@ -61,7 +62,26 @@ export const updateMaintenanceDevice = (id: number, payload: MaintenanceDevicePa
|
||||
});
|
||||
};
|
||||
|
||||
export const maintenanceLedgerImportTemplateUrl = `${API_BASE}/import-template`;
|
||||
export const downloadMaintenanceLedgerImportTemplate = async (): Promise<Blob> => {
|
||||
const res = await fetch(`${API_BASE}/import-template`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let message = `HTTP ${res.status}`;
|
||||
let code = 'SYSTEM.HTTP_ERROR';
|
||||
let requestId: string | undefined;
|
||||
try {
|
||||
const data = await res.json();
|
||||
message = data?.error?.message || data?.message || message;
|
||||
code = data?.error?.code || data?.code || code;
|
||||
requestId = data?.request_id;
|
||||
} catch {
|
||||
// 非 JSON 错误响应时保留 HTTP 状态即可。
|
||||
}
|
||||
throw new BusinessError({ message, code, requestId, status: res.status });
|
||||
}
|
||||
return res.blob();
|
||||
};
|
||||
|
||||
export const importMaintenanceDevices = (file: File) => {
|
||||
const form = new FormData();
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
* 依赖:shared/api/client、shared/utils/auth、record.types。
|
||||
* 逻辑:右侧固定面板通过本模块新增记录和查询最近记录;会话查询也可复用同一后端接口。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
MaintenanceRecord,
|
||||
MaintenanceRecordImportResult,
|
||||
MaintenanceRecordListResult,
|
||||
MaintenanceRecordPayload,
|
||||
} from '@/features/maintenance/types/record.types';
|
||||
@@ -83,3 +84,34 @@ export const exportMaintenanceRecords = async (params: ListMaintenanceRecordsPar
|
||||
}
|
||||
return response.blob();
|
||||
};
|
||||
|
||||
export const downloadMaintenanceRecordImportTemplate = async (): Promise<Blob> => {
|
||||
const response = await fetch(`${API_BASE}/import-template`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
let message = `HTTP ${response.status}`;
|
||||
let code = 'SYSTEM.HTTP_ERROR';
|
||||
let requestId: string | undefined;
|
||||
try {
|
||||
const data = await response.json();
|
||||
message = data?.error?.message || data?.message || message;
|
||||
code = data?.error?.code || data?.code || code;
|
||||
requestId = data?.request_id;
|
||||
} catch {
|
||||
// 非 JSON 错误响应时保留 HTTP 状态。
|
||||
}
|
||||
throw new BusinessError({ message, code, requestId, status: response.status });
|
||||
}
|
||||
return response.blob();
|
||||
};
|
||||
|
||||
export const importMaintenanceRecords = (file: File) => {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return requestJson<MaintenanceRecordImportResult>(`${API_BASE}/import`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: form,
|
||||
});
|
||||
};
|
||||
@@ -11,9 +11,9 @@ import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
createMaintenanceDevice,
|
||||
downloadMaintenanceLedgerImportTemplate,
|
||||
importMaintenanceDevices,
|
||||
listMaintenanceDevices,
|
||||
maintenanceLedgerImportTemplateUrl,
|
||||
updateMaintenanceDevice,
|
||||
} from '@/features/maintenance/api/maintenanceLedger.api';
|
||||
import type {
|
||||
@@ -31,6 +31,7 @@ const activeTab = ref<TabName>('list');
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const importing = ref(false);
|
||||
const downloadingTemplate = ref(false);
|
||||
const devices = ref<MaintenanceDevice[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
@@ -214,7 +215,7 @@ const saveDevice = async (): Promise<void> => {
|
||||
*/
|
||||
const validateImportFile = (file: File): boolean => {
|
||||
const fileName = file.name.toLowerCase();
|
||||
if (!fileName.endsWith('.xlsx')) {
|
||||
if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
|
||||
msg.warning(t('maintenance.ledger.messages.invalidFormat'));
|
||||
return false;
|
||||
}
|
||||
@@ -225,6 +226,29 @@ const validateImportFile = (file: File): boolean => {
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 下载设备台账导入模板。
|
||||
* 核心逻辑:通过 fetch 携带认证头获取 Blob,避免浏览器新开页面时因缺少鉴权跳转到错误 JSON。
|
||||
*/
|
||||
const downloadTemplate = async (): Promise<void> => {
|
||||
downloadingTemplate.value = true;
|
||||
try {
|
||||
const blob = await downloadMaintenanceLedgerImportTemplate();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'maintenance_devices_import_template.xlsx';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.ledger.messages.downloadTemplateFailed'));
|
||||
} finally {
|
||||
downloadingTemplate.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 上传 Excel 模板并导入设备台账。
|
||||
* @param event - 文件选择事件。
|
||||
@@ -299,12 +323,12 @@ onMounted(loadDevices);
|
||||
<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>
|
||||
<button type="button" class="admin-report-page-btn" :disabled="downloadingTemplate" @click="downloadTemplate">
|
||||
{{ downloadingTemplate ? t('maintenance.ledger.actions.downloadingTemplate') : t('maintenance.ledger.actions.downloadTemplate') }}
|
||||
</button>
|
||||
<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" />
|
||||
<input type="file" class="hidden" accept=".xls,.xlsx" :disabled="importing" @change="onImportFileChange" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -7,19 +7,23 @@
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { listMaintenanceDevices } from '@/features/maintenance/api/maintenanceLedger.api';
|
||||
import {
|
||||
createMaintenanceRecord,
|
||||
deleteMaintenanceRecord,
|
||||
downloadMaintenanceRecordImportTemplate,
|
||||
exportMaintenanceRecords,
|
||||
importMaintenanceRecords,
|
||||
listMaintenanceRecords,
|
||||
updateMaintenanceRecord,
|
||||
} from '@/features/maintenance/api/maintenanceRecord.api';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type {
|
||||
MaintenanceRecord,
|
||||
MaintenanceRecordImportResult,
|
||||
MaintenanceRecordPayload,
|
||||
MaintenanceRepairStatus,
|
||||
} from '@/features/maintenance/types/record.types';
|
||||
@@ -34,6 +38,8 @@ const saving = ref(false);
|
||||
const deviceLoading = ref(false);
|
||||
const deletingId = ref<number | null>(null);
|
||||
const exporting = ref(false);
|
||||
const importing = ref(false);
|
||||
const downloadingTemplate = ref(false);
|
||||
const records = ref<MaintenanceRecord[]>([]);
|
||||
const matchedDevice = ref<MaintenanceDevice | null>(null);
|
||||
const total = ref(0);
|
||||
@@ -42,7 +48,11 @@ const pageSize = ref(10);
|
||||
const keyword = ref('');
|
||||
const status = ref('');
|
||||
const editingId = ref<number | null>(null);
|
||||
const importResult = ref<MaintenanceRecordImportResult | null>(null);
|
||||
const deleteDialogOpen = ref(false);
|
||||
const pendingDeleteRecord = ref<MaintenanceRecord | null>(null);
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const MAX_IMPORT_FILE_SIZE = 10 * 1024 * 1024;
|
||||
|
||||
const form = reactive<MaintenanceRecordPayload>({
|
||||
deviceCode: '',
|
||||
@@ -70,6 +80,11 @@ const statusOptions: Array<{ value: MaintenanceRepairStatus | ''; label: string
|
||||
];
|
||||
|
||||
const formTitle = computed(() => t(editingId.value ? 'maintenance.record.formTitle.edit' : 'maintenance.record.formTitle.create'));
|
||||
const deleteConfirmMessage = computed(() =>
|
||||
pendingDeleteRecord.value
|
||||
? t('maintenance.record.messages.deleteConfirm', { deviceCode: pendingDeleteRecord.value.deviceCode })
|
||||
: ''
|
||||
);
|
||||
|
||||
/**
|
||||
* 将维修状态枚举转为中文展示。
|
||||
@@ -149,6 +164,69 @@ const exportRecords = async (): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Validate maintenance record import file before uploading it to the backend parser.
|
||||
* @param file - Excel file selected by the administrator.
|
||||
* @returns Whether the file is allowed to upload.
|
||||
*/
|
||||
const validateImportFile = (file: File): boolean => {
|
||||
const fileName = file.name.toLowerCase();
|
||||
if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
|
||||
msg.warning(t('maintenance.record.messages.invalidFormat'));
|
||||
return false;
|
||||
}
|
||||
if (file.size > MAX_IMPORT_FILE_SIZE) {
|
||||
msg.warning(t('maintenance.record.messages.fileTooLarge'));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Download the maintenance record import template with auth headers and keep failures in-page.
|
||||
*/
|
||||
const downloadTemplate = async (): Promise<void> => {
|
||||
downloadingTemplate.value = true;
|
||||
try {
|
||||
const blob = await downloadMaintenanceRecordImportTemplate();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'maintenance_record_history_template.xls';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.downloadTemplateFailed'));
|
||||
} finally {
|
||||
downloadingTemplate.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Upload an Excel file and create maintenance records in batch.
|
||||
* @param event - File picker change 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 importMaintenanceRecords(file);
|
||||
msg.success(t('maintenance.record.messages.importDone'));
|
||||
page.value = 1;
|
||||
await loadRecords();
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.importFailed'));
|
||||
} finally {
|
||||
importing.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 查询设备台账快照,帮助管理员确认维修记录归属。
|
||||
*/
|
||||
@@ -259,12 +337,22 @@ const saveRecord = async (): Promise<void> => {
|
||||
* 删除维修记录。
|
||||
* @param record - 待删除的维修记录。
|
||||
*/
|
||||
const removeRecord = async (record: MaintenanceRecord): Promise<void> => {
|
||||
if (!window.confirm(t('maintenance.record.messages.deleteConfirm', { deviceCode: record.deviceCode }))) return;
|
||||
const openDeleteDialog = (record: MaintenanceRecord): void => {
|
||||
pendingDeleteRecord.value = record;
|
||||
deleteDialogOpen.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 确认删除维修记录。
|
||||
*/
|
||||
const confirmRemoveRecord = async (): Promise<void> => {
|
||||
const record = pendingDeleteRecord.value;
|
||||
if (!record) return;
|
||||
deletingId.value = record.id;
|
||||
try {
|
||||
await deleteMaintenanceRecord(record.id);
|
||||
msg.success(t('maintenance.record.messages.deleted'));
|
||||
pendingDeleteRecord.value = null;
|
||||
await loadRecords();
|
||||
} catch (error: any) {
|
||||
msg.error(error?.message || t('maintenance.record.messages.deleteFailed'));
|
||||
@@ -273,6 +361,10 @@ const removeRecord = async (record: MaintenanceRecord): Promise<void> => {
|
||||
}
|
||||
};
|
||||
|
||||
const cancelDeleteDialog = (): void => {
|
||||
pendingDeleteRecord.value = null;
|
||||
};
|
||||
|
||||
onMounted(loadRecords);
|
||||
</script>
|
||||
|
||||
@@ -325,11 +417,27 @@ onMounted(loadRecords);
|
||||
<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="downloadingTemplate" @click="downloadTemplate">
|
||||
{{ downloadingTemplate ? t('maintenance.record.actions.downloadingTemplate') : t('maintenance.record.actions.downloadTemplate') }}
|
||||
</button>
|
||||
<label class="admin-report-page-btn cursor-pointer" :class="{ 'opacity-60': importing }">
|
||||
{{ importing ? t('maintenance.record.actions.importing') : t('maintenance.record.actions.importExcel') }}
|
||||
<input type="file" class="hidden" accept=".xls,.xlsx" :disabled="importing" @change="onImportFileChange" />
|
||||
</label>
|
||||
<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 v-if="importResult" class="rounded-xl border border-default bg-surface px-3 py-2 text-sm">
|
||||
{{ t('maintenance.record.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.record.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">
|
||||
@@ -364,7 +472,7 @@ onMounted(loadRecords);
|
||||
type="button"
|
||||
class="admin-report-page-btn"
|
||||
:disabled="deletingId === record.id"
|
||||
@click="removeRecord(record)"
|
||||
@click="openDeleteDialog(record)"
|
||||
>
|
||||
{{ deletingId === record.id ? t('maintenance.record.actions.deleting') : t('maintenance.record.actions.delete') }}
|
||||
</button>
|
||||
@@ -480,5 +588,13 @@ onMounted(loadRecords);
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="deleteDialogOpen"
|
||||
:message="deleteConfirmMessage"
|
||||
:confirm-loading="deletingId !== null"
|
||||
@confirm="confirmRemoveRecord"
|
||||
@cancel="cancelDeleteDialog"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -54,3 +54,10 @@ export interface MaintenanceRecordListResult {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface MaintenanceRecordImportResult {
|
||||
total: number;
|
||||
created: number;
|
||||
failed: number;
|
||||
errors: Array<{ row: number; message: string }>;
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
"search": "Search",
|
||||
"create": "Add Equipment",
|
||||
"downloadTemplate": "Download Template",
|
||||
"downloadingTemplate": "Downloading...",
|
||||
"importExcel": "Import Excel",
|
||||
"importing": "Importing...",
|
||||
"edit": "Edit",
|
||||
@@ -67,10 +68,11 @@
|
||||
"saved": "Equipment ledger saved",
|
||||
"saveFailed": "Failed to save equipment ledger",
|
||||
"loadFailed": "Failed to load equipment ledger",
|
||||
"invalidFormat": "Please upload a .xlsx equipment ledger template",
|
||||
"invalidFormat": "Please upload a .xls or .xlsx equipment ledger template",
|
||||
"fileTooLarge": "The equipment ledger file cannot exceed 10MB",
|
||||
"importDone": "Equipment ledger import completed",
|
||||
"importFailed": "Failed to import equipment ledger"
|
||||
"importFailed": "Failed to import equipment ledger",
|
||||
"downloadTemplateFailed": "Failed to download equipment ledger template"
|
||||
},
|
||||
"importResult": "Import result: {total} rows, {created} created, {updated} updated, {failed} failed.",
|
||||
"importErrorRow": "Row {row}: {message}"
|
||||
@@ -108,6 +110,10 @@
|
||||
"create": "Add Record",
|
||||
"export": "Export",
|
||||
"exporting": "Exporting...",
|
||||
"downloadTemplate": "Download Template",
|
||||
"downloadingTemplate": "Downloading...",
|
||||
"importExcel": "Import",
|
||||
"importing": "Importing...",
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"deleting": "Deleting...",
|
||||
@@ -160,10 +166,17 @@
|
||||
"status": "Status",
|
||||
"empty": "Enter an equipment code to match an equipment ledger snapshot automatically."
|
||||
},
|
||||
"importResult": "Import result: {total} rows, {created} created, {failed} failed.",
|
||||
"importErrorRow": "Row {row}: {message}",
|
||||
"messages": {
|
||||
"loadFailed": "Failed to query maintenance records",
|
||||
"exported": "Maintenance records exported",
|
||||
"exportFailed": "Failed to export maintenance records",
|
||||
"invalidFormat": "Please upload a .xls or .xlsx maintenance record template",
|
||||
"fileTooLarge": "Maintenance record file cannot exceed 10MB",
|
||||
"importDone": "Maintenance records imported",
|
||||
"importFailed": "Failed to import maintenance records",
|
||||
"downloadTemplateFailed": "Failed to download maintenance record template",
|
||||
"deviceLoadFailed": "Failed to query equipment ledger",
|
||||
"required": "Equipment code, report date, and fault description are required",
|
||||
"updated": "Maintenance record updated",
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"search": "ค้นหา",
|
||||
"create": "เพิ่มอุปกรณ์",
|
||||
"downloadTemplate": "ดาวน์โหลดเทมเพลต",
|
||||
"downloadingTemplate": "กำลังดาวน์โหลด...",
|
||||
"importExcel": "นำเข้า Excel",
|
||||
"importing": "กำลังนำเข้า...",
|
||||
"edit": "แก้ไข",
|
||||
@@ -67,10 +68,11 @@
|
||||
"saved": "บันทึกทะเบียนอุปกรณ์แล้ว",
|
||||
"saveFailed": "บันทึกทะเบียนอุปกรณ์ไม่สำเร็จ",
|
||||
"loadFailed": "โหลดทะเบียนอุปกรณ์ไม่สำเร็จ",
|
||||
"invalidFormat": "โปรดอัปโหลดเทมเพลตทะเบียนอุปกรณ์รูปแบบ .xlsx",
|
||||
"invalidFormat": "โปรดอัปโหลดเทมเพลตทะเบียนอุปกรณ์รูปแบบ .xls หรือ .xlsx",
|
||||
"fileTooLarge": "ไฟล์ทะเบียนอุปกรณ์ต้องไม่เกิน 10MB",
|
||||
"importDone": "นำเข้าทะเบียนอุปกรณ์เสร็จสิ้น",
|
||||
"importFailed": "นำเข้าทะเบียนอุปกรณ์ไม่สำเร็จ"
|
||||
"importFailed": "นำเข้าทะเบียนอุปกรณ์ไม่สำเร็จ",
|
||||
"downloadTemplateFailed": "ดาวน์โหลดเทมเพลตทะเบียนอุปกรณ์ไม่สำเร็จ"
|
||||
},
|
||||
"importResult": "ผลการนำเข้า: ทั้งหมด {total} รายการ, เพิ่ม {created}, อัปเดต {updated}, ล้มเหลว {failed}",
|
||||
"importErrorRow": "แถว {row}: {message}"
|
||||
@@ -108,6 +110,10 @@
|
||||
"create": "เพิ่มบันทึก",
|
||||
"export": "ส่งออก",
|
||||
"exporting": "กำลังส่งออก...",
|
||||
"downloadTemplate": "ดาวน์โหลดเทมเพลต",
|
||||
"downloadingTemplate": "กำลังดาวน์โหลด...",
|
||||
"importExcel": "นำเข้า",
|
||||
"importing": "กำลังนำเข้า...",
|
||||
"edit": "แก้ไข",
|
||||
"delete": "ลบ",
|
||||
"deleting": "กำลังลบ...",
|
||||
@@ -160,10 +166,17 @@
|
||||
"status": "สถานะ",
|
||||
"empty": "กรอกรหัสอุปกรณ์เพื่อจับคู่ข้อมูลทะเบียนอุปกรณ์อัตโนมัติ"
|
||||
},
|
||||
"importResult": "ผลการนำเข้า: ทั้งหมด {total} รายการ, เพิ่ม {created}, ล้มเหลว {failed}",
|
||||
"importErrorRow": "แถว {row}: {message}",
|
||||
"messages": {
|
||||
"loadFailed": "ค้นหาบันทึกซ่อมบำรุงไม่สำเร็จ",
|
||||
"exported": "ส่งออกบันทึกซ่อมบำรุงแล้ว",
|
||||
"exportFailed": "ส่งออกบันทึกซ่อมบำรุงไม่สำเร็จ",
|
||||
"invalidFormat": "โปรดอัปโหลดเทมเพลตบันทึกซ่อมบำรุงรูปแบบ .xls หรือ .xlsx",
|
||||
"fileTooLarge": "ไฟล์บันทึกซ่อมบำรุงต้องไม่เกิน 10MB",
|
||||
"importDone": "นำเข้าบันทึกซ่อมบำรุงแล้ว",
|
||||
"importFailed": "นำเข้าบันทึกซ่อมบำรุงไม่สำเร็จ",
|
||||
"downloadTemplateFailed": "ดาวน์โหลดเทมเพลตบันทึกซ่อมบำรุงไม่สำเร็จ",
|
||||
"deviceLoadFailed": "ค้นหาทะเบียนอุปกรณ์ไม่สำเร็จ",
|
||||
"required": "ต้องระบุรหัสอุปกรณ์ วันที่แจ้งซ่อม และรายละเอียดปัญหา",
|
||||
"updated": "อัปเดตบันทึกซ่อมบำรุงแล้ว",
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"search": "查询",
|
||||
"create": "新增设备",
|
||||
"downloadTemplate": "下载模板",
|
||||
"downloadingTemplate": "下载中...",
|
||||
"importExcel": "导入 Excel",
|
||||
"importing": "导入中...",
|
||||
"edit": "编辑",
|
||||
@@ -67,10 +68,11 @@
|
||||
"saved": "设备台账已保存",
|
||||
"saveFailed": "保存设备台账失败",
|
||||
"loadFailed": "加载设备台账失败",
|
||||
"invalidFormat": "请上传 .xlsx 格式的设备台账模板",
|
||||
"invalidFormat": "请上传 .xls 或 .xlsx 格式的设备台账模板",
|
||||
"fileTooLarge": "设备台账文件不能超过 10MB",
|
||||
"importDone": "设备台账导入完成",
|
||||
"importFailed": "导入设备台账失败"
|
||||
"importFailed": "导入设备台账失败",
|
||||
"downloadTemplateFailed": "下载设备台账模板失败"
|
||||
},
|
||||
"importResult": "导入结果:共 {total} 条,新增 {created} 条,更新 {updated} 条,失败 {failed} 条。",
|
||||
"importErrorRow": "第 {row} 行:{message}"
|
||||
@@ -108,6 +110,10 @@
|
||||
"create": "新增维修记录",
|
||||
"export": "导出",
|
||||
"exporting": "导出中...",
|
||||
"downloadTemplate": "下载模板",
|
||||
"downloadingTemplate": "下载中...",
|
||||
"importExcel": "导入",
|
||||
"importing": "导入中...",
|
||||
"edit": "编辑",
|
||||
"delete": "删除",
|
||||
"deleting": "删除中...",
|
||||
@@ -160,10 +166,17 @@
|
||||
"status": "状态",
|
||||
"empty": "输入设备编号后可自动匹配设备台账快照。"
|
||||
},
|
||||
"importResult": "导入结果:共 {total} 条,新增 {created} 条,失败 {failed} 条。",
|
||||
"importErrorRow": "第 {row} 行:{message}",
|
||||
"messages": {
|
||||
"loadFailed": "查询维修记录失败",
|
||||
"exported": "维修记录已导出",
|
||||
"exportFailed": "导出维修记录失败",
|
||||
"invalidFormat": "请上传 .xls 或 .xlsx 格式的维修记录模板",
|
||||
"fileTooLarge": "维修记录文件不能超过 10MB",
|
||||
"importDone": "维修记录导入完成",
|
||||
"importFailed": "导入维修记录失败",
|
||||
"downloadTemplateFailed": "下载维修记录模板失败",
|
||||
"deviceLoadFailed": "查询设备台账失败",
|
||||
"required": "设备编号、报修日期和故障描述不能为空",
|
||||
"updated": "维修记录已更新",
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"search": "查詢",
|
||||
"create": "新增設備",
|
||||
"downloadTemplate": "下載範本",
|
||||
"downloadingTemplate": "下載中...",
|
||||
"importExcel": "匯入 Excel",
|
||||
"importing": "匯入中...",
|
||||
"edit": "編輯",
|
||||
@@ -67,10 +68,11 @@
|
||||
"saved": "設備台帳已儲存",
|
||||
"saveFailed": "儲存設備台帳失敗",
|
||||
"loadFailed": "載入設備台帳失敗",
|
||||
"invalidFormat": "請上傳 .xlsx 格式的設備台帳範本",
|
||||
"invalidFormat": "請上傳 .xls 或 .xlsx 格式的設備台帳範本",
|
||||
"fileTooLarge": "設備台帳檔案不能超過 10MB",
|
||||
"importDone": "設備台帳匯入完成",
|
||||
"importFailed": "匯入設備台帳失敗"
|
||||
"importFailed": "匯入設備台帳失敗",
|
||||
"downloadTemplateFailed": "下載設備台帳範本失敗"
|
||||
},
|
||||
"importResult": "匯入結果:共 {total} 筆,新增 {created} 筆,更新 {updated} 筆,失敗 {failed} 筆。",
|
||||
"importErrorRow": "第 {row} 行:{message}"
|
||||
@@ -108,6 +110,10 @@
|
||||
"create": "新增維修記錄",
|
||||
"export": "匯出",
|
||||
"exporting": "匯出中...",
|
||||
"downloadTemplate": "下載範本",
|
||||
"downloadingTemplate": "下載中...",
|
||||
"importExcel": "匯入",
|
||||
"importing": "匯入中...",
|
||||
"edit": "編輯",
|
||||
"delete": "刪除",
|
||||
"deleting": "刪除中...",
|
||||
@@ -160,10 +166,17 @@
|
||||
"status": "狀態",
|
||||
"empty": "輸入設備編號後可自動匹配設備台帳快照。"
|
||||
},
|
||||
"importResult": "匯入結果:共 {total} 筆,新增 {created} 筆,失敗 {failed} 筆。",
|
||||
"importErrorRow": "第 {row} 行:{message}",
|
||||
"messages": {
|
||||
"loadFailed": "查詢維修記錄失敗",
|
||||
"exported": "維修記錄已匯出",
|
||||
"exportFailed": "匯出維修記錄失敗",
|
||||
"invalidFormat": "請上傳 .xls 或 .xlsx 格式的維修記錄範本",
|
||||
"fileTooLarge": "維修記錄檔案不能超過 10MB",
|
||||
"importDone": "維修記錄匯入完成",
|
||||
"importFailed": "匯入維修記錄失敗",
|
||||
"downloadTemplateFailed": "下載維修記錄範本失敗",
|
||||
"deviceLoadFailed": "查詢設備台帳失敗",
|
||||
"required": "設備編號、報修日期和故障描述不能為空",
|
||||
"updated": "維修記錄已更新",
|
||||
|
||||
Binary file not shown.
Reference in new issue
Block a user