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