Compare commits

..
Author SHA1 Message Date
abaishu0730 f80127e7bd Merge pull request 'fix: 任务搜索与筛选提供空状态(#33 D4)' (#36) from codex/issue33-d4 into main
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 11:01:56 +08:00
abaishu0730 ec2591ac75 Merge pull request 'fix: 主窗口位置、尺寸和最大化跨重启恢复(#33 D3)' (#39) from codex/issue33-d3 into main
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 11:01:32 +08:00
abaishu0730 22442e03ae Merge pull request 'fix: BOM 导入提示忽略列及近义表头(#33 D5)' (#38) from codex/issue33-d5 into main
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 11:00:58 +08:00
abaishu0730 9d9b316634 Merge pull request 'fix: 资源释放后续跑原工程队列(#33 D8)' (#41) from codex/issue33-d8 into main
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 11:00:28 +08:00
阿白叔 650dfd5491 fix: restore the main window geometry across sessions
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m28s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m27s
Core regression / JavaScript syntax (pull_request) Successful in 9s
2026-11-25 09:58:38 +08:00
阿白叔 ba69f86628 fix: surface ignored BOM headers during import
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m41s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 4m50s
Core regression / JavaScript syntax (pull_request) Successful in 9s
2026-11-25 09:58:17 +08:00
阿白叔 63999b7bfd fix: explain empty task searches and filters (#33 D4)
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m27s
Core regression / JavaScript syntax (push) Successful in 8s
Core regression / Python core, intervention UI and release configuration (pull_request) Waiting to run
Core regression / JavaScript syntax (pull_request) Successful in 6s
2026-11-25 09:48:10 +08:00
13 changed files with 370 additions and 25 deletions

No files matched your search

@@ -0,0 +1,31 @@
# Issue 33 D5 · BOM 未知列验收
现场 B3 的 `INVALID_C1_bad_header_extra_col.xlsx` 带有 `extra_column`。名称归一化将未知列映射为空,后续只复制模板定义的列。导入成功时,工作区原先只报告保存行数与失败行数。
现在 BOM 导入保留模板列的精确映射,并为每个被忽略的具名列显示来源文件、原始列名与警告计数。详情和任务事件同时记录这些警告。缺失必需列时,导入停止,错误详情列出具体缺失项并对相近列名给出改名建议。
## Windows 11 重放
通过 Qt 工作区的“导入 BOM”按钮和真实任务服务运行,测试替换的是文件选择对话框的返回值。现场文件复制到临时目录,仅把第一条记录的工程名称与路径绑定到临时工程,保留了原始表头和替换字段。
| 工作簿 | 结果 |
| --- | --- |
| 两个额外列「供应商」「备注」 | 保存 1 行、失败 0 行、警告 2 项。详情逐列列名,任务事件记录同一组警告 |
| 现场 B3 `extra_column` | 保存 1 行、失败 0 行、警告 1 项。详情保留该列名 |
| 用「新料号编码」替换必需的「新料号」 | 指出缺少「新料号」,并建议将「新料号编码」改为「新料号」 |
| 缺少「新料号」 | 指出具体缺失项 |
| 表头公式与额外列中的数据公式 | 分别拒绝表头公式和第 2 行公式 |
| 原模板 | 保存 1 行、失败 0 行,无警告 |
BOM 草稿导入时未启动工程位号采集。回归还检查了由监督子进程返回的真实预览报告能携带同样的警告。包含现场工作簿重放的定向回归共通过 110 项。
## 复跑
在仓库根目录运行。现场文件从工单附件 `05_实测证据/paper2_bom` 解出。普通回归可省略 `DX_ISSUE33_D5_FIELD`,此时跳过现场文件重放。
```powershell
$env:PYTHONUTF8 = '1'
$env:PYTHONPATH = (Resolve-Path src).Path
$env:DX_ISSUE33_D5_FIELD = 'C:/path/to/INVALID_C1_bad_header_extra_col.xlsx'
python -m pytest -q -s tests/v1_1/test_bom_header_feedback.py tests/v1_1/test_bom_import_report.py tests/v1_1/test_bom_pending.py tests/v1_1/test_bom_sources_supervision.py tests/trial_task_center/test_bom_import_review.py tests/trial_task_center/test_item_value_and_bom_sources.py
```
@@ -0,0 +1,21 @@
# Issue #33 D3 主窗口布局恢复
原来的 `ui-layout.ini` 只保存分栏、表头与排序,`TrialTaskCenterWindow` 每次启动都会重用默认窗口尺寸。复现时,保存进程关闭前的普通窗口为 `(45, 55, 1200, 760)` 且已最大化,重启后普通窗口变为 `(2, 2, 1280, 880)` 且未最大化。
正常接受关闭后,现通过 Qt `saveGeometry()` 持久化普通窗口几何和最大化状态。启动时调用 `restoreGeometry()`。若配置损坏、DPI 改变导致 Qt 拒绝恢复,或普通窗口超出当前可用屏幕,窗口会在当前可用屏幕内重新定位,并保留产品定义的最小尺寸。
## Windows 原生窗口实测
```powershell
$env:QT_QPA_PLATFORM = 'windows'
python -m pytest -q -s tests/v1_1/test_window_geometry.py
```
| 场景 | 结果 |
| --- | --- |
| 正常退出并启动新进程 | 普通窗口几何保持 `(45, 55, 1200, 760)`,最大化状态保持为真 |
| 新进程设 `QT_SCALE_FACTOR=1.5` | 普通窗口回退为 `(8, 36, 1008, 700)`,窗口位于可用屏幕,采用普通状态 |
| 配置值为错误类型或截断的字节 | 窗口仍能打开,普通窗口位置可达 |
| 配置保存位置为 `(50000, 50000)` | 窗口回到可用屏幕 |
测试通过 4 项。屏外场景用坐标模拟显示器移除,DPI 变化由 Qt 环境设置触发。
@@ -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 {}))
@@ -4,7 +4,7 @@ from threading import Event
from ..stop_control import StopControl
from shiboken6 import isValid
import time
from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
from PySide6.QtCore import QByteArray, QElapsedTimer, QRect, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
from PySide6.QtGui import QAction, QActionGroup
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QHBoxLayout, QMessageBox,
QPushButton, QLabel, QSizePolicy, QSplitter, QStackedWidget, QTabWidget, QToolButton, QVBoxLayout, QWidget)
@@ -185,6 +185,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self.archive_on_close_check.setToolTip('默认关闭。仅归档安全任务,保留计划、日志和文件;待核验或资源未释放的任务保留在当前列表。')
self._build_layout()
self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat)
self._restore_window_geometry()
self.auto_intervention_check.setChecked(self._layout_settings.value(
'dsh/auto_intervention', True, type=bool))
self.auto_intervention_check.toggled.connect(self._set_auto_intervention)
@@ -321,6 +322,34 @@ class TrialTaskCenterWindow(MaterialMainWindow):
return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter,
'rules': self.mapping_table.horizontalHeader(), 'targets': self.plan_panel.table.horizontalHeader()}
def _restore_window_geometry(self):
saved = self._layout_settings.value('main_window/geometry')
if saved is None:
return
default = self.geometry()
restored = isinstance(saved, QByteArray) and self.restoreGeometry(saved)
normal = self.normalGeometry() if restored else default
screen = QApplication.screenAt(normal.center()) if restored else None
screen = screen or QApplication.primaryScreen()
if screen is None:
return
available = screen.availableGeometry()
if restored and available.contains(normal) and normal.size().expandedTo(self.minimumSize()) == normal.size():
return
# Qt may reject a saved geometry after a DPI change. Keep the normal
# window reachable on the current display, even when its minimum exceeds it.
available = available.adjusted(8, 36, -8, -8)
state = self.windowState()
self.setWindowState(Qt.WindowState.WindowNoState)
size = normal.size().boundedTo(available.size()).expandedTo(self.minimumSize())
fallback = QRect(available.topLeft(), size)
fallback.moveCenter(available.center())
fallback.moveLeft(max(fallback.left(), available.left()))
fallback.moveTop(max(fallback.top(), available.top()))
self.setGeometry(fallback)
self.setWindowState(state)
def _reset_layout(self):
self.workspace_splitter.setSizes((240, 1040))
self.detail_splitter.setSizes((650, 110))
@@ -418,9 +447,11 @@ class TrialTaskCenterWindow(MaterialMainWindow):
QTimer.singleShot(100, self.close)
return
self._cancel_dsh_diagnosis()
self._layout_settings.setValue('main_window/geometry', self.saveGeometry())
for name, widget in self._layout_widgets().items():
self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
self._layout_settings.sync()
self._closed = True
self._dsh_status.close()
self._dsh_stall_timer.stop()
@@ -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 ""}'
@@ -79,6 +79,10 @@ class TaskList(QWidget):
self.recycle_button = QPushButton('回收站', objectName='taskRecycleBin')
self.recycle_button.setCheckable(True)
self.count = QLabel(objectName='taskCount')
self.empty_hint = QLabel(objectName='taskEmptyHint')
self.empty_hint.setTextFormat(Qt.TextFormat.PlainText)
self.empty_hint.setWordWrap(True)
self.empty_hint.hide()
self.filter = QComboBox(objectName="taskFilter")
for label, key, picture in (('全部任务', 'all', 'grid'), ('未完成', 'unfinished', 'clock'),
('待开始', 'pending', 'clock'), ('执行中', 'running', 'clock'),
@@ -146,6 +150,7 @@ class TaskList(QWidget):
layout.addWidget(self.filter)
layout.addLayout(batch)
layout.addLayout(selection)
layout.addWidget(self.empty_hint)
layout.addWidget(self.list, 1)
layout.addWidget(self.queue_button)
layout.addLayout(footer)
@@ -254,6 +259,17 @@ class TaskList(QWidget):
if getattr(task, "task_id") == selected:
self.list.setCurrentItem(item)
hidden = selected and self.current_task_id() is None
self.count.setText(f'{len(tasks)} / {len(self._tasks)} 个任务' + (' · 当前任务已隐藏' if hidden else ''))
if not tasks:
category_text = self.filter.currentText() if category != 'all' and not self.recycle_button.isChecked() else ''
if not self._tasks:
hint = '回收站为空。' if self.recycle_button.isChecked() else '暂无任务,点击“新建任务”导入工程。'
elif query:
scope = f'“{category_text}”中' if category_text else ''
hint = f'{scope}未找到与“{self.search.text().strip()}”匹配的任务。'
else:
hint = f'暂无“{category_text}”任务。'
self.empty_hint.setText(hint)
self.empty_hint.setVisible(not tasks)
self.count.setText(f'匹配 {len(tasks)} / 共 {len(self._tasks)} 个任务' + (' · 当前任务已隐藏' if hidden else ''))
self._update_selection_state()
self.view_changed.emit()
@@ -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:
+20
View File
@@ -27,6 +27,26 @@ def visible_ids(panel):
return [panel.list.item(index).data(Qt.ItemDataRole.UserRole) for index in range(panel.list.count())]
def test_empty_list_explains_search_filter_and_initial_state(navigation, qtbot):
panel, tasks, opened = navigation
panel.populate(tasks[:1])
qtbot.keyClicks(panel.search, 'zzzz_no_match')
assert panel.empty_hint.isVisible()
assert 'zzzz_no_match' in panel.empty_hint.text()
assert '匹配 0 / 共 1 个任务' in panel.count.text()
panel.filter.setCurrentIndex(panel.filter.findData('completed'))
assert '已完成' in panel.empty_hint.text() and 'zzzz_no_match' in panel.empty_hint.text()
panel.search.clear()
assert '已完成' in panel.empty_hint.text()
panel.filter.setCurrentIndex(panel.filter.findData('all'))
assert not panel.empty_hint.isVisible() and len(visible_ids(panel)) == 1
panel.populate(())
assert '新建任务' in panel.empty_hint.text()
panel.recycle_button.setChecked(True)
panel.populate(())
assert '回收站' in panel.empty_hint.text()
@pytest.mark.parametrize(('category','expected'),[
('all',['draft','ready','running','paused','completed','failed','blocked']),
('unfinished',['draft','ready','running','paused','failed','blocked']),
+99
View File
@@ -0,0 +1,99 @@
import json
import os
from pathlib import Path
import pytest
from openpyxl import load_workbook
from PySide6.QtWidgets import QFileDialog
from test_bom_batch import batch, records_for
from dx_productivity.trial_task_center.bom_plan import write_bom_template
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
@pytest.mark.parametrize('case', ['extra', 'near', 'missing', 'header_formula', 'row_formula', 'original'])
def test_bom_header_feedback_through_workspace(case, batch, tmp_path, qtbot, monkeypatch):
service, _, tasks, targets, inventory_calls = batch
task = tasks[0]
record = records_for(tasks, targets)[0]
source = write_bom_template(tmp_path / f'{case}.xlsx', [record])
workbook = load_workbook(source)
sheet = workbook.active
if case == 'extra':
sheet['L1'], sheet['L2'] = '供应商', 'Example supplier'
sheet['M1'], sheet['M2'] = '备注', 'Example note'
elif case == 'near':
sheet['D1'] = '新料号编码'
elif case == 'missing':
sheet['D1'] = None
elif case == 'header_formula':
sheet['L1'] = '=1+1'
elif case == 'row_formula':
sheet['L1'], sheet['L2'] = '备注', '=1+1'
workbook.save(source)
workbook.close()
assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch)
def test_field_extra_column_through_workspace(batch, tmp_path, qtbot, monkeypatch):
field = os.environ.get('DX_ISSUE33_D5_FIELD')
if not field:
pytest.skip('set DX_ISSUE33_D5_FIELD to replay the field attachment')
service, _, tasks, targets, inventory_calls = batch
source = tmp_path / Path(field).name
workbook = load_workbook(field)
sheet = workbook.active
# Rebind to the local fixture project. Keep the original Excel header and BOM cells.
sheet['A2'] = tasks[0].name
sheet['B2'] = str(targets[tasks[0].task_id][0].project_path)
workbook.save(source)
workbook.close()
assert_workspace_import('field', source, tasks[0], service, inventory_calls, qtbot, monkeypatch)
def assert_workspace_import(case, source, task, service, inventory_calls, qtbot, monkeypatch):
window = TrialTaskCenterWindow(service)
window.auto_intervention_check.setChecked(False)
qtbot.addWidget(window)
window.open_task(task.task_id)
panel = window.plan_panel
qtbot.waitUntil(panel.import_bom_button.isEnabled, timeout=5000)
monkeypatch.setattr(QFileDialog, 'getOpenFileNames', lambda *args: ([str(source)], 'Excel (*.xlsx)'))
panel.import_bom_button.click()
qtbot.waitUntil(lambda: not window._workers, timeout=8000)
status = window.run_panel.operator_band.text()
print(status)
pending = service.pending_bom(task.task_id)
assert not inventory_calls
if case in {'extra', 'field', 'original', 'near', 'missing', 'header_formula'}:
panel.report_toggle.setChecked(True)
assert panel.report_dialog is not None
details = panel.report_dialog.view.toPlainText()
print(details)
if case in {'extra', 'field', 'original'}:
assert len(pending) == 1
assert panel.last_bom_report.failed_rows == 0 and panel.last_bom_report.deferred
if case == 'extra':
assert '失败 0 行' in status and '警告 2 项' in status
assert all(text in details for text in ('已忽略', '供应商', '备注', source.name))
assert pending[0].record.new == 'NEW-0'
events = (service._logging.root / 'tasks' / task.task_id / 'events.jsonl').read_text(encoding='utf-8')
entries = [json.loads(line) for line in events.splitlines()]
entry = next(event for event in entries if event['operation'] == 'import_bom_drafts')
assert tuple(entry['details']['warnings']) == panel.last_bom_report.warnings
elif case == 'field':
assert '警告 1 项' in status and 'extra_column' in details
else:
assert '警告' not in status and '已忽略' not in details
else:
assert not pending
if case == 'near':
assert '缺少必需列「新料号」' in status
assert '「新料号编码」' in details and '改为「新料号」' in details
elif case == 'missing':
assert '缺少必需列「新料号」' in status and '新料号' in details
elif case == 'header_formula':
assert 'BOM 表头不接受公式' in status and 'BOM 表头不接受公式' in details
else:
assert '第 2 行不接受公式' in status
window.close()
@@ -9,6 +9,8 @@ from test_bom_batch import batch
def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tmp_path):
from openpyxl import load_workbook
from dx_productivity.trial_task_center.bom_plan import write_bom_template
service, store, tasks, targets, calls = batch
for task in tasks:
@@ -17,9 +19,14 @@ def test_real_supervised_sources_roundtrip_origin_metadata_and_preview(batch, tm
'project_name': task.name, 'project_path': str(targets[task.task_id][0].project_path),
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number',
},)) for index, task in enumerate(tasks))
workbook = load_workbook(sources[0])
workbook.active['M1'] = '备注'
workbook.save(sources[0])
workbook.close()
service._supervised = True
report = service.preview_bom_sources(tasks[0].task_id, sources)
assert report.passed_rows == 2 and report.preview is not None
assert report.warnings == ('source-0.xlsx:已忽略未知列「备注」',)
assert tuple(row.source_file for row in report.rows) == tuple(str(path.resolve()) for path in sources)
assert all(row.source_row == 2 for row in report.rows)
assert report.source_map_path.is_file()
+89
View File
@@ -0,0 +1,89 @@
import json
import os
from pathlib import Path
import subprocess
import sys
import pytest
from PySide6.QtCore import QByteArray
from test_ui_remediation import window
_GEOMETRY = 'main_window/geometry'
def test_geometry_persists_across_application_processes(tmp_path):
source = Path(__file__).resolve().parents[2] / 'src'
env = os.environ | {'PYTHONPATH': str(source)}
script = """
import json
import sys
from PySide6.QtCore import QTimer
from dx_productivity.trial_task_center import application
mode, root = sys.argv[1:]
window_type = application._load_window()
def open_window(service):
window = window_type(service)
def capture():
normal = window.normalGeometry()
area = window.screen().availableGeometry()
print(json.dumps({'normal': normal.getRect(), 'maximized': window.isMaximized(),
'reachable': area.contains(normal.topLeft()), 'fits': area.contains(normal)}),
flush=True)
window.close()
def arrange():
if mode == 'save':
window.setGeometry(45, 55, 1200, 760)
window.showMaximized()
QTimer.singleShot(200, capture)
QTimer.singleShot(0, arrange)
return window
application._load_window = lambda: open_window
raise SystemExit(application.main(['--data-root', root]))
"""
env.setdefault('QT_QPA_PLATFORM', 'offscreen')
def launch(mode, **overrides):
result = subprocess.run([sys.executable, '-c', script, mode, str(tmp_path)], env=env | overrides,
timeout=90, capture_output=True, text=True)
assert result.returncode == 0, result.stderr
return json.loads(result.stdout)
saved = launch('save')
reopened = launch('restore')
rescaled = launch('restore', QT_SCALE_FACTOR='1.5')
print(f'window geometry saved={saved}, reopened={reopened}')
print(f'window geometry at changed DPI={rescaled}')
assert saved['maximized'] and reopened['maximized']
assert saved['normal'][2:] == [1200, 760]
assert reopened['reachable'] and rescaled['reachable']
if saved['fits']:
assert reopened['normal'] == saved['normal']
@pytest.mark.parametrize('saved', ['broken', QByteArray(b'bad'), 'offscreen'])
def test_invalid_or_offscreen_settings_leave_window_visible(window, qtbot, saved):
if saved == 'offscreen':
window.setGeometry(50000, 50000, 1200, 760)
saved = window.saveGeometry()
window._layout_settings.setValue(_GEOMETRY, saved)
window._layout_settings.sync()
reopened = type(window)(window.service)
qtbot.addWidget(reopened)
try:
reopened.show()
rect = reopened.geometry()
area = reopened.screen().availableGeometry()
assert area.contains(rect.topLeft())
assert rect.intersects(area)
assert not reopened.isMaximized()
finally:
reopened.close()