Merge pull request 'fix: BOM 导入提示忽略列及近义表头(#33 D5)' (#38) from codex/issue33-d5 into main
Core regression / Python core, intervention UI and release configuration (push) Successful in 6m4s
Core regression / JavaScript syntax (push) Successful in 7s

This commit was merged in pull request #38.
This commit is contained in:
abaishu0730 committed 2026-11-25 11:00:58 +08:00
commit 22442e03ae
8 files changed
+191 -23

No files matched your search

@@ -48,6 +48,7 @@ class BomImportReport:
source_map_path: Path | None = None
passed_preview: BomBatchPreview | None = None
deferred: bool = False
warnings: tuple[str, ...] = ()
@property
def total_rows(self):
@@ -77,7 +77,9 @@ def resolution_binding(store, task_id):
def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=None, on_phase=None, allow_partial=False):
"""Persist routed spreadsheet requests without opening CAD or resolving parts."""
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, allow_partial=allow_partial)
warnings = []
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
allow_partial=allow_partial, warnings=warnings)
scope = _scope(service._store, task_id)
paths = tuple(project.path for _, project in scope)
names = {project.path: task.name for task, project in scope}
@@ -93,7 +95,8 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
write_routed_bom(normalized, rows, routes, project_names=names)
append_task_event(service._logging, level='INFO', task_id=task_id,
operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验',
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
'warnings': warnings})
try:
report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress,
on_phase=on_phase, spreadsheet_only=True, allow_partial=allow_partial)
@@ -110,7 +113,7 @@ def import_drafts(service, task_id, sources, *, stop_event=None, on_progress=Non
if report.deferred and result.project_path not in failed_paths:
reason = '表格已保存,执行前核验工程位号'
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=reason))
report = replace(report, rows=tuple(annotated), source_map_path=mapping)
report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
if report.deferred:
accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True)
if result.project_path not in failed_paths)
@@ -245,7 +245,8 @@ class TaskCenterService:
on_phase(BomImportPhase.READING, message)
if on_progress is not None:
on_progress(message)
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress,
warnings = []
rows = load_sources(sources, stop_event=stop_event, on_progress=on_progress, warnings=warnings,
**({'allow_partial': True} if allow_partial else {}))
scope = _scope(self._store, task_id)
paths = tuple(project.path for _, project in scope)
@@ -278,7 +279,7 @@ class TaskCenterService:
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row,
reason=reason + f';来源:{source.source} 第 {source.excel_row} 行'))
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping)
annotated_report = replace(report, rows=tuple(annotated), source_map_path=mapping, warnings=tuple(warnings))
return bind_source_report(annotated_report,
tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping)
@@ -290,7 +291,8 @@ class TaskCenterService:
write_routed_bom(normalized, rows, routes, project_names=names)
append_task_event(self._logging, level='INFO', task_id=task_id,
operation='preview_bom_sources', message='BOM 导入来源记录已保存',
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows})})
details={'source_map_path': str(mapping), 'source_count': len({row.source for row in rows}),
'warnings': warnings})
report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime,
**({'allow_partial': True} if allow_partial else {}))
@@ -787,21 +787,22 @@ class ProjectPlanPanel(QWidget):
report = state.report
if report is None:
return '', '', ''
warning_summary = f' · 警告 {len(report.warnings)} 项' if report.warnings else ''
if report.deferred:
failed_paths = {row.project_path for row in report.rows if row.status == 'failed'}
accepted = tuple(row for row in report.rows if row.project_path not in failed_paths)
summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、'
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行。')
details = [summary, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行{warning_summary}。')
details = [summary, *report.warnings, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}'
for row in report.rows)
return summary, '\n'.join(details), 'BOM 已保存 · 待核验 · 详情'
return summary, '\n'.join(details), f'BOM 已保存 · 待核验{warning_summary} · 详情'
outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过'
summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、'
f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;'
f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、'
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个。')
details = [summary, *report.errors]
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个{warning_summary}。')
details = [summary, *report.errors, *report.warnings]
if report.source_map_path is not None:
details.append(f'导入来源记录:{report.source_map_path}')
details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}'
@@ -1,11 +1,13 @@
"""Safe multi-file BOM loading and project routing for workspace imports."""
from dataclasses import dataclass
from difflib import get_close_matches
import hashlib
from pathlib import Path, PureWindowsPath
from openpyxl import load_workbook
from .bom_import_report import BomImportReport, BomInspectionError
from .bom_plan import BOM_HEADERS, _normal_headers, _part_number_text, write_bom_template
from .errors import TaskCenterError
@@ -55,7 +57,37 @@ def _selected_xlsx(sources):
return tuple(sorted(paths, key=lambda path: str(path).casefold()))
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False):
_REQUIRED_HEADERS = (
('old_part_number', '旧料号'), ('new_part_number', '新料号'), ('refdes', '位号'),
)
def _source_headers(path, cells):
headers = _normal_headers(tuple(cell.value for cell in cells))
names = tuple(name for name in headers if name)
unknown = tuple(str(cell.value).strip() for cell, name in zip(cells, headers, strict=True)
if not name and cell.value is not None and str(cell.value).strip())
if any(cell.data_type == 'f' for cell in cells):
reason = 'BOM 表头不接受公式'
elif len(names) != len(set(names)):
reason = 'BOM 列名重复'
else:
missing = [(name, label) for name, label in _REQUIRED_HEADERS if name not in names]
if not missing:
return {name: index for index, name in enumerate(headers) if name}, unknown
labels = '、'.join(label for _, label in missing)
hints = []
for name, label in missing:
matches = (get_close_matches(label, unknown, n=1, cutoff=.7)
or get_close_matches(name, unknown, n=1, cutoff=.8))
if matches:
hints.append(f'请将「{matches[0]}」改为「{label}」')
reason = '。'.join([f'BOM 缺少必需列「{labels}」', *hints])
message = f'{path.name} 第 1 行:{reason}'
raise BomInspectionError(TaskCenterError('bom_import', message), BomImportReport((), (), errors=(message,)))
def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=False, warnings=None):
"""Read every selected workbook before any CAD operation starts."""
from .operation_control import check_cancelled
@@ -74,17 +106,7 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
if len(workbook.worksheets) != 1:
raise ValueError('BOM 只能包含一个工作表')
rows = iter(workbook.active.iter_rows())
header_cells = next(rows, ())
headers = _normal_headers(tuple(cell.value for cell in header_cells))
names = tuple(name for name in headers if name)
if len(names) != len(set(names)):
raise ValueError('BOM 列名重复')
required = {'old_part_number', 'new_part_number', 'refdes'}
if not required <= set(names):
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
if any(cell.data_type == 'f' for cell in header_cells):
raise ValueError('BOM 表头不接受公式')
positions = {name: index for index, name in enumerate(headers) if name}
positions, unknown = _source_headers(path, next(rows, ()))
for excel_row, cells in enumerate(rows, 2):
check_cancelled(stop_event)
formula = any(cell.data_type == 'f' for cell in cells)
@@ -116,6 +138,8 @@ def load_sources(sources, *, stop_event=None, on_progress=None, allow_partial=Fa
result.append(SourceRow(path, excel_row, values, value_mode, source_sha256))
if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256:
raise ValueError('BOM 来源在读取期间已改变,请重新导入')
if warnings is not None:
warnings.extend(f'{path.name}:已忽略未知列「{name}」' for name in unknown)
except TaskCenterError:
raise
except Exception as error: