feat: support item value policies and migrated multi-file BOM import
Core regression / Python core and release configuration (push) Successful in 17s
Core regression / JavaScript syntax (push) Successful in 2s
Core regression / Python core and release configuration (pull_request) Successful in 14s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-05 11:26:35 +08:00
1 parent 9316cf4fc4
commit 8b5509d64f
29 files changed
+1418 -63

No files matched your search

@@ -0,0 +1,479 @@
from pathlib import Path
import pytest
from openpyxl import Workbook
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.target_plan import (
ComponentTarget,
TargetPlanRow,
compile_target_rules,
)
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def _target(tmp_path, uid, refdes):
return ComponentTarget(tmp_path / 'migrated.prj', 'MAIN', '1', uid, refdes, 'OLD', '10nF')
def test_each_enabled_item_freezes_its_own_value_mode(tmp_path):
rows = (
TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW', value_mode='preserve'),
TargetPlanRow(_target(tmp_path, 'u2', 'R2'), True, 'NEW', value_mode='part_label'),
TargetPlanRow(_target(tmp_path, 'u3', 'R3'), True, 'NEW', value_mode='custom', custom_value='47k'),
)
rules = compile_target_rules(rows)
assert rows[2].custom_value_enabled
assert {(rule.targets[0].refdes, rule.value_mode, rule.custom_value) for rule in rules} == {
('R1', 'preserve', ''), ('R2', 'part_label', ''), ('R3', 'custom', '47k')
}
def test_inherit_item_uses_task_default_but_explicit_item_override_wins(tmp_path):
rows = (
TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW', value_mode='inherit'),
TargetPlanRow(_target(tmp_path, 'u2', 'R2'), True, 'NEW', value_mode='preserve'),
)
rules = compile_target_rules(rows, default_value_mode='part_label')
assert [(rule.targets[0].refdes, rule.value_mode) for rule in rules] == [
('R1', 'part_label'), ('R2', 'preserve')
]
def test_service_execution_rules_resolve_task_default_for_inherited_items(tmp_path):
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
store = TaskStore(tmp_path / 'execution-default.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('default policy')
project = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (project,))
targets = (
ComponentTarget(project, 'MAIN', '1', 'u1', 'R1', 'OLD1', '10nF'),
ComponentTarget(project, 'MAIN', '1', 'u2', 'R2', 'OLD2', '10nF'),
)
store.record_target_inventory(task.task_id, targets)
store.replace_target_plan(task.task_id, (
TargetPlanRow(targets[0], True, 'NEW1', value_mode='inherit'),
TargetPlanRow(targets[1], True, 'NEW2', value_mode='preserve'),
))
service.set_copy_part_number_to_value(task.task_id, True)
try:
rules = service._execution_rules(task.task_id)
assert [(rule.targets[0].refdes, rule.value_mode) for rule in rules] == [
('R1', 'part_label'), ('R2', 'preserve')
]
finally:
store.close()
def test_execution_command_preserves_item_value_modes(tmp_path):
projects = (ProjectRecord('p1', 'task', 'Board', tmp_path / 'migrated.prj', tmp_path,
True, True, ProjectStatus.PENDING, 0),)
rows = (
TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW', value_mode='preserve'),
TargetPlanRow(_target(tmp_path, 'u2', 'R2'), True, 'NEW', value_mode='part_label'),
)
rules = compile_target_rules(rows)
command = QuickRunPreparer(tmp_path / 'data', script_source=Path(__file__)).prepare(
'task', projects, rules, copy_part_number_to_value=False,
sheet_targets={str(projects[0].path).casefold(): (('MAIN', '1'),)},
).command_path.read_text(encoding='utf-8')
header, first, second = command.splitlines()
mode = header.split('\t').index('value_mode')
assert [first.split('\t')[mode], second.split('\t')[mode]] == ['preserve', 'part_label']
def test_invalid_item_value_options_are_rejected(tmp_path):
with pytest.raises(TaskCenterError, match='Value'):
TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW', value_mode='automatic')
with pytest.raises(TaskCenterError, match='custom Value is empty'):
compile_target_rules((TargetPlanRow(_target(tmp_path, 'u1', 'R1'), True, 'NEW',
value_mode='custom'),))
def test_legacy_bom_custom_value_remains_custom_after_normalization(tmp_path):
from dx_productivity.trial_task_center.bom_plan import read_bom_records, write_bom_template
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources, write_routed_bom
source = write_bom_template(tmp_path / 'legacy.xlsx', ({
'project_name': 'Board.prj', 'project_path': r'Z:\old\Board.prj',
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1',
'custom_value': '47k',
},))
rows = load_sources((source,))
normalized = write_routed_bom(tmp_path / 'normalized.xlsx', rows,
route_sources(rows, (tmp_path / 'Board.prj',)))
record, = read_bom_records(normalized)
assert record.value_mode == 'custom' and record.custom == '47k'
def test_target_context_keeps_editable_mapping_rules_after_item_overrides(tmp_path):
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
store = TaskStore(tmp_path / 'context.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
project = tmp_path / 'board.prj'
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
task, = service.create_project_tasks(tmp_path, selected_paths=(project,))
original = service.add_rule(task.task_id, 'OLD', 'NEW')
target = ComponentTarget(project, 'MAIN', '1', 'u1', 'R1', 'OLD', '10nF')
store.record_target_inventory(task.task_id, (target,))
store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'OTHER', value_mode='part_label'),))
try:
context = service.task_context(task.task_id)
assert [(r.rule_id, r.new_part_number) for r in context.rules] == [(original.rule_id, 'NEW')]
assert service._execution_rules(task.task_id)[0].new_part_number == 'OTHER'
finally:
store.close()
def _write_bom(path, project_name, project_path, refdes):
book = Workbook()
sheet = book.active
sheet.append(['project_name', 'project_path', 'old_part_number', 'new_part_number', 'refdes', 'value_mode'])
sheet.append([project_name, project_path, 'OLD', 'NEW', refdes, 'part_label'])
book.save(path)
def test_multi_file_bom_load_preserves_sources_and_migrates_exact_project_name(tmp_path):
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources
first = tmp_path / 'first.xlsx'
second = tmp_path / 'second.xlsx'
_write_bom(first, 'Board.prj', r'Z:\old\Board.prj', 'R1')
_write_bom(second, 'Board.prj', r'Z:\old\Board.prj', 'R2')
current = tmp_path / 'Board.prj'
rows = load_sources((first, second))
routes = route_sources(rows, (current,))
assert [row.source.name for row in rows] == ['first.xlsx', 'second.xlsx']
assert [row.excel_row for row in rows] == [2, 2]
assert routes[rows[0].project_key] == current
def test_migrated_name_match_is_ambiguous_without_manual_route(tmp_path):
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources
source = tmp_path / 'one.xlsx'
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
candidates = (tmp_path / 'a' / 'Board.prj', tmp_path / 'b' / 'Board.prj')
for candidate in candidates:
candidate.parent.mkdir()
candidate.touch()
rows = load_sources((source,))
routes = route_sources(rows, candidates)
assert routes[rows[0].project_key] is None
def test_distinct_project_names_route_independently_when_stale_paths_are_identical(tmp_path):
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources
sources = (tmp_path / 'first.xlsx', tmp_path / 'second.xlsx')
_write_bom(sources[0], 'BoardA.prj', r'Z:\old\wrong.prj', 'R1')
_write_bom(sources[1], 'BoardB.prj', r'Z:\old\wrong.prj', 'R1')
paths = (tmp_path / 'BoardA.prj', tmp_path / 'BoardB.prj')
rows = load_sources(sources)
routes = route_sources(rows, paths)
assert tuple(routes[row.project_key] for row in rows) == paths
def test_routed_bom_writes_source_map_for_closed_loop_diagnostics(tmp_path):
from dx_productivity.trial_task_center.workspace_bom import load_sources, route_sources, write_routed_bom
source = tmp_path / 'one.xlsx'
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
current = tmp_path / 'Board.prj'
rows = load_sources((source,))
routes = route_sources(rows, (current,))
destination = tmp_path / 'normalized' / 'bom.xlsx'
write_routed_bom(destination, rows, routes)
source_map = destination.with_name('source-map.json').read_text(encoding='utf-8')
assert 'migrated_exact_name' in source_map
assert 'one.xlsx' in source_map and '"source_row": 2' in source_map
def test_target_plan_schema_migrates_value_mode_for_existing_inventory(tmp_path):
from dx_productivity.trial_task_center.store import TaskStore
path = tmp_path / 'tasks.db'
store = TaskStore(path)
task = store.create_task('migration')
project = tmp_path / 'board.prj'
store.sync_projects(task.task_id, tmp_path, (project,))
store.record_target_inventory(task.task_id, (ComponentTarget(project, 'MAIN', '1', 'u1', 'R1', 'OLD', '10nF'),))
store.close()
import sqlite3
with sqlite3.connect(path) as connection:
connection.execute('ALTER TABLE target_plan DROP COLUMN value_mode')
store = TaskStore(path)
try:
# Existing inventory must inherit the task policy after migration.
assert store.list_target_plan(task.task_id)[0].value_mode == 'inherit'
finally:
store.close()
def test_closed_loop_persists_plan_reopens_and_freezes_command_modes(tmp_path):
from dx_productivity.trial_task_center.models import ProjectStatus, ProjectRecord
from dx_productivity.trial_task_center.store import TaskStore
database_path = tmp_path / 'closed-loop.db'
project = tmp_path / 'board.prj'
store = TaskStore(database_path)
task = store.create_task('closed-loop')
store.sync_projects(task.task_id, tmp_path, (project,))
targets = (_target(tmp_path, 'u1', 'R1'), _target(tmp_path, 'u2', 'R2'))
targets = tuple(ComponentTarget(project, t.schematic_name, t.sheet_number, t.uid, t.refdes,
t.old_part_number, t.old_value) for t in targets)
store.record_target_inventory(task.task_id, targets)
rows = (TargetPlanRow(targets[0], True, 'NEW', value_mode='preserve'),
TargetPlanRow(targets[1], True, 'NEW', value_mode='part_label'))
store.replace_target_plan(task.task_id, rows)
store.close()
reopened = TaskStore(database_path)
try:
frozen = reopened.list_target_plan(task.task_id)
rules = compile_target_rules(frozen)
command = QuickRunPreparer(tmp_path / 'evidence', script_source=Path(__file__)).prepare(
task.task_id,
(ProjectRecord('p1', task.task_id, 'Board', project, tmp_path, True, True,
ProjectStatus.PENDING, 0),),
rules,
copy_part_number_to_value=False,
sheet_targets={str(project).casefold(): (('MAIN', '1'),)},
).command_path.read_text(encoding='utf-8')
header, *command_rows = command.splitlines()
mode_index = header.split('\t').index('value_mode')
assert [row.split('\t')[mode_index] for row in command_rows] == ['preserve', 'part_label']
finally:
reopened.close()
def test_service_multi_file_preview_normalizes_migrated_routes_before_cad(tmp_path, monkeypatch):
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
import dx_productivity.trial_task_center.bom_import_report as report_module
source = tmp_path / 'migrated.xlsx'
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
current = tmp_path / 'Board.prj'
store = TaskStore(tmp_path / 'service.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('BOM')
store.sync_projects(task.task_id, tmp_path, (current,))
seen = {}
def fake_inspect(_service, _task_id, path, **_options):
seen['path'] = Path(path)
return report_module.BomImportReport(
rows=(report_module.BomRowResult(2, str(current), 'Board', 'passed', 'validated'),),
projects=(report_module.BomProjectResult(str(current), 'Board', 'passed', (2,)),),
)
monkeypatch.setattr(report_module, 'inspect_batch', fake_inspect)
try:
report = service.preview_bom_sources(task.task_id, (source,))
assert report.rows[0].reason.startswith('validated;来源:')
assert 'migrated.xlsx' in report.rows[0].reason and '第 2 行' in report.rows[0].reason
assert seen['path'].is_file()
assert (seen['path'].parent / 'source-map.json').is_file()
finally:
store.close()
@pytest.fixture
def simulated_bom_workspace(tmp_path):
from types import SimpleNamespace
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
root = tmp_path / 'projects'
for name in ('BoardA', 'BoardB'):
project = root / name / (name + '.prj')
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
store = TaskStore(tmp_path / 'simulation.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'evidence'))
tasks = service.create_project_tasks(root)
for task in tasks:
project = service.projects(task.task_id)[0].path
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '10nF')
for i in (1, 2))
store.record_target_inventory(task.task_id, targets)
runtime = SimpleNamespace(bind_logs=lambda *_: None)
yield service, store, tasks, runtime
store.close()
def test_two_excel_imports_save_reopen_freeze_and_recovery_readback(simulated_bom_workspace, tmp_path):
from dataclasses import replace
from dx_productivity.trial_task_center.bom_plan import write_bom_template
from dx_productivity.trial_task_center.bom_import_state import BomImportPhase as Phase
from dx_productivity.trial_task_center.quick_run import _read_command_options, _read_commands, _queue_matches_inputs
from dx_productivity.trial_task_center.store import TaskStore
service, store, tasks, runtime = simulated_bom_workspace
service.set_copy_part_number_to_value(tasks[0].task_id, True)
sources = []
for task, modes in zip(tasks, (('inherit', 'preserve'), ('custom', 'part_number'))):
project = service.projects(task.task_id)[0].path
sources.append(write_bom_template(tmp_path / (project.stem + '.xlsx'), tuple({
'project_name': task.name, 'project_path': 'Z:/old/' + project.name,
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': f'R{i}',
'value_mode': mode, 'custom_value': '47k' if mode == 'custom' else '',
} for i, mode in enumerate(modes, 1))))
phases = []
report = service.preview_bom_sources(tasks[0].task_id, sources, runtime=runtime,
on_phase=lambda phase, _: phases.append(phase))
assert report.passed_rows == 4 and report.preview is not None
assert phases == [Phase.READING, Phase.VALIDATING, Phase.INVENTORY, Phase.MATCHING,
Phase.INVENTORY, Phase.MATCHING]
assert all(not row.enabled for task in tasks for row in store.list_target_plan(task.task_id))
for row, filename, number in zip(report.rows, ('BoardA.xlsx', 'BoardA.xlsx', 'BoardB.xlsx', 'BoardB.xlsx'), (2, 3, 2, 3)):
assert filename in row.reason and f'第 {number} 行' in row.reason
service.save_bom_batch(report.preview, {p.task_id: p.rows for p in report.preview.projects})
reopened = TaskStore(store.path)
try:
for task, expected in zip(tasks, ((('part_label', ''), ('preserve', '')),
(('custom', '47k'), ('part_number', '')))):
policy = reopened.get_task(task.task_id).copy_part_number_to_value
rules = compile_target_rules(reopened.list_target_plan(task.task_id),
default_value_mode='part_label' if policy else 'preserve')
projects = reopened.list_projects(task.task_id)
command = QuickRunPreparer(tmp_path / task.task_id, script_source=Path(__file__)).prepare(
task.task_id, projects, rules, copy_part_number_to_value=policy,
sheet_targets={str(projects[0].path).casefold(): (('MAIN', '1'),)},
).command_path
options = _read_command_options(command)
assert tuple((mode, custom) for mode, custom, _, _ in options.values()) == expected
commands = _read_commands(command)
assert _queue_matches_inputs(command, commands, projects, rules)
changed = (replace(rules[0], custom_value='changed') if rules[0].value_mode == 'custom'
else replace(rules[0], value_mode='part_number'))
assert not _queue_matches_inputs(command, commands, projects, (changed, *rules[1:]))
finally:
reopened.close()
def test_cross_file_duplicate_blocks_every_plan_with_original_sources(simulated_bom_workspace, tmp_path):
service, store, tasks, runtime = simulated_bom_workspace
sources = (tmp_path / 'first.xlsx', tmp_path / 'second.xlsx')
for source in sources:
_write_bom(source, 'BoardA.prj', r'Z:\old\BoardA.prj', 'R1')
report = service.preview_bom_sources(tasks[0].task_id, sources, runtime=runtime)
assert report.preview is None and report.failed_rows == 2
assert 'first.xlsx' in report.rows[0].reason and 'second.xlsx' in report.rows[1].reason
assert all(not row.enabled for task in tasks for row in store.list_target_plan(task.task_id))
def test_multi_source_import_reuses_supervised_inspection(tmp_path, monkeypatch):
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.bom_import_report import BomImportReport
store = TaskStore(tmp_path / 'supervised.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'), supervised=True)
task = store.create_task('board')
store.sync_projects(task.task_id, tmp_path, (tmp_path / 'Board.prj',))
source = tmp_path / 'one.xlsx'
_write_bom(source, 'Board.prj', r'Z:\old\Board.prj', 'R1')
phases = []
def supervised(operation, arguments, **controls):
assert operation == 'inspect_bom_batch'
assert Path(arguments['path']).is_file()
controls['on_phase']('validating', 'normalized')
return BomImportReport((), ())
monkeypatch.setattr(service, '_supervise', supervised)
try:
service.preview_bom_sources(task.task_id, (source,), on_phase=lambda phase, _: phases.append(phase))
assert phases == ['validating']
finally:
store.close()
def test_legacy_plan_text_false_inherits_without_enabling_custom(simulated_bom_workspace, tmp_path):
from openpyxl import load_workbook
from dx_productivity.trial_task_center.spreadsheet_plan import export_target_plan, read_target_plan
_, store, tasks, _ = simulated_bom_workspace
task_id = tasks[0].task_id
path = export_target_plan(store, task_id, tmp_path / 'legacy-plan.xlsx')
book = load_workbook(path)
book.active.delete_cols(14)
book.active['I2'] = True
book.active['J2'] = 'NEW'
book.active['K2'] = 'FALSE'
book.save(path)
book.close()
imported = read_target_plan(store, task_id, path)
assert imported[0].enabled and imported[0].value_mode == 'inherit'
assert not imported[0].custom_value_enabled
@pytest.mark.parametrize('invalid', ['=1+1', '#N/A'])
def test_malformed_second_excel_is_blocked_before_inspection(simulated_bom_workspace, tmp_path, monkeypatch, invalid):
from openpyxl import load_workbook
service, store, tasks, _ = simulated_bom_workspace
first, second = tmp_path / 'first.xlsx', tmp_path / 'second.xlsx'
for source in (first, second):
_write_bom(source, 'BoardA.prj', r'Z:\old\BoardA.prj', 'R1')
book = load_workbook(second)
book.active['D2'] = invalid
book.save(second)
book.close()
monkeypatch.setattr(service, 'inspect_bom_batch', lambda *_a, **_k: pytest.fail('invalid source reached inspection'))
with pytest.raises(TaskCenterError, match='second.xlsx.*2'):
service.preview_bom_sources(tasks[0].task_id, (first, second))
assert all(not row.enabled for task in tasks for row in store.list_target_plan(task.task_id))
@pytest.mark.parametrize('mode', ['preserve', 'part_label', 'part_number'])
def test_batch_custom_default_does_not_overwrite_explicit_item_mode(simulated_bom_workspace, mode):
from dataclasses import replace
service, store, tasks, _ = simulated_bom_workspace
task_id = tasks[0].task_id
rule = service.add_rule(task_id, 'OLD', 'NEW')
rows = store.list_target_plan(task_id)
store.replace_target_plan(task_id, (replace(rows[0], enabled=True, value_mode=mode), rows[1]))
service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW', enabled=True,
custom_value_enabled=True, custom_value='47k')
row = store.list_target_plan(task_id)[0]
assert row.value_mode == mode and not row.custom_value_enabled
assert service._execution_rules(task_id)[0].value_mode == mode
def test_disabling_seeded_custom_default_restores_inherited_policy(simulated_bom_workspace):
from dataclasses import replace
service, store, tasks, _ = simulated_bom_workspace
task_id = tasks[0].task_id
rule = service.add_rule(task_id, 'OLD', 'NEW', custom_value_enabled=True, custom_value='47k')
rows = store.list_target_plan(task_id)
store.replace_target_plan(task_id, (replace(rows[0], enabled=True), rows[1]))
service.set_copy_part_number_to_value(task_id, True)
service.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW', enabled=True,
custom_value_enabled=False, custom_value='')
row = store.list_target_plan(task_id)[0]
assert row.value_mode == 'inherit' and not row.custom_value_enabled
assert service._execution_rules(task_id)[0].value_mode == 'part_label'