Compare commits

..
Author SHA1 Message Date
阿白叔 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
12 changed files with 192 additions and 242 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
```
@@ -1,17 +0,0 @@
# Issue #33 D1 同数据目录单实例
`application.main` 原先直接配置日志、打开 `task-center.db` 并执行启动恢复。现场 `data_lock` 日志有两次同根 `application_start`,两实例均成功读取任务列表。现有执行租约只在执行操作中生效。
GUI 现在先取得 `.gui-instance.lock` 的内核文件锁,再打开日志和数据库。第二次启动经 Qt 本地套接字请求激活现有窗口,该窗口写入 `instance_conflict` 并在状态栏提示。锁保持到 SQLite 和后台读线程关闭,进程强制结束时由操作系统回收。启动参数中的工作进程和 CLI 在 GUI 文件锁之前分流。
## Windows 复测
```powershell
$env:QT_QPA_PLATFORM = 'offscreen'
python -m pytest -q tests/v1_1/test_single_instance.py
```
- 四个真实 GUI 子进程并发打开同一目录,其中两个使用大写路径。日志有一次 `application_start`、一次启动恢复和三次 `instance_conflict`,三个转发进程均返回 0。
- 另一个数据目录的窗口与持锁窗口同时存活。同根 `--native-helper` 执行自身参数校验并返回 2,冲突计数仍为三次。
- 强制结束持锁进程后,同根 `--smoke-test` 成功启动并正常关闭,预先写入的任务 ID 仍在 SQLite。另一数据目录的进程继续运行。
- 修改前运行同一并发场景时,三个竞争进程没有退出,测试失败。测试使用 Qt offscreen,验证激活请求已处理。Windows 桌面前台切换和实际 CAD 写入需通过交互式验收复核。
@@ -9,13 +9,12 @@ import platform
import sys import sys
from typing import Sequence from typing import Sequence
from PySide6.QtCore import QTimer, QThreadPool, Qt from PySide6.QtCore import QTimer, QThreadPool
from PySide6.QtGui import QIcon from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
from dx_productivity.trial_task_center.service import TaskCenterService from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.single_instance import InstanceUnavailable, gui_instance, listen_for_activation
from dx_productivity.trial_task_center.store import TaskStore from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.version import VERSION from dx_productivity.trial_task_center.version import VERSION
@@ -162,28 +161,10 @@ def main(argv: Sequence[str] | None = None) -> int:
from dx_productivity.trial_task_center.sceneos_cli import run from dx_productivity.trial_task_center.sceneos_cli import run
return run(data_root) return run(data_root)
try:
with gui_instance(data_root) as endpoint:
if endpoint is None:
return 0
return _run_gui(argv, arguments, data_root, endpoint)
except (OSError, InstanceUnavailable) as error:
message = f'无法打开 DxPartReplace。\n{data_root}\n{error}'
if sys.stderr is not None:
print(message, file=sys.stderr)
if os.name == 'nt' and bool(getattr(sys, 'frozen', False)):
import ctypes
ctypes.windll.user32.MessageBoxW(None, message, 'DxPartReplace', 0x30)
return 1
def _run_gui(argv, arguments, data_root, endpoint):
logging_context = configure_logging(data_root) logging_context = configure_logging(data_root)
install_exception_hooks(logging_context) install_exception_hooks(logging_context)
store: TaskStore | None = None store: TaskStore | None = None
window = None window = None
activation_server = None
try: try:
database_path = data_root / "task-center.db" database_path = data_root / "task-center.db"
_log_startup(logging_context, data_root, database_path) _log_startup(logging_context, data_root, database_path)
@@ -196,16 +177,6 @@ def _run_gui(argv, arguments, data_root, endpoint):
configure_application_identity(qt_application) configure_application_identity(qt_application)
window = _load_window()(service) window = _load_window()(service)
window.show() window.show()
def activate():
logging_context.logger.info('instance_conflict data_root=%s', data_root)
window.setWindowState(window.windowState() & ~Qt.WindowState.WindowMinimized)
window.show()
window.raise_()
window.activateWindow()
window.statusBar().showMessage('此数据目录已在使用,已切换到现有窗口。', 6000)
activation_server = listen_for_activation(endpoint, activate)
if arguments.smoke_test: if arguments.smoke_test:
QTimer.singleShot(0, lambda: (window.close(), qt_application.quit())) QTimer.singleShot(0, lambda: (window.close(), qt_application.quit()))
exit_code = qt_application.exec() exit_code = qt_application.exec()
@@ -216,8 +187,6 @@ def _run_gui(argv, arguments, data_root, endpoint):
logging_context.report_exception("startup", error) logging_context.report_exception("startup", error)
return 1 return 1
finally: finally:
if activation_server is not None:
activation_server.close()
if store is not None: if store is not None:
# The window invalidates queued UI results on close. Finish the # The window invalidates queued UI results on close. Finish the
# remaining read before releasing the shared SQLite connection. # remaining read before releasing the shared SQLite connection.
@@ -48,6 +48,7 @@ class BomImportReport:
source_map_path: Path | None = None source_map_path: Path | None = None
passed_preview: BomBatchPreview | None = None passed_preview: BomBatchPreview | None = None
deferred: bool = False deferred: bool = False
warnings: tuple[str, ...] = ()
@property @property
def total_rows(self): 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): 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.""" """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) scope = _scope(service._store, task_id)
paths = tuple(project.path for _, project in scope) paths = tuple(project.path for _, project in scope)
names = {project.path: task.name for task, 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) write_routed_bom(normalized, rows, routes, project_names=names)
append_task_event(service._logging, level='INFO', task_id=task_id, append_task_event(service._logging, level='INFO', task_id=task_id,
operation='import_bom_drafts', message='BOM 表格来源记录已保存,工程位号待核验', 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: try:
report = inspect_batch(service, task_id, normalized, stop_event=stop_event, on_progress=on_progress, 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) 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: if report.deferred and result.project_path not in failed_paths:
reason = '表格已保存,执行前核验工程位号' reason = '表格已保存,执行前核验工程位号'
annotated.append(replace(result, source_file=str(source.source), source_row=source.excel_row, reason=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: if report.deferred:
accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True) accepted_sources = tuple(source for result, source in zip(report.rows, rows, strict=True)
if result.project_path not in failed_paths) if result.project_path not in failed_paths)
@@ -245,7 +245,8 @@ class TaskCenterService:
on_phase(BomImportPhase.READING, message) on_phase(BomImportPhase.READING, message)
if on_progress is not None: if on_progress is not None:
on_progress(message) 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 {})) **({'allow_partial': True} if allow_partial else {}))
scope = _scope(self._store, task_id) scope = _scope(self._store, task_id)
paths = tuple(project.path for _, project in scope) paths = tuple(project.path for _, project in scope)
@@ -278,7 +279,7 @@ class TaskCenterService:
reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')' reason = '位号在 BOM 中重复(' + ';'.join(locations) + ')'
annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row, annotated.append(replace(row, source_file=str(source.source), source_row=source.excel_row,
reason=reason + f';来源:{source.source} 第 {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, return bind_source_report(annotated_report,
tuple(dict.fromkeys((str(row.source), row.source_sha256) for row in rows)), mapping) 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) write_routed_bom(normalized, rows, routes, project_names=names)
append_task_event(self._logging, level='INFO', task_id=task_id, append_task_event(self._logging, level='INFO', task_id=task_id,
operation='preview_bom_sources', message='BOM 导入来源记录已保存', 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, report = inspect_batch(self, task_id, normalized, stop_event=stop_event,
on_progress=on_progress, on_phase=inspection_phase, runtime=runtime, on_progress=on_progress, on_phase=inspection_phase, runtime=runtime,
**({'allow_partial': True} if allow_partial else {})) **({'allow_partial': True} if allow_partial else {}))
@@ -1,86 +0,0 @@
"""Hold a data-root lock while the GUI owns its database and layout."""
from contextlib import contextmanager
import errno
import os
import time
from PySide6.QtNetwork import QLocalServer, QLocalSocket
from .path_access import internal_path
from .task_queue import _os_lock
class InstanceUnavailable(RuntimeError):
pass
@contextmanager
def gui_instance(data_root):
root = internal_path(data_root)
root.mkdir(parents=True, exist_ok=True)
# OS locks release on process death. Keep the file so every contender locks the same inode.
with (root / '.gui-instance.lock').open('a+b') as handle:
identity = os.fstat(handle.fileno())
endpoint = f'DxPartReplace-{identity.st_dev:x}-{identity.st_ino:x}'
deadline = time.monotonic() + 30
while True:
try:
_os_lock(handle, True)
break
except OSError as error:
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
raise
if _activate(endpoint):
yield None
return
if time.monotonic() >= deadline:
raise InstanceUnavailable('此数据目录已在使用,现有窗口暂未响应。')
time.sleep(.05)
yield endpoint
def _activate(endpoint):
socket = QLocalSocket()
socket.connectToServer(endpoint)
if not socket.waitForConnected(100):
return False
if os.name == 'nt':
import ctypes
from ctypes import wintypes
pid = wintypes.DWORD()
get_pipe_pid = ctypes.windll.kernel32.GetNamedPipeServerProcessId
get_pipe_pid.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
if get_pipe_pid(int(socket.socketDescriptor()), ctypes.byref(pid)):
ctypes.windll.user32.AllowSetForegroundWindow(pid.value)
socket.write(b'activate\n')
socket.flush()
return (socket.bytesAvailable() > 0 or socket.waitForReadyRead(1000)) and socket.readAll() == b'1'
def listen_for_activation(endpoint, activate):
server = QLocalServer()
server.setSocketOptions(QLocalServer.SocketOption.UserAccessOption)
if os.name != 'nt':
QLocalServer.removeServer(endpoint) # The lock owner can remove a crashed owner's socket.
if not server.listen(endpoint):
raise RuntimeError(server.errorString())
def accept():
while server.hasPendingConnections():
socket = server.nextPendingConnection()
def respond(socket=socket):
if socket.canReadLine() and socket.readLine() == b'activate\n':
activate()
socket.write(b'1')
socket.flush()
socket.disconnectFromServer()
socket.disconnected.connect(socket.deleteLater)
socket.readyRead.connect(respond)
respond()
server.newConnection.connect(accept)
return server
@@ -779,21 +779,22 @@ class ProjectPlanPanel(QWidget):
report = state.report report = state.report
if report is None: if report is None:
return '', '', '' return '', '', ''
warning_summary = f' · 警告 {len(report.warnings)} 项' if report.warnings else ''
if report.deferred: if report.deferred:
failed_paths = {row.project_path for row in report.rows if row.status == 'failed'} 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) accepted = tuple(row for row in report.rows if row.project_path not in failed_paths)
summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、' summary = (f'BOM 表格已保存,工程位号待核验:{len(accepted)} 行、'
f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行。') f'{len({row.project_path for row in accepted})} 个工程;失败 {report.failed_rows} 行{warning_summary}。')
details = [summary, '确认执行后仅核验当前工程;本次导入未读取工程位号。'] details = [summary, *report.warnings, '确认执行后仅核验当前工程;本次导入未读取工程位号。']
details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}' details.extend(f'{row.project_name} · {Path(row.source_file).name} 第 {row.source_row} 行:{row.reason}'
for row in report.rows) 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 '校验未通过' outcome = '校验通过' if state.phase is BomImportPhase.PREVIEW_READY else '校验未通过'
summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、' summary = (f'BOM {outcome}:共 {report.total_rows} 行,通过 {report.passed_rows} 行、'
f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;' f'失败 {report.failed_rows} 行、未检查 {report.unchecked_rows} 行;'
f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、' f'共 {report.total_projects} 个工程,通过 {report.passed_projects} 个、'
f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个。') f'失败 {report.failed_projects} 个、未检查 {report.unchecked_projects} 个{warning_summary}。')
details = [summary, *report.errors] details = [summary, *report.errors, *report.warnings]
if report.source_map_path is not None: if report.source_map_path is not None:
details.append(f'导入来源记录:{report.source_map_path}') details.append(f'导入来源记录:{report.source_map_path}')
details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}' details.extend(f'{Path(row.source_file).name + " · " if row.source_file else ""}'
@@ -1,11 +1,13 @@
"""Safe multi-file BOM loading and project routing for workspace imports.""" """Safe multi-file BOM loading and project routing for workspace imports."""
from dataclasses import dataclass from dataclasses import dataclass
from difflib import get_close_matches
import hashlib import hashlib
from pathlib import Path, PureWindowsPath from pathlib import Path, PureWindowsPath
from openpyxl import load_workbook 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 .bom_plan import BOM_HEADERS, _normal_headers, _part_number_text, write_bom_template
from .errors import TaskCenterError from .errors import TaskCenterError
@@ -55,7 +57,37 @@ def _selected_xlsx(sources):
return tuple(sorted(paths, key=lambda path: str(path).casefold())) 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.""" """Read every selected workbook before any CAD operation starts."""
from .operation_control import check_cancelled 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: if len(workbook.worksheets) != 1:
raise ValueError('BOM 只能包含一个工作表') raise ValueError('BOM 只能包含一个工作表')
rows = iter(workbook.active.iter_rows()) rows = iter(workbook.active.iter_rows())
header_cells = next(rows, ()) positions, unknown = _source_headers(path, 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}
for excel_row, cells in enumerate(rows, 2): for excel_row, cells in enumerate(rows, 2):
check_cancelled(stop_event) check_cancelled(stop_event)
formula = any(cell.data_type == 'f' for cell in cells) 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)) result.append(SourceRow(path, excel_row, values, value_mode, source_sha256))
if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256: if hashlib.sha256(path.read_bytes()).hexdigest() != source_sha256:
raise ValueError('BOM 来源在读取期间已改变,请重新导入') raise ValueError('BOM 来源在读取期间已改变,请重新导入')
if warnings is not None:
warnings.extend(f'{path.name}:已忽略未知列「{name}」' for name in unknown)
except TaskCenterError: except TaskCenterError:
raise raise
except Exception as error: except Exception as error:
+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): 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 from dx_productivity.trial_task_center.bom_plan import write_bom_template
service, store, tasks, targets, calls = batch service, store, tasks, targets, calls = batch
for task in tasks: 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), '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', 'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1', 'value_mode': 'part_number',
},)) for index, task in enumerate(tasks)) },)) for index, task in enumerate(tasks))
workbook = load_workbook(sources[0])
workbook.active['M1'] = '备注'
workbook.save(sources[0])
workbook.close()
service._supervised = True service._supervised = True
report = service.preview_bom_sources(tasks[0].task_id, sources) report = service.preview_bom_sources(tasks[0].task_id, sources)
assert report.passed_rows == 2 and report.preview is not None 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 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 all(row.source_row == 2 for row in report.rows)
assert report.source_map_path.is_file() assert report.source_map_path.is_file()
-84
View File
@@ -1,84 +0,0 @@
from __future__ import annotations
import os
from pathlib import Path
import subprocess
import sys
import time
from dx_productivity.trial_task_center.store import TaskStore
_SOURCE = Path(__file__).resolve().parents[2] / 'src'
_APP = 'dx_productivity.trial_task_center.application'
def _wait_for(predicate, description):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
if predicate():
return
time.sleep(.05)
raise AssertionError(description)
def test_concurrent_gui_launches_activate_one_owner_and_recover_after_kill(tmp_path):
root = tmp_path / 'Shared Root'
independent = tmp_path / 'Independent Root'
root.mkdir()
store = TaskStore(root / 'task-center.db')
try:
task = store.create_task('Existing task')
finally:
store.close()
processes = []
env = os.environ | {'PYTHONPATH': str(_SOURCE), 'QT_QPA_PLATFORM': 'offscreen'}
def launch(path, *arguments):
process = subprocess.Popen(
[sys.executable, '-m', _APP, '--data-root', str(path), *arguments],
env=env,
)
processes.append(process)
return process
def log(path):
logfile = path / 'logs/application.log'
return logfile.read_text(encoding='utf-8') if logfile.exists() else ''
try:
alias = root.with_name(root.name.upper()) if os.name == 'nt' else root
contenders = [launch(root), launch(alias), launch(root), launch(alias)]
_wait_for(lambda: sum(p.poll() is not None for p in contenders) >= 3,
'Three concurrent launches should exit after handing off to one GUI')
owners = [p for p in contenders if p.poll() is None]
assert len(owners) == 1
assert [p.returncode for p in contenders if p not in owners] == [0, 0, 0]
_wait_for(lambda: log(root).count('instance_conflict') == 3,
'The GUI should handle and log all three activation requests')
assert log(root).count('application_start ') == 1
other = launch(independent)
_wait_for(lambda: 'application_start ' in log(independent), 'Different root should start independently')
assert other.poll() is None and owners[0].poll() is None
helper = launch(root, '--native-helper')
assert helper.wait(timeout=60) == 2 # The helper validates its own required snapshot.
assert log(root).count('instance_conflict') == 3
owners[0].kill()
owners[0].wait(timeout=10)
assert launch(root, '--smoke-test').wait(timeout=60) == 0
assert log(root).count('application_start ') == 2
assert log(root).count('application_clean_shutdown') == 1
assert other.poll() is None
store = TaskStore(root / 'task-center.db')
try:
assert [record.task_id for record in store.list_tasks()] == [task.task_id]
finally:
store.close()
finally:
for process in processes:
if process.poll() is None:
process.kill()
process.wait(timeout=10)