fix: address PR21 BOM routing and supervision review
Core regression / Python core and release configuration (push) Successful in 19s
Core regression / JavaScript syntax (push) Successful in 4s
Core regression / Python core and release configuration (pull_request) Successful in 17s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-05 12:42:20 +08:00
1 parent 8b5509d64f
commit 94a873f929
19 files changed
+619 -67

No files matched your search

@@ -89,7 +89,7 @@ def run(request_path):
from .stop_control import StopControl
stop = StopControl() if request.get('interactive_stop', False) else threading.Event()
finished, output_lock = threading.Event(), threading.Lock()
kind = {'inspect_bom_batch': 'bom_import', 'preview_bom_batch': 'bom_import',
kind = {'inspect_bom_batch': 'bom_import', 'preview_bom_batch': 'bom_import', 'preview_bom_sources': 'bom_import',
'execute_task_queue': 'task_queue', 'execute_quick_run_queue': 'quick_run_queue'}.get(request['operation'], request['operation'])
runtime = BatchCadRuntime(root, kind, stop, session_id=batch_id)
sequence = 0
@@ -156,9 +156,9 @@ def run(request_path):
elif operation == 'execute_task_queue':
from .task_queue import execute_task_queue
result = execute_task_queue(service, **arguments, stop_event=stop, runtime=runtime)
elif operation in {'inspect_bom_batch', 'preview_bom_batch'}:
elif operation in {'inspect_bom_batch', 'preview_bom_batch', 'preview_bom_sources'}:
controls = {'stop_event': stop, 'on_progress': progress, 'runtime': runtime}
if operation == 'inspect_bom_batch':
if operation in {'inspect_bom_batch', 'preview_bom_sources'}:
controls['on_phase'] = phase
result = getattr(service, operation)(**arguments, **controls)
elif operation == 'collect_target_inventory':
@@ -174,7 +174,7 @@ def run(request_path):
response.update(status='ok', business_succeeded=True, result=encode(result))
write_record(directory / 'business-result.json', {'version': VERSION, 'batch_id': batch_id,
'attempt_id': attempt_id, 'generation': max(1, runtime.generation), 'payload': response})
if operation == 'inspect_bom_batch':
if operation in {'inspect_bom_batch', 'preview_bom_sources'}:
from .bom_import_state import BomImportPhase
phase(BomImportPhase.RELEASING, '本批位号核验结束,正在释放后台资源…')
except Exception as error:
@@ -45,7 +45,7 @@ def _identity(scope):
def export_template(store, task_id, path):
records = () if task_id is None else tuple({'project_name': task.name, 'project_path': str(project.path),
'enabled': True, 'sync_nc': True} for task, project in _scope(store, task_id))
return write_bom_template(path, records)
return write_bom_template(path, records, include_value_mode=True)
def _assert_editable(service, task_id):
@@ -23,6 +23,9 @@ class BomRowResult:
project_name: str
status: str # passed, failed, unchecked
reason: str = ''
source_file: str = ''
source_row: int | None = None
duplicate_rows: tuple[int, ...] = ()
@dataclass(frozen=True)
@@ -39,6 +42,7 @@ class BomImportReport:
projects: tuple[BomProjectResult, ...]
preview: BomBatchPreview | None = None
errors: tuple[str, ...] = ()
source_map_path: Path | None = None
@property
def total_rows(self):
@@ -120,7 +124,8 @@ def _check_record_conflicts(rows, records, indices):
reason = '位号在 BOM 中重复(Excel 行 ' + ', '.join(
str(rows[item].excel_row) for item in dict.fromkeys(claimed)) + ')'
for index in claimed:
rows[index] = replace(rows[index], status='failed', reason=reason)
rows[index] = replace(rows[index], status='failed', reason=reason,
duplicate_rows=tuple(rows[item].excel_row for item in dict.fromkeys(claimed)))
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None):
@@ -316,7 +321,8 @@ def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None,
if len(indices_for_target) > 1:
for index in indices_for_target:
rows[index] = replace(rows[index], status='failed', reason='位号在 BOM 中重复(Excel 行 ' +
', '.join(str(rows[item].excel_row) for item in indices_for_target) + ')')
', '.join(str(rows[item].excel_row) for item in indices_for_target) + ')',
duplicate_rows=tuple(rows[item].excel_row for item in indices_for_target))
combined = tuple(matched_rows.get(key, row) for key, row in matcher.by_key.items()) if matcher else ()
try:
compile_target_rules(combined, default_value_mode=task_default_value_mode)
@@ -29,6 +29,8 @@ _HEADER_HELP = (
'是否替换:TRUE/FALSE 或 是/否;留空默认替换。未列出的位号保留。',
'自定义 Value,可选;留空沿用工具原有 Value 策略。',
'同步 NC:TRUE/FALSE 或 是/否;留空默认开启。',
'Value 来源:inherit 沿用任务策略,preserve 保留原值,part_label 使用 Part Label,'
'part_number 使用新料号,custom 使用自定义 Value 列;留空时有自定义值则使用 custom,否则 inherit。',
)
_REFDES_SPLIT = re.compile(r'[,,;;、\s]+')
_ALIASES = {
@@ -45,9 +47,9 @@ _ALIASES = {
}
def write_bom_template(path: Path, records=()) -> Path:
def write_bom_template(path: Path, records=(), *, include_value_mode=False) -> Path:
records = tuple(records)
headers = BOM_HEADERS + (('value_mode',) if any('value_mode' in record for record in records) else ())
headers = BOM_HEADERS + (('value_mode',) if include_value_mode or any('value_mode' in record for record in records) else ())
workbook = Workbook()
sheet = workbook.active
sheet.title = 'BOM Replacement'
@@ -52,6 +52,9 @@ def _scrub_json(value):
def _allowed(parts):
if (len(parts) == 5 and parts[0] == 'tasks' and parts[2] == 'quick-run-history'
and re.fullmatch(r'bom-import-[A-Za-z0-9-]+', parts[3])):
return parts[-1] == 'source-map.json'
if len(parts) == 2 and parts[0] == 'logs':
return bool(re.fullmatch(r'[^/]+\.log(?:\.\d+)?', parts[-1]))
if len(parts) == 3 and parts[0] == 'batch-resources':
@@ -16,7 +16,7 @@ HISTORY_MAX_AGE_DAYS = 30
HISTORY_MAX_ENTRIES = 100
HISTORY_MAX_BYTES = 5 * 1024 * 1024 * 1024
HISTORY_MIN_ENTRIES = 10
_HISTORY_NAME = re.compile(r"(?:batch|recovery|sheet-discovery|obsolete)-[A-Za-z0-9-]+\Z")
_HISTORY_NAME = re.compile(r"(?:batch|recovery|sheet-discovery|obsolete|bom-import)-[A-Za-z0-9-]+\Z")
@dataclass(frozen=True, slots=True)
@@ -198,48 +198,79 @@ class TaskCenterService:
def preview_bom_sources(self, task_id: str, sources, *, stop_event=None, on_progress=None,
on_phase=None, runtime=None):
"""Normalize several BOM files and exact-name migrated project paths before CAD reads."""
sources = tuple(Path(source) for source in sources)
if runtime is None and self._supervised:
return self._supervise('preview_bom_sources', {'task_id': task_id, 'sources': sources},
stop_event=stop_event, on_progress=on_progress, on_phase=on_phase)
from .bom_batch import _scope
from .bom_import_report import BomImportReport
from .bom_import_report import BomImportReport, inspect_batch
from .bom_import_state import BomImportPhase
from .retention import maintain_quick_run_storage
from .workspace_bom import load_sources, route_sources, write_routed_bom
from uuid import uuid4
def normalize():
rows = load_sources(tuple(Path(source) for source in sources), stop_event=stop_event)
def preview():
message = '正在读取 BOM 来源表格…'
if on_phase is not None:
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)
scope = _scope(self._store, task_id)
paths = tuple(project.path for _, project in scope)
routes = route_sources(rows, paths, single=len(paths) == 1)
names = {project.path: task.name for task, project in scope}
routes = route_sources(rows, paths, single=len(paths) == 1, project_names=names)
unresolved = [(row.source.name, row.excel_row, row.project_name or row.project_path)
for row in rows if routes.get(row.project_key) is None]
if unresolved:
details = '; '.join(f'{name} 第 {number} 行:{key}' for name, number, key in unresolved[:20])
raise TaskCenterError('project_binding', f'无法唯一匹配 BOM 工程,请确认迁移工程对应关系:{details}')
root = self._logging.root / 'imports' / uuid4().hex
normalized = write_routed_bom(root / 'normalized-bom.xlsx', rows, routes)
return normalized, rows
task_root = self._logging.root / 'tasks' / task_id
maintain_quick_run_storage(task_root)
root = task_root / 'quick-run-history' / ('bom-import-' + uuid4().hex)
normalized = root / 'normalized-bom.xlsx'
mapping = root / 'source-map.json'
normalized, sources_by_row = self._idle_quick_run_operation('preview_bom_sources', task_id, normalize)
def annotate(report):
if report is None:
return report
annotated = []
for row in report.rows:
if not 2 <= row.excel_row <= len(rows) + 1:
annotated.append(row)
continue
source = rows[row.excel_row - 2]
reason = row.reason
if row.duplicate_rows:
locations = (f'{rows[number - 2].source.name} 第 {rows[number - 2].excel_row} 行'
for number in row.duplicate_rows)
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} 行'))
return replace(report, rows=tuple(annotated), source_map_path=mapping)
def annotate(report):
if report is None:
return report
annotated = tuple(
replace(row, reason=(row.reason + ';来源:' +
f"{sources_by_row[row.excel_row - 2].source} 第 {sources_by_row[row.excel_row - 2].excel_row} 行")
if 2 <= row.excel_row <= len(sources_by_row) + 1 else row.reason)
for row in report.rows)
return replace(report, rows=annotated)
def inspection_phase(phase, message):
if on_phase is not None and phase is not BomImportPhase.READING:
on_phase(phase, message)
# Reuse the existing supervised reader and its cancellation/resource gates.
try:
report = self.inspect_bom_batch(task_id, normalized, stop_event=stop_event,
on_progress=on_progress, on_phase=on_phase, runtime=runtime)
except TaskCenterError as error:
if getattr(error, 'bom_report', None) is not None:
error.bom_report = annotate(error.bom_report)
if isinstance(getattr(error, 'completed_result', None), BomImportReport):
error.completed_result = annotate(error.completed_result)
raise
return annotate(report)
try:
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})})
report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime)
return annotate(report)
except TaskCenterError as error:
if getattr(error, 'bom_report', None) is not None:
error.bom_report = annotate(error.bom_report)
if isinstance(getattr(error, 'completed_result', None), BomImportReport):
error.completed_result = annotate(error.completed_result)
raise
finally:
normalized.unlink(missing_ok=True)
return self._idle_quick_run_operation('preview_bom_sources', task_id, preview)
def save_bom_batch(self, preview, rows_by_task):
from .bom_batch import save_batch
@@ -11,7 +11,7 @@ import re
from .errors import TaskCenterError
VERSION = 1
OPERATIONS = frozenset({'probe', 'runtime_smoke', 'inspect_bom_batch', 'preview_bom_batch',
OPERATIONS = frozenset({'probe', 'runtime_smoke', 'inspect_bom_batch', 'preview_bom_batch', 'preview_bom_sources',
'collect_target_inventory', 'execute_task_queue', 'execute_quick_run_queue', 'execute_quick_run',
'prepare_quick_run', 'prepare_failed_quick_run', 'recover_quick_run', 'cleanup_batch_resources',
'target_cell_choices'})
@@ -13,7 +13,8 @@ def validated_outcome(operation, body):
or body.get('status') not in {'ok', 'error'}):
raise ValueError('Invalid supervisor business outcome')
result = decode(body['result']) if body['business_succeeded'] else None
expected = {'inspect_bom_batch': BomImportReport, 'preview_bom_batch': BomBatchPreview,
expected = {'inspect_bom_batch': BomImportReport, 'preview_bom_sources': BomImportReport,
'preview_bom_batch': BomBatchPreview,
'execute_task_queue': TaskQueueResult, 'execute_quick_run_queue': BatchRunResult,
'execute_quick_run': QuickRunStepResult, 'recover_quick_run': QuickRunStepResult,
'prepare_quick_run': QuickRunResult, 'prepare_failed_quick_run': QuickRunProgress,
@@ -43,10 +44,11 @@ def resource_pending_error(operation, result, error, primary_error=None):
result = replace(result, preview=None)
failure = BatchResourceCleanupError('后台资源仍待清理;报告和已保存核验结果保留。' + (str(error) if error else ''),
completed_result=result, primary_error=primary_error, cleanup_error=error)
if isinstance(result, BomImportReport):
failure.bom_report = result
elif getattr(error, 'bom_report', None) is not None:
failure.bom_report = replace(error.bom_report, preview=None)
for candidate in (result, getattr(error, 'bom_report', None),
getattr(primary_error, 'bom_report', None)):
if isinstance(candidate, BomImportReport):
failure.bom_report = replace(candidate, preview=None)
break
return failure
@@ -697,7 +697,10 @@ class ProjectPlanPanel(QWidget):
f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、'
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个。')
details = [summary, *report.errors]
details.extend(f'Excel 第 {row.excel_row} 行 · {row.project_name or "未指定工程"} '
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 ""}'
f'Excel 第 {row.source_row if row.source_row is not None else row.excel_row} 行 · {row.project_name or "未指定工程"} '
f'({row.project_path or "无工程路径"})· '
f'{ {"passed": "通过", "failed": "失败", "unchecked": "未检查"}[row.status]}:{row.reason}'
for row in report.rows)
@@ -1,8 +1,7 @@
"""Safe multi-file BOM loading and project routing for workspace imports."""
from dataclasses import dataclass
import json
from pathlib import Path
from pathlib import Path, PureWindowsPath
from openpyxl import load_workbook
@@ -54,7 +53,7 @@ def _selected_xlsx(sources):
return tuple(sorted(paths, key=lambda path: str(path).casefold()))
def load_sources(sources, *, stop_event=None):
def load_sources(sources, *, stop_event=None, on_progress=None):
"""Read every selected workbook before any CAD operation starts."""
from .operation_control import check_cancelled
@@ -62,8 +61,10 @@ def load_sources(sources, *, stop_event=None):
if not paths:
raise TaskCenterError('bom_import', '未找到可导入的 .xlsx 替换清单')
result = []
for path in paths:
for number, path in enumerate(paths, 1):
check_cancelled(stop_event)
if on_progress is not None:
on_progress(f'正在读取 BOM {number}/{len(paths)}:{path.name}')
workbook = None
try:
workbook = load_workbook(path, read_only=True, data_only=False)
@@ -91,6 +92,9 @@ def load_sources(sources, *, stop_event=None):
)
if not any(values[index] not in (None, '') for index in (2, 3, 4, 9)):
continue
project_path = str(values[1] or '').strip()
if project_path and not (Path(project_path).is_absolute() or PureWindowsPath(project_path).is_absolute()):
raise ValueError(f'Excel 第 {excel_row} 行工程路径必须是完整路径')
try:
_part_number_text(cells, positions, 'old_part_number', '旧料号')
_part_number_text(cells, positions, 'new_part_number', '新料号')
@@ -120,7 +124,7 @@ def _exact_name_matches(project_name, paths):
return tuple(path for path in paths if _project_name(path) == name)
def resolve_project(project_path, project_name, paths):
def resolve_project(project_path, project_name, paths, *, project_names=None):
"""Resolve exact path first, then an exact unique migrated project name."""
paths = tuple(Path(path) for path in paths)
raw = _path_key(project_path)
@@ -128,18 +132,21 @@ def resolve_project(project_path, project_name, paths):
if len(exact_path) == 1:
return exact_path[0]
if project_name:
aliases = tuple(path for path in paths
if _path_key((project_names or {}).get(path)) == _path_key(project_name))
# A project_name containing directories is stronger than a basename.
name_key = _path_key(project_name)
suffix = tuple(path for path in paths if _path_key(path).endswith('/' + name_key.lstrip('/')))
if len(suffix) == 1:
return suffix[0]
if len(suffix) > 1:
matches = tuple(dict.fromkeys((*aliases, *suffix)))
if len(matches) == 1:
return matches[0]
if len(matches) > 1:
return None
matches = _exact_name_matches(project_name or project_path, paths)
return matches[0] if len(matches) == 1 else None
def route_sources(rows, paths, *, manual=None, single=False):
def route_sources(rows, paths, *, manual=None, single=False, project_names=None):
"""Route source rows; stale paths are allowed only on exact unique names."""
paths, manual = tuple(Path(path) for path in paths), manual or {}
routes = {}
@@ -153,14 +160,14 @@ def route_sources(rows, paths, *, manual=None, single=False):
if chosen not in paths:
raise TaskCenterError('project_binding', '人工选择的工程不在本次工程列表中')
else:
chosen = resolve_project(row.project_path, row.project_name, paths)
if chosen is None and single and len(paths) == 1 and not row.project_name and not row.project_path:
chosen = resolve_project(row.project_path, row.project_name, paths, project_names=project_names)
if chosen is None and single and len(paths) == 1 and not row.project_path:
chosen = paths[0]
routes[key] = chosen
return routes
def write_routed_bom(destination, rows, routes):
def write_routed_bom(destination, rows, routes, *, project_names=None):
"""Write canonical project paths while preserving row order and values."""
records = []
source_map = []
@@ -172,14 +179,26 @@ def write_routed_bom(destination, rows, routes):
record['project_path'] = str(Path(target).resolve())
record['value_mode'] = row.value_mode
records.append(record)
if _path_key(row.project_path) == _path_key(target.resolve()):
reason = 'exact_path'
elif row.project_name and _path_key(row.project_name) == _path_key((project_names or {}).get(target)):
reason = 'migrated_task_name' if row.project_path else 'task_name'
elif row.project_name and _path_key(target).endswith('/' + _path_key(row.project_name).lstrip('/')):
reason = 'migrated_exact_name' if row.project_path else 'exact_name'
elif row.project_name and _project_name(row.project_name) == _project_name(target):
reason = 'migrated_basename' if row.project_path else 'basename'
elif row.project_path:
reason = 'migrated_basename'
else:
reason = 'single_project'
source_map.append({'source_file': str(row.source), 'source_row': row.excel_row,
'original_project_path': row.project_path,
'project_name': row.project_name,
'matched_project_path': str(Path(target).resolve()),
'match_reason': 'migrated_exact_name' if _path_key(row.project_path) != _path_key(target.resolve()) else 'exact_path'})
'match_reason': reason})
destination = Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
result = write_bom_template(destination, records)
destination.with_name('source-map.json').write_text(
json.dumps(source_map, ensure_ascii=False, indent=2), encoding='utf-8')
from .batch_resources import write_record
write_record(destination.with_name('source-map.json'), source_map)
return result