from pathlib import Path import gc import weakref import pytest from openpyxl import load_workbook from dx_productivity.trial_task_center.bom_plan import 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 @pytest.fixture def batch(tmp_path): root = tmp_path / 'projects' for name in ('a', 'b'): folder = root / name folder.mkdir(parents=True) (folder / 'same.prj').write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n') store = TaskStore(tmp_path / 'tasks.db') service = TaskCenterService(store, configure_logging(tmp_path / 'data')) tasks = service.create_project_tasks(root) targets = {} calls = [] for task in tasks: path = service.projects(task.task_id)[0].path targets[task.task_id] = tuple(ComponentTarget(path, 'MAIN', '1', uid, ref, 'OLD', '33R') for uid, ref in (('u1', 'R1'), ('u2', 'R2'))) def collect(project, parts, task_id=task.task_id, **controls): calls.append((task_id, parts)) return targets[task_id] service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory = collect yield service, store, tasks, targets, calls store.close() def records_for(tasks, targets): return tuple({'project_path': str(targets[task.task_id][0].project_path), 'old_part_number': 'OLD', 'new_part_number': 'NEW-' + str(i), 'refdes': 'R1'} for i, task in enumerate(tasks)) def test_template_lists_every_project_before_inventory_is_collected(batch, tmp_path): service, store, tasks, targets, calls = batch path = service.export_bom_template(tasks[0].task_id, tmp_path / 'template.xlsx') workbook = load_workbook(path) try: records = [dict(zip((cell.value for cell in workbook.active[1]), values)) for values in workbook.active.iter_rows(min_row=2, values_only=True)] assert {row['project_path'] for row in records} == { str(targets[task.task_id][0].project_path) for task in tasks} assert all(not row['old_part_number'] and not row['new_part_number'] and not row['refdes'] for row in records) assert not calls and all(not store.list_target_plan(t.task_id) for t in tasks) finally: workbook.close() def test_batch_bom_routes_identical_refdes_and_only_saves_after_confirmation(batch, tmp_path): service, store, tasks, targets, calls = batch path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets)) preview = service.preview_bom_batch(tasks[0].task_id, path) assert len(preview.projects) == 2 and len(calls) == 2 assert all(not store.list_target_plan(task.task_id) for task in tasks) service.save_bom_batch(preview, {item.task_id: item.rows for item in preview.projects}) for i, task in enumerate(tasks): rows = store.list_target_plan(task.task_id) assert rows[0].target.refdes == 'R1' and rows[0].new_part_number == 'NEW-' + str(i) assert rows[0].enabled and not rows[1].enabled assert all(row.target.project_path == targets[task.task_id][0].project_path for row in rows) def test_unknown_project_rejected_before_any_collection_or_save(batch, tmp_path): service, store, tasks, targets, calls = batch records = list(records_for(tasks, targets)) records[1]['project_path'] = str(tmp_path / 'foreign.prj') path = write_bom_template(tmp_path / 'bad.xlsx', records) with pytest.raises(TaskCenterError, match='工程'): service.preview_bom_batch(tasks[0].task_id, path) assert not calls and all(not store.list_target_plan(task.task_id) for task in tasks) @pytest.mark.parametrize('empty_inventory', [True, False]) def test_matching_failure_identifies_the_project_and_keeps_all_plans_empty(batch, tmp_path, empty_inventory): service, store, tasks, targets, calls = batch records = list(records_for(tasks, targets)) if empty_inventory: service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = lambda *a: () else: records[0]['refdes'] = 'R9' path = write_bom_template(tmp_path / 'unmatched.xlsx', records) with pytest.raises(TaskCenterError) as caught: service.preview_bom_batch(tasks[0].task_id, path) assert tasks[0].name in caught.value.message assert str(targets[tasks[0].task_id][0].project_path) in caught.value.message assert all(not store.list_target_plan(task.task_id) for task in tasks) def test_missing_project_is_ambiguous_for_batch_and_never_guessed(batch, tmp_path): service, store, tasks, targets, calls = batch path = write_bom_template(tmp_path / 'missing-project.xlsx', ({'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1'},)) with pytest.raises(TaskCenterError, match='工程路径'): service.preview_bom_batch(tasks[0].task_id, path) assert not calls def test_existing_inventories_are_reused_without_collecting_again(batch, tmp_path): service, store, tasks, targets, calls = batch for task in tasks: store.record_target_inventory(task.task_id, targets[task.task_id]) path = write_bom_template(tmp_path / 'existing.xlsx', records_for(tasks, targets)) preview = service.preview_bom_batch(tasks[0].task_id, path) assert not calls and len(preview.projects) == 2 assert all(not any(row.enabled for row in store.list_target_plan(task.task_id)) for task in tasks) def test_saved_plan_changed_after_preview_blocks_entire_batch(batch, tmp_path): service, store, tasks, targets, calls = batch path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets)) preview = service.preview_bom_batch(tasks[0].task_id, path) store.record_target_inventory(tasks[1].task_id, targets[tasks[1].task_id]) with pytest.raises(TaskCenterError, match='预览后已改变'): service.save_bom_batch(preview, {item.task_id: item.rows for item in preview.projects}) assert not store.list_target_plan(tasks[0].task_id) def test_batch_save_rolls_back_all_projects_if_any_plan_fails(batch, tmp_path, monkeypatch): service, store, tasks, targets, calls = batch path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets)) preview = service.preview_bom_batch(tasks[0].task_id, path) original = store.replace_target_plan def fail_second(task_id, rows): if task_id == tasks[1].task_id: raise TaskCenterError('target_identity', 'second project changed') return original(task_id, rows) monkeypatch.setattr(store, 'replace_target_plan', fail_second) with pytest.raises(TaskCenterError, match='second project'): service.save_bom_batch(preview, {item.task_id: item.rows for item in preview.projects}) assert all(not store.list_target_plan(task.task_id) for task in tasks) assert all(not store.get_task(task.task_id).target_plan_mode for task in tasks) def test_blank_project_scaffold_is_ignored_and_unlisted_task_plan_is_untouched(batch, tmp_path): service, store, tasks, targets, calls = batch store.record_target_inventory(tasks[1].task_id, targets[tasks[1].task_id]) before = store.list_target_plan(tasks[1].task_id) records = [records_for(tasks, targets)[0], {'project_path': str(targets[tasks[1].task_id][0].project_path), 'enabled': True, 'sync_nc': True}] path = write_bom_template(tmp_path / 'partial.xlsx', records) preview = service.preview_bom_batch(tasks[0].task_id, path) assert len(preview.projects) == 1 service.save_bom_batch(preview, {item.task_id: item.rows for item in preview.projects}) assert store.list_target_plan(tasks[1].task_id) == before def test_ui_previews_each_project_and_confirms_the_batch_once(batch, tmp_path, qtbot, monkeypatch): from PySide6.QtWidgets import QFileDialog from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow service, store, tasks, targets, calls = batch path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets)) window = TrialTaskCenterWindow(service) qtbot.addWidget(window) window.open_task(tasks[0].task_id) qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy) monkeypatch.setattr(QFileDialog, 'getOpenFileName', lambda *args: (str(path), 'Excel (*.xlsx)')) window.plan_panel.import_bom_button.click() qtbot.waitUntil(lambda: not window._workers, timeout=5000) assert window.plan_panel.table.rows()[0].new_part_number == 'NEW-0' assert not store.list_target_plan(tasks[0].task_id) assert window.plan_panel.save_button.text() == '保存本批位号计划' service.move_project_task(tasks[0].task_id, 1) window.plan_panel.import_bom_button.click() qtbot.waitUntil(lambda: not window._workers, timeout=5000) window.open_task(tasks[1].task_id) qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy) assert window.plan_panel.table.rows()[0].new_part_number == 'NEW-1' model = window.plan_panel.table.model() model.setData(model.index(0, 6), 'EDITED-SECOND') window.plan_panel.save_button.click() qtbot.waitUntil(lambda: not window._workers and not window._loading and not window._context_query.busy, timeout=5000) assert store.list_target_plan(tasks[0].task_id)[0].new_part_number == 'NEW-0' assert store.list_target_plan(tasks[1].task_id)[0].new_part_number == 'EDITED-SECOND' assert not window.plan_panel.has_unsaved_plan(tuple(task.task_id for task in tasks)) assert window.run_panel.quick_run_button.isEnabled() window.close() @pytest.mark.parametrize('action', ['save', 'discard']) def test_finished_bom_preview_is_released_while_report_remains(batch, tmp_path, qtbot, action): from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow service, store, tasks, targets, calls = batch window = TrialTaskCenterWindow(service, close_plan_confirmer=lambda: 'discard') qtbot.addWidget(window) window.open_task(tasks[0].task_id) qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy) path = write_bom_template(tmp_path / 'release.xlsx', records_for(tasks, targets)) panel = window.plan_panel report = service.inspect_bom_batch(tasks[0].task_id, path) preview = weakref.ref(report.preview) panel._received_bom_report(report) del report assert panel.last_bom_report.preview is not None if action == 'save': saved = service.save_bom_batch(panel.last_bom_report.preview, {p.task_id: p.rows for p in panel.last_bom_report.preview.projects}) panel._saved_bom_batch(saved) else: panel.discard_all() qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy) gc.collect() assert preview() is None, 'finished report retains the full component preview' assert panel.last_bom_report.passed_rows == 2 assert '通过 2 行' in panel.report_text window.close()