fix(bom): reject lossy non-text part numbers
This commit is contained in:
1 parent
bc36289059
commit
ba4c328b2f
3 files changed
+149
-5
No files matched your search
@@ -70,8 +70,16 @@ def write_bom_template(path: Path, records=()) -> Path:
|
||||
'H': 28, 'I': 12, 'J': 24, 'K': 12}.items():
|
||||
sheet.column_dimensions[column].width = width
|
||||
sheet.column_dimensions[column].alignment = wrapped
|
||||
writable_last_row = max(2, sheet.max_row)
|
||||
for column in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J'):
|
||||
sheet.column_dimensions[column].number_format = '@'
|
||||
# Existing cell styles override column defaults in Excel. Format the
|
||||
# scaffold (or first editing row) explicitly to preserve zeroes without
|
||||
# expanding the workbook's used area with empty formatted rows.
|
||||
for row_number in range(2, writable_last_row + 1):
|
||||
cell = sheet[f'{column}{row_number}']
|
||||
cell.number_format = '@'
|
||||
cell.alignment = wrapped
|
||||
path = Path(path)
|
||||
workbook.save(path)
|
||||
return path
|
||||
@@ -110,8 +118,11 @@ def read_bom_records(path: Path) -> tuple[BomRecord, ...]:
|
||||
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
|
||||
positions = {name: index for index, name in enumerate(headers) if name}
|
||||
result = []
|
||||
for cells in records[1:]:
|
||||
record = parse_bom_row(cells, positions)
|
||||
for number, cells in enumerate(records[1:], 2):
|
||||
try:
|
||||
record = parse_bom_row(cells, positions)
|
||||
except (ValueError, TypeError) as error:
|
||||
raise ValueError(f'Excel 第 {number} 行:{error}') from error
|
||||
if record is not None:
|
||||
result.append(record)
|
||||
return tuple(result)
|
||||
@@ -130,8 +141,8 @@ def parse_bom_row(cells, positions):
|
||||
return None
|
||||
if any(cell.data_type == 'f' for cell in cells):
|
||||
raise ValueError('BOM 不接受公式,请填写实际值')
|
||||
old = _text(values, positions, 'old_part_number')
|
||||
new = _text(values, positions, 'new_part_number')
|
||||
old = _part_number_text(cells, positions, 'old_part_number', '旧料号')
|
||||
new = _part_number_text(cells, positions, 'new_part_number', '新料号')
|
||||
refs = _split_refdes(_text(values, positions, 'refdes'))
|
||||
if not old and not new and not refs and not _text(values, positions, 'custom_value'):
|
||||
return None # An untouched project row is a scaffold, not a rule.
|
||||
@@ -224,6 +235,19 @@ def _text(values, positions, name):
|
||||
return '' if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _part_number_text(cells, positions, name, label):
|
||||
index = positions.get(name)
|
||||
if index is None or index >= len(cells):
|
||||
return ''
|
||||
cell = cells[index]
|
||||
value = cell.value
|
||||
if value is None:
|
||||
return ''
|
||||
if not isinstance(value, str) or cell.data_type not in {'s', 'inlineStr'}:
|
||||
raise ValueError(f'BOM {label}必须按文本填写,不能使用数值、日期、布尔或错误单元格')
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _split_refdes(value):
|
||||
return tuple(item for item in _REFDES_SPLIT.split(value.strip()) if item)
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from dx_productivity.trial_task_center.bom_plan import read_bom_records, write_bom_template
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_task(tmp_path, monkeypatch):
|
||||
project = tmp_path / 'board.prj'
|
||||
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
task = service.create_project_tasks(tmp_path, selected_paths=(project,))[0]
|
||||
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '')
|
||||
for i in (1, 2, 3))
|
||||
def forbidden_inventory(*args, **controls):
|
||||
raise AssertionError('BOM type validation must finish before external inventory collection')
|
||||
|
||||
# No malformed workbook may start the external CAD/native reader.
|
||||
monkeypatch.setattr(service.for_project_task(task.task_id)._quick_run_preparer,
|
||||
'collect_inventory', forbidden_inventory)
|
||||
store.record_target_inventory(task.task_id, targets)
|
||||
store.replace_target_plan(task.task_id, (
|
||||
TargetPlanRow(targets[0]), TargetPlanRow(targets[1]),
|
||||
TargetPlanRow(targets[2], True, 'PRIOR'),
|
||||
))
|
||||
yield service, store, task, project
|
||||
store.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('column', ['C', 'D'])
|
||||
@pytest.mark.parametrize('value', [
|
||||
123, 123.5, True, False, date(2026, 10, 17), datetime(2026, 10, 17, 12),
|
||||
'#N/A', '=100+23',
|
||||
], ids=['integer', 'decimal', 'true', 'false', 'date', 'datetime', 'error', 'formula'])
|
||||
def test_nontext_part_numbers_reject_whole_preview_with_excel_row(project_task, tmp_path, column, value):
|
||||
service, store, task, project = project_task
|
||||
before = store.list_target_plan(task.task_id)
|
||||
path = write_bom_template(tmp_path / 'types.xlsx', [{
|
||||
'project_path': str(project), 'old_part_number': 'OLD',
|
||||
'new_part_number': '000123', 'refdes': 'R1',
|
||||
}])
|
||||
workbook = load_workbook(path)
|
||||
workbook.active[f'{column}2'] = value
|
||||
if type(value) in (int, float):
|
||||
workbook.active[f'{column}2'].number_format = '000000'
|
||||
workbook.save(path)
|
||||
workbook.close()
|
||||
|
||||
report = service.inspect_bom_batch(task.task_id, path)
|
||||
assert report.preview is None
|
||||
assert [(row.excel_row, row.status) for row in report.rows] == [(2, 'failed')]
|
||||
assert '文本' in report.rows[0].reason or '公式' in report.rows[0].reason
|
||||
assert store.list_target_plan(task.task_id) == before
|
||||
with pytest.raises(TaskCenterError, match='第 2 行'):
|
||||
service.preview_bom_batch(task.task_id, path)
|
||||
with pytest.raises(TaskCenterError, match='第 2 行'):
|
||||
read_bom_records(path)
|
||||
|
||||
|
||||
def test_corrected_text_preserves_leading_zeroes_and_existing_merge_semantics(project_task, tmp_path):
|
||||
service, store, task, project = project_task
|
||||
before = store.list_target_plan(task.task_id)
|
||||
path = write_bom_template(tmp_path / 'corrected.xlsx', [
|
||||
{'project_path': str(project), 'old_part_number': 'OLD',
|
||||
'new_part_number': '000123', 'refdes': 'R1'},
|
||||
{'project_path': str(project), 'old_part_number': 'OLD',
|
||||
'new_part_number': 'OTHER', 'refdes': 'R2'},
|
||||
])
|
||||
workbook = load_workbook(path)
|
||||
workbook.active['D2'] = 123
|
||||
workbook.active['D2'].number_format = '000000'
|
||||
workbook.save(path)
|
||||
report = service.inspect_bom_batch(task.task_id, path)
|
||||
assert report.preview is None
|
||||
assert [(row.excel_row, row.status) for row in report.rows] == [(2, 'failed'), (3, 'unchecked')]
|
||||
assert store.list_target_plan(task.task_id) == before
|
||||
|
||||
workbook.active['D2'] = '000123'
|
||||
workbook.save(path)
|
||||
workbook.close()
|
||||
report = service.inspect_bom_batch(task.task_id, path)
|
||||
assert report.passed_rows == 2 and report.preview is not None
|
||||
service.save_bom_batch(report.preview, {p.task_id: p.rows for p in report.preview.projects})
|
||||
assert [(row.target.refdes, row.enabled, row.new_part_number)
|
||||
for row in store.list_target_plan(task.task_id)] == [
|
||||
('R1', True, '000123'), ('R2', True, 'OTHER'), ('R3', True, 'PRIOR'),
|
||||
]
|
||||
assert {rule.new_part_number for rule in service._execution_rules(task.task_id)} == {
|
||||
'000123', 'OTHER', 'PRIOR',
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scaffold_count,last_row', [(0, 2), (1, 2), (3, 4)])
|
||||
def test_template_text_format_covers_existing_writable_cells_without_extra_rows(tmp_path, scaffold_count, last_row):
|
||||
records = [{'project_name': f'board{i}', 'project_path': f'C:/board{i}.prj'}
|
||||
for i in range(scaffold_count)]
|
||||
path = write_bom_template(tmp_path / 'template.xlsx', records)
|
||||
workbook = load_workbook(path)
|
||||
try:
|
||||
sheet = workbook.active
|
||||
assert sheet.max_row == last_row
|
||||
for row in range(2, last_row + 1):
|
||||
for column in ('C', 'D'):
|
||||
cell = sheet[f'{column}{row}']
|
||||
assert cell.number_format == '@', cell.coordinate
|
||||
assert cell.alignment.wrap_text is True, cell.coordinate
|
||||
finally:
|
||||
workbook.close()
|
||||
@@ -152,7 +152,11 @@ def test_blank_bom_can_be_downloaded_without_task_or_inventory(qtbot, tmp_path,
|
||||
workbook = load_workbook(output)
|
||||
try:
|
||||
assert tuple(cell.value for cell in workbook.active[1]) == BOM_HEADERS
|
||||
assert workbook.active.max_row == 1
|
||||
# The first editing row is explicitly text-formatted to preserve zeroes.
|
||||
assert workbook.active.max_row == 2
|
||||
assert all(cell.value is None for cell in workbook.active[2])
|
||||
assert workbook.active['C2'].number_format == '@'
|
||||
assert workbook.active['D2'].number_format == '@'
|
||||
finally:
|
||||
workbook.close()
|
||||
window.close()
|
||||
|
||||
Reference in new issue
Block a user