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
@@ -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.
Reference in new issue
Block a user