515 lines
19 KiB
Python
515 lines
19 KiB
Python
"""
|
|
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 _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 模板导入设备台账。
|
|
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
|
|
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 [],
|
|
}
|