Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c04957293c | ||
|
|
6b5f79b412 | ||
|
|
a16914bc72 | ||
|
|
0f8dde61bf | ||
|
|
ce574ddb44 | ||
|
|
84d8f9c7f5 | ||
|
|
b3883cfca1 | ||
|
|
224f4e7c1e | ||
|
|
45a9cc6e0c | ||
|
|
6c0ca95d84 | ||
|
|
136d7ffd67 | ||
|
|
159616ea4a | ||
|
|
d0125f8f59 | ||
|
|
2fdbe3acb3 | ||
|
|
65a72c6a3a | ||
|
|
9b2372e389 | ||
|
|
29ea67c35e | ||
|
|
d832a1c736 | ||
|
|
7f0ec29d31 | ||
|
|
ff06f86f62 | ||
|
|
e655797e32 | ||
|
|
b47059587a | ||
|
|
a1f924295c | ||
|
|
0f0d6a7103 | ||
|
|
1b39d802bd | ||
|
|
a332e7bd59 | ||
|
|
4d8ba4c5bb | ||
|
|
791b3854b3 | ||
|
|
8986ce1759 | ||
|
|
9f95b24067 | ||
|
|
75165f60de | ||
|
|
714ac0bfc6 |
No files matched your search
@@ -17,3 +17,4 @@ __pycache__/
|
||||
.coverage
|
||||
coverage.xml
|
||||
/.worktrees/
|
||||
/.superpowers/
|
||||
@@ -1,209 +1,130 @@
|
||||
# DxDesigner Part Replacement
|
||||
# DxDesigner 器件批量替换工具
|
||||
|
||||
面向 Windows 和 DxDesigner/Expedition Enterprise 7.9.5 的器件批量替换工具。工具通过 DxDesigner 原生 `Replace Part` 完成替换,并在写入前后保存快照、检查受保护字段、记录操作证据,支持桌面连续队列和可恢复的批处理流程。
|
||||
面向 **Windows + DxDesigner / Expedition Enterprise 7.9.5** 的器件批量替换工具。一个工程对应一个任务,可以只替换同料号下的部分位号;支持直接编辑和 Excel BOM 导入,同批工程按顺序执行。
|
||||
|
||||
**当前版本 V1.1.1**:[下载便携包](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/tag/v1.1.1) · [版本说明](docs/releases/v1.1.1.md)。目录读取后一个工程对应一个任务,可采集位号并直接选择部分器件替换,逐行设置新料号、Value 和 NC;Excel 为可选编辑方式,同批任务顺序执行。见 [使用说明](docs/user/v1.1.0-project-tasks.md) 和 [快速测试入口](docs/testing/v1.1.0-test-entrypoints.md)。
|
||||
**最新版本:V1.1.2** · [下载便携包](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/download/v1.1.2/DxPartReplace-1.1.2.zip) · [版本说明与附件](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/releases/tag/v1.1.2) · [完整使用说明](docs/user/v1.1.0-project-tasks.md)
|
||||
|
||||
**V1.1.1 后台执行**:任务中心的自动采集、替换和恢复默认在独立 Windows 桌面启动自有 CAD;完成或暂停后退出 CAD、等待进程结束并确认桌面释放。用户可继续在主桌面查看其他文件,工具不接管主桌面的 CAD。目标工程仍须保存并关闭,避免同时访问同一工程。实测及限制见 [私有桌面执行验证](docs/testing/2026-10-15-private-desktop-execution.md)。
|
||||
## 窗口操作教程
|
||||
|
||||
> **当前发布级别:evaluation-only(仅评估)。** 在目标现场完成 7.9.5 验收并取得可追溯证据之前,只能对完整、可丢弃的工程副本和对应中央库进行操作。不要用于唯一工程副本、生产库或未经认证的料号映射。
|
||||
下面的 GIF 来自已验收 EXE 的真实窗口操作,包含创建任务、BOM 导入、错误行提示、保存、顺序执行、查看结果和开始新一轮。共 20 个步骤、47.5 秒;仅记录工具及其弹窗,CAD 等待已压缩,Excel 填表示例在录制之外完成。
|
||||
|
||||
## 能做什么
|
||||

|
||||
|
||||
| 使用路径 | 适合场景 | 结果含义 |
|
||||
| --- | --- | --- |
|
||||
| `DxPartReplace.exe` 桌面连续队列 | 选择工程目录和映射后,按“工程 → 图页 → 规则”串行执行 | 命中项经过替换、保存、关闭和重新打开核验;未命中项记录并跳过;“队列完成”不等于通过 Packager、ERC 或网表检查 |
|
||||
| 桌面人工证据流程 | 由操作员在 DxDesigner 中完成替换,工具采集 Before/After 证据 | 只表示证据比较通过,不自动替换、保存或关闭工程 |
|
||||
| `Start-PartReplacement.ps1` + `dx_productivity` CLI | 需要完整库存、认证、备份、恢复和外部检查门禁的评估批次 | 只有项目进入 `verified_saved` 且外部检查通过,批次才可报告为成功 |
|
||||
如果图片没有自动播放,可以[单独打开 GIF](docs/user/media/v1.1.2-window-bom-tutorial.gif)。
|
||||
|
||||
三条路径的任务、日志和通过条件不同,不能互相替代。详细边界见 [`docs/user/trial-task-center.md`](docs/user/trial-task-center.md)。
|
||||
## 开始使用
|
||||
|
||||
## 运行前提
|
||||
1. 下载并完整解压便携包,保留 `DxPartReplace.exe` 和 `_internal` 的相对位置。**便携包无需安装 Python**,本机仍需安装可用的 DxDesigner、许可证和中央库。
|
||||
2. 双击 `DxPartReplace.exe`。首次运行会自动创建同目录的 `data`,保存任务、日志和执行证据。
|
||||
3. 点击左侧 **新建**,在弹窗填写工程根目录,点击 **读取工程**,勾选需要处理的 `.prj`,再点击 **创建任务**。每个工程自动创建一个任务。
|
||||
|
||||
- Windows;真实替换基线为 **DxDesigner/Expedition Enterprise 7.9.5**。
|
||||
- 源码运行和批处理 CLI 使用 **Python 3.12(必须是 3.12)**。
|
||||
- 目标机器需要可用的 DxDesigner 安装、许可证和中央库;没有中央库时只能运行测试、构建和界面冒烟检查。
|
||||
- 自动替换每次处理一个工程。开始前保存并关闭本次目标工程;V1.1.1 使用自有后台 CAD,用户打开的其他工程不会被接管。更早发布包仍按原版本要求关闭已打开工程。
|
||||
- 每次现场试验使用完整工程副本,并保留备份、快照、状态、事件日志和报告。
|
||||
首次使用请在完整工程副本上验证映射与库配置。执行前保存并关闭待处理工程;工具会启动自己的后台 CAD,主桌面仍可查看其他文件。
|
||||
|
||||
## 发布包:最快上手
|
||||
## 方式一:通过 BOM 批量配置
|
||||
|
||||
1. 解压与目标 DxDesigner 版本匹配的发布包,保留 `DxPartReplace.exe`、`_internal` 和 `data` 目录结构。
|
||||
2. 双击 `DxPartReplace.exe`。
|
||||
3. 新建任务,读取包含 `.prj` 文件的根目录;勾选工程后批量创建任务,一个工程一个任务。
|
||||
4. 添加“旧 Part Number → 新 Part Number”映射,按需要设置 Value 和 `/NC` 选项。
|
||||
5. 需要只替换部分位号时,在“位号计划”采集、勾选并保存;先确认工程已经保存并关闭,再点击 **连续执行队列** 或 **顺序执行本批任务**。
|
||||
6. 执行过程中不要在 DxDesigner 中切页、编辑或关闭当前工程。遇到“结果无法确认”、保护锁或恢复提示时,先保留现场文件并按恢复文档处理,不要重复点击。
|
||||
### 1. 导出本批模板
|
||||
|
||||
发布版默认把可变数据放在 EXE 同目录的 `data` 下:
|
||||
选择任务,打开顶部 **本批位号计划**,点击 **BOM 模板**。只要已导入工程,就能导出同批所有工程的一张空白表,**不需要先采集位号或填写料号规则**。
|
||||
|
||||
~~~text
|
||||
data/task-center.db 任务数据库
|
||||
data/logs/application.log 应用日志
|
||||
data/tasks/<task-id>/ 任务事件与证据
|
||||
data/quick-run/ 连续队列交接文件、备份和运行日志
|
||||
~~~
|
||||
工程名称、工程路径自动填写。工程路径用于唯一分配任务,请保持原样;同一工程有多条替换时,可以复制该工程行。
|
||||
|
||||
更新程序时只替换 EXE 和 `_internal`,不要删除 `data`。分发新包时使用未运行过的干净目录,不要把包含工程备份的本机 `data` 一起外发。
|
||||
### 2. 在 Excel 填写替换项
|
||||
|
||||
## 从源码运行
|
||||
保留原模板的 11 列表头,按需要填写:
|
||||
|
||||
在仓库根目录使用 PowerShell:
|
||||
| 列名 | 填写内容 |
|
||||
| --- | --- |
|
||||
| `old_part_number` | 工程当前的旧料号 |
|
||||
| `new_part_number` | 中央库中的目标新料号 |
|
||||
| `refdes` | 要处理的位号,例如 `RV05`;一行可以写多个位号,以逗号、分号、空格或顿号分隔 |
|
||||
| `enabled` | `TRUE` / `是` 表示替换,`FALSE` / `否` 表示保留 |
|
||||
| `sync_nc` | 是否同步 NC,默认开启,可逐行关闭 |
|
||||
| `custom_value` | 可选的自定义 Value;填写后优先写入,留空沿用任务的 Value 策略 |
|
||||
|
||||
~~~powershell
|
||||
例如,首次配置的旧料号同时对应 `RV05`、`RV11`,只想替换 `RV05`,可以只填写 `RV05` 的启用项;首次采集的其余位号默认不替换。
|
||||
|
||||
**再次导入时,BOM 中未列出的既有计划行会保留原勾选和编辑状态。** 如果这轮只想执行 BOM 列出的目标,请在预览中检查其他启用行,并明确取消勾选,或在 BOM 中填写对应的 `enabled=FALSE` 行。
|
||||
|
||||
同名位号分布在不同图页时,补填 `schematic_name`、`sheet_number` 或 `uid` 消除歧义。`enabled` 留空默认替换,`sync_nc` 留空默认开启;建议显式填写。料号按文本填写;导入不接受公式,也不接受旧新相同、链式或循环替换。
|
||||
|
||||
### 3. 导入并检查报告
|
||||
|
||||
点击 **导入 BOM**,选择填好的文件。工具按工程匹配位号;缺少库存时,会调用后台 CAD 只读采集。
|
||||
|
||||
- 校验报告显示通过、失败、未检查的行数,并标明 Excel 行号及原因。
|
||||
- 有错误时,整批不会生成新的可保存预览,也不会部分写入计划。修正后重新导入。
|
||||
- 全部通过后,先得到预览;可以切换任务,检查或修改各工程的位号计划。
|
||||
|
||||
### 4. 保存并执行
|
||||
|
||||
确认预览后点击 **保存本批位号计划**;普通单工程编辑时按钮显示 **保存位号计划**。
|
||||
|
||||
点击 **执行当前任务** 处理当前工程,或点击左侧 **顺序执行本批任务** 处理同批工程。确认范围后,工具逐项执行原生 Replace Part、保存、关闭并重新打开核验。
|
||||
|
||||
**左侧搜索和显示排序只影响浏览,不改变本批执行范围。** 调整执行顺序请使用上移、下移任务按钮。
|
||||
|
||||
## 方式二:直接在界面编辑
|
||||
|
||||
1. 在 **本批料号规则** 添加旧、新料号,按需配置 Value 与同步 NC;规则提供采集条件和默认值。
|
||||
2. 切到 **本批位号计划**,点击 **采集所有匹配位号**。
|
||||
3. 勾选需要替换的行,逐行填写新料号、自定义 Value 和 NC。查找可按位号、UID、料号、图页或 Value 过滤;批量操作的范围会显示为当前工程或可见行。
|
||||
4. 保存计划后执行。位号计划模式以**已保存的每行计划**为准,手动覆盖的值不会因修改默认规则而被随意覆盖。
|
||||
|
||||
两种方式可以配合使用,不必为了编辑而先导出 Excel。切换任务会保留编辑草稿;关闭时有未保存内容会提示保存全部、放弃或取消。
|
||||
|
||||
## Value、暂停与执行结果
|
||||
|
||||
- 顶部 **Value 策略** 开关控制当前任务是否将替换后的 Part Label 写入 Value;逐行自定义 Value 优先。处理多个任务时,分别确认各任务的开关。
|
||||
- **同步 NC** 是逐行选项,默认开启,可以关闭。
|
||||
- 点击 **完成当前项后暂停** 后,工具在当前步骤安全收尾后停止,不会在原生写入中途强行中断。
|
||||
- 点击 **替换结果 / 日志** 查看图页、位号、旧料号、实际回读料号和核验状态。失败、未命中、未核验不会显示为已保存成功;完整日志支持翻页。
|
||||
- 日志和 BOM 详情按需打开,关闭后释放窗口;数据和证据仍保留。
|
||||
|
||||
## 完成后再执行一轮
|
||||
|
||||
已完成任务可以点击 **开始新一轮**。工具归档旧计划、命令、快照与执行证据,清空过期位号基线,将同批已完成任务恢复为待配置。
|
||||
|
||||
接着按工程**当前料号**重新填 BOM 或修改规则,重新采集、保存并执行。旧轮次可通过 **查看轮次证据** 打开。出现状态不确定或恢复提示时,先使用 **核验并恢复**,不要直接重复执行。
|
||||
|
||||
## 更新程序与保留数据
|
||||
|
||||
先关闭旧程序并备份 `data`。完整解压新包,用新 EXE 和 `_internal` 配合原 `data` 使用;不要混用不同版本的依赖目录,也不要删除原数据。
|
||||
|
||||
```text
|
||||
DxPartReplace/
|
||||
DxPartReplace.exe
|
||||
_internal/
|
||||
data/ 首次运行后创建,更新时保留
|
||||
task-center.db 任务数据库
|
||||
logs/application.log 应用日志
|
||||
tasks/<任务ID>/ 任务事件、备份、快照及轮次证据
|
||||
```
|
||||
|
||||
不同版本不要同时打开同一数据目录。排查失败时保留日志、原生报告和工程副本;不要手工删除锁文件、状态或恢复证据来强行续跑。
|
||||
|
||||
## 验证范围与已知限制
|
||||
|
||||
V1.1.2 已完成本机冻结 EXE 验收:两个工程实际替换和独立回读、297 字符工程路径、BOM 失败/成功导入、Part Label 写入 Value、旧版任务数据副本、新轮次和自有后台资源释放。详见[成品验收报告](docs/testing/2026-10-15-packaged-acceptance.md)。
|
||||
|
||||
当前按 **evaluation-only(评估试用)** 交付。不同机器、中央库和 CAD 版本仍需用工程副本确认兼容性;替换回读通过不代表已通过 Packager、ERC 或网表检查。
|
||||
|
||||
首次采集与 CAD 启动可能需要较长时间,存在已知的偶发 COM 启动阻塞;启动有等待上限和清理机制。本次两工程执行约 4 分 19 秒,不承诺其他工程使用相同时间。长路径兼容已覆盖验证场景,不代表旧 CAD 或中央库支持任意路径。
|
||||
|
||||
## 开发与更多资料
|
||||
|
||||
源码运行需要 Python 3.12:
|
||||
|
||||
```powershell
|
||||
py -3.12 -m venv .venv
|
||||
.\.venv\Scripts\python.exe -m pip install --upgrade pip
|
||||
.\.venv\Scripts\python.exe -m pip install -e ".[dev]"
|
||||
~~~
|
||||
|
||||
启动桌面程序:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity.trial_task_center.application
|
||||
# 或
|
||||
.\.venv\Scripts\dx-part-replace-gui.exe
|
||||
~~~
|
||||
|
||||
启动 CLI:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --help
|
||||
# 或
|
||||
.\.venv\Scripts\dx-part-replace.exe --help
|
||||
~~~
|
||||
|
||||
源码运行时,任务中心默认使用 `%LOCALAPPDATA%\DxProductivity\trial-task-center`。可以用 `DX_TASK_CENTER_HOME` 指定独立数据目录;发布版则默认使用 EXE 旁边的 `data`。
|
||||
|
||||
## CLI 快速参考
|
||||
|
||||
CLI 的输出默认是便于阅读的文本;添加 `--json` 可获得脚本可消费的稳定 JSON。下面的命令只负责发现和创建作业,真实 DxDesigner 操作仍需要已验收的配置、中央库和现场操作流程。
|
||||
|
||||
发现候选项目后必须逐行审阅:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --json discover "D:\Disposable\Projects" --output "D:\Qualification\projects-candidates.txt"
|
||||
~~~
|
||||
|
||||
创建作业需要 UTF-8 映射、项目列表和认证文件:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --json create "C:\DxProductivity\runs\part-replace-<GUID>" --mapping "D:\Qualification\replacement.csv" --projects "D:\Qualification\projects.txt" --certifications "D:\Qualification\certifications.json"
|
||||
~~~
|
||||
|
||||
常用作业查询和恢复命令:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --json status "C:\DxProductivity\runs\part-replace-<GUID>"
|
||||
.\.venv\Scripts\python.exe -m dx_productivity --json restore "C:\DxProductivity\runs\part-replace-<GUID>" "<project_id>"
|
||||
~~~
|
||||
|
||||
不要编辑 `manifest`、`mailbox`、状态文件或事件文件来推进任务;恢复必须使用原作业目录,不能用相同输入重新创建一个“看起来一样”的新作业。完整命令循环、状态和恢复前提见 [`docs/user/part-replacement.md`](docs/user/part-replacement.md)。
|
||||
|
||||
## 原生批处理集成
|
||||
|
||||
这条路径用于需要兼容性配置、项目库存、认证映射、备份、恢复和 Packager/ERC/网表检查门禁的评估批次。
|
||||
|
||||
### 1. 安装运行目录
|
||||
|
||||
`Install.ps1` 会验证 Python 3.12 和 `dx_productivity` 导入,将现场 probe 产生的兼容性配置原子部署到 `runs\compatibility-profile.json`,并写入当前用户的设置。先用 `-WhatIf` 预览路径:
|
||||
|
||||
~~~powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Install.ps1" -InstallRoot "C:\DxProductivity" -PythonExecutable "C:\Python312\python.exe" -CompatibilityProfile "C:\Qualification\compatibility-profile.json" -WhatIf
|
||||
~~~
|
||||
|
||||
确认输出后再去掉 `-WhatIf`。然后在 DxDesigner 中导入 `integration\dxdesigner795\MenuAdd.vbs`,使 `Dx Productivity` 菜单出现。
|
||||
|
||||
兼容性配置必须来自实际 probe 和现场验收。不能手工把 `live_acceptance.checked` 改成 `true`;未完成验收时,发布分类仍为 `evaluation-only`。
|
||||
|
||||
### 2. 准备输入
|
||||
|
||||
映射文件 `replacement.csv` 只有两个列名:
|
||||
|
||||
~~~csv
|
||||
old_part_number,new_part_number
|
||||
OLD-001,NEW-001
|
||||
OLD-002,NEW-002
|
||||
~~~
|
||||
|
||||
工具会拒绝空值、重复旧值、旧新相同、链式映射和循环映射。目标只能通过中央库 `Part Number` 指定,不能用元件名、符号名或引脚名代替。
|
||||
|
||||
项目列表 `projects.txt` 每行一个绝对 `.prj` 路径:
|
||||
|
||||
~~~text
|
||||
D:\Disposable\Board-A\Board-A.prj
|
||||
D:\Disposable\Board-B\Board-B.prj
|
||||
~~~
|
||||
|
||||
每个 old/new 映射都必须先在代表性、关闭的可丢弃副本上完成认证,并绑定中央库身份或目标指纹。当前交付没有公开的“生成认证”命令,不要伪造 `certifications.json`。
|
||||
|
||||
### 3. 启动作业
|
||||
|
||||
~~~powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Start-PartReplacement.ps1" -Mapping "D:\Qualification\replacement.csv" -Projects "D:\Qualification\projects.txt" -Certifications "D:\Qualification\certifications.json"
|
||||
~~~
|
||||
|
||||
暂停时保留控制台打印的绝对作业路径,用 `-ResumeJob` 恢复;恢复时不要再次传入 Mapping、Projects、Certifications 或 DiscoveryRoot:
|
||||
|
||||
~~~powershell
|
||||
& "C:\DxProductivity\integration\dxdesigner795\Start-PartReplacement.ps1" -ResumeJob "C:\DxProductivity\runs\part-replace-<GUID>"
|
||||
~~~
|
||||
|
||||
完整操作顺序和人工菜单动作见 [`docs/user/part-replacement.md`](docs/user/part-replacement.md)。
|
||||
|
||||
## 安全边界与恢复
|
||||
|
||||
- 写入前先固定图页清单、检查工程身份,并为实际命中的工程创建原理图精简备份;备份包含文件清单和 SHA-256。
|
||||
- 原生替换后检查 Part Number、RefDes、层级、放置单元、位置、旋转、镜像、门/槽、引脚集合、引脚坐标和网络身份。硬字段或连接无法证明未变时必须阻断。
|
||||
- 连续队列按“工程 → 图页 → 规则”串行执行,同一时间不打开多个工程;图页新增、删除或重命名会在下一次写入前停止。
|
||||
- 零命中会记录为 `no_match` 并跳过替换,不等于替换成功,也不代表其他图页没有该料号。
|
||||
- 保存、关闭、回读或监控结果不确定时保留保护锁、快照和证据,不要删除锁文件或强制重试。
|
||||
- 恢复只能针对原作业、原工程和绑定证据执行;恢复失败时保留失败树、备份和隔离证据,交给现场负责人调查。
|
||||
|
||||
Value 内容、样式继承和 `/NC` 同步规则见 [`docs/user/value-copy-and-layout.md`](docs/user/value-copy-and-layout.md);连续队列和长期证据保留见 [`docs/user/continuous-queue.md`](docs/user/continuous-queue.md)。
|
||||
|
||||
## 日志、报告与支持交接
|
||||
|
||||
排查问题时保留目标工程副本和整个数据目录,至少包括:
|
||||
|
||||
- `logs/application.log`;
|
||||
- 对应任务的 `events.jsonl`;
|
||||
- `quick-run/quick-part-replace.log`、`command.tsv`、`status.tsv`;
|
||||
- 替换前后快照、原生 helper 报告、`uncertain.flag`(如存在);
|
||||
- CLI 作业中的 `reports/impact.csv`、`reports/differences.json`、`reports/summary.html`。
|
||||
|
||||
交接记录还应包含 DxDesigner build、Windows 版本、工程规范路径、中央库身份/指纹、映射、操作员、日期及每份证据的 SHA-256。自动化回归和 mock 测试不能替代现场验收。
|
||||
|
||||
## 开发、测试与构建
|
||||
|
||||
运行完整测试:
|
||||
|
||||
~~~powershell
|
||||
.\.venv\Scripts\python.exe -m pytest -q
|
||||
~~~
|
||||
|
||||
构建 Windows 发布目录:
|
||||
|
||||
~~~powershell
|
||||
.\packaging\Build-DxPartReplace.ps1 -PythonExecutable ".\.venv\Scripts\python.exe"
|
||||
~~~
|
||||
|
||||
构建脚本会运行打包相关测试、调用 PyInstaller、检查 `QuickPartReplace.vbs` 是否完整复制,并启动 `--smoke-test` 验证 EXE 能创建和关闭日志。打包需要本机已注册的 DxDesigner EE 7.9.5 类型库;输出位于 `dist\DxPartReplace`。
|
||||
|
||||
## 文档索引
|
||||
|
||||
- [桌面任务中心与连续队列](docs/user/trial-task-center.md)
|
||||
- [DxDesigner 7.9.5 批处理操作指南](docs/user/part-replacement.md)
|
||||
- [连续队列细节与长期保留](docs/user/continuous-queue.md)
|
||||
- [Value、布局和 `/NC` 规则](docs/user/value-copy-and-layout.md)
|
||||
- [中断恢复](docs/user/interrupted-recovery.md)
|
||||
- [进度监控与超时](docs/user/progress-timeout.md)
|
||||
- [自动启动 DxDesigner](docs/user/automatic-designer-startup.md)
|
||||
- [现场验收清单](docs/testing/dxdesigner-795-part-replacement-live.md)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
```
|
||||
|
||||
源码默认数据目录为 `%LOCALAPPDATA%\DxProductivity\trial-task-center`,可用 `DX_TASK_CENTER_HOME` 指定独立目录。运行回归:`python -m pytest -q`;构建使用 `packaging/Build-DxPartReplace.ps1`。
|
||||
|
||||
- [完整桌面使用说明](docs/user/v1.1.0-project-tasks.md)
|
||||
- [中断核验与恢复](docs/user/interrupted-recovery.md)
|
||||
- [Value 与属性继承](docs/user/value-copy-and-layout.md)
|
||||
- [历史流程和独立 CLI 说明](docs/user/trial-task-center.md)
|
||||
- [CLI 与原生批处理集成](docs/user/part-replacement.md)
|
||||
- [V1.1.2 版本说明](docs/releases/v1.1.2.md)
|
||||
@@ -0,0 +1,11 @@
|
||||
# BOM 真人流程与重复执行
|
||||
|
||||
沿用当前 1.1.2 开发版和 11 列模板;用户已授权实现与在副本上实际替换。原 CAD PID 18732、原工程及原始 BOM 不操作;及时提交推送,不打包发布。
|
||||
|
||||
1. 导入反馈:提供结构化校验报告,显示总行数、校验通过/失败/未检查行数、工程、Excel 行号和原因。严格原 API 保持拒绝整批部分写入;UI 走报告入口,有错误时不保存或默默执行部分替换,修正后重新导入。
|
||||
2. 完成任务:显式“开始新一轮”保留旧命令、快照、计划和日志,重置运行状态并清除已过期目标基线,重新采集当前工程再编辑和执行;不解除中断/不确定状态。批规则编辑需兼顾同批仍完成的成员,以明确的新一轮范围保证一致性。
|
||||
3. 长路径:分别核对证据目录、Excel 路径、实际工程路径;通过真实 WSH 检查和实际 CAD 试验发现限制后修复。身份验证始终使用原始工程身份,运行别名不得让工程串位。
|
||||
4. 原生真人流程脚本:Qt 弹窗选择创建任务、导出默认模板、修改模板实际单元格、失败导入报告、成功导入预览、保存、点击执行、原生 Replace Part 保存回读;开始新一轮后再次导入与替换;用独立原生读取核对选中与未选中位号,检查私有桌面及自有 CAD 释放。
|
||||
5. 自动回归覆盖报告、事务、重跑状态和长路径身份;真实验证记录步骤耗时、路径长度、日志、前后器件和截图,报告任何实际限制。
|
||||
|
||||
并行所有权:报告代理持有 bom_plan.py/bom_batch.py/new bom_import_report.py/ui/project_plan.py;重跑代理持有 service.py/store reset helper/ui/main_window.py/run_panel.py/execution_state.py;主代理持有路径兼容、VBS 与真实探针,并接入报告服务 API。不得并行启动 CAD。
|
||||
@@ -0,0 +1,26 @@
|
||||
# 2026-10-15 全流程审查修复
|
||||
|
||||
范围:修复当前审查确认的八项问题,沿用 1.1.2 开发版和现有 11 列 BOM 模板;提交并推送当前开发分支,不打包、不发布。不操作用户原 CAD 进程。
|
||||
|
||||
## 约束与决策
|
||||
|
||||
- 同批规则通过服务层事务同步到所有未删除成员。任一成员被冻结或已有不可编辑执行证据时,拒绝整个修改,不做部分成功;已有历史分歧须明确报错,避免选中任务决定执行结果。
|
||||
- 规则是位号计划的默认值。修改规则时仅更新仍与旧默认值一致的新料号、NC;Value 开关和内容作为一组比较并传播,保留用户的手动覆盖与启用选择;界面明确显示实际执行使用位号计划。规则新增可以补全空默认值;删除不清空用户位号计划。历史规则合并后统一检查链式替换及循环;显式编辑或删除冲突规则可以解除历史分歧。
|
||||
- 位号基线允许执行前添加,既有 UID、位号、旧料号与旧 Value 必须全部仍在且一致。采集时包含既有旧料号,防止以不完整清单掩盖工程变化。预览不落库,确认批量事务后才保存。
|
||||
- 新 BOM 预览取代重叠的过期范围,同范围保留未重新导入工程的编辑。关闭窗口检查所有任务草稿,提供保存全部、放弃、取消;保存失败保持打开和草稿。
|
||||
- 回收站使用独立入口,保留搜索、排序、恢复、永久删除,不恢复常驻状态下拉框。
|
||||
- 原生读取比较基于规范化内容,枚举顺序变化可接受,实际字段变化及重复身份仍拒绝。
|
||||
- 采集与 BOM 导入共用可取消操作控制,显示每工程进度;取消传至原生启动及监控,等待自有会话安全释放,不保存部分计划。
|
||||
- 回归额外发现 Windows 临时共享冲突会令工程会话的继续指令读取失败;在 VBS 的继续指令读取处增加有界重试,保留后续 token 和 checkpoint 严格校验。
|
||||
|
||||
## 工作项
|
||||
|
||||
1. 位号清单扩展与 BOM 事务:`bom_batch.py`、`store_target_plan.py`,针对增量、身份变化、回滚增加回归。
|
||||
2. 界面草稿、预览、回收站:`ui/project_plan.py`、`ui/main_window.py`、`ui/task_list.py`,含关闭保护和采集取消界面接入。
|
||||
3. 原生顺序比较、取消:`discovery_cache.py`、`quick_run.py`、`project_discovery.py`、`inventory.py`,保留缓存一致性与私有桌面释放约束。
|
||||
4. 服务层批规则与默认值传播:`service.py` 与新独立规则模块;服务采集 API 接入取消进度,并扩展采集旧料号范围。
|
||||
5. 集成回归:针对现有捕获的七工程真实库存复放导入,完整适用测试;审查修复后的变更,分批 Git 提交推送。
|
||||
|
||||
接口:`preview_bom_batch` / `preview_batch`、`collect_target_inventory` / preparer 的库存读取使用可选关键字 `stop_event=None, on_progress=None`。`on_progress(message: str)` 仅通知,UI 用线程信号回主线程;取消抛出 `TaskCenterError('operation_cancelled', ...)`。未传控制参数时兼容已有两参数测试替身。
|
||||
|
||||
任务交叉:工作项 1 生产库存扩展接口,由 4 调用;1、3 共用取消参数,由 4 接线;2 消费 4 的公开 API。各项代码分别持有,集成时统一检查。
|
||||
@@ -0,0 +1,12 @@
|
||||
# 1.1.2 界面与吞吐优化
|
||||
|
||||
沿用用户已认可的审查方案;本轮不打包、不发布。
|
||||
|
||||
1. 修复 BOM 报告跨批次残留:按导入发起批次存储,切换时恢复,支持折叠摘要。
|
||||
2. 修复 980×700 长路径场景位号表不可见:路径省略与复制、可调表格/执行区、有限日志高度。
|
||||
3. 明确当前工程与本批范围,集中 Value 策略、区分自定义内容和实际回读,修正私有桌面说明。
|
||||
4. 整理操作层级、任务选中态、表格排序和样式;保留默认 BOM 与原位号计划入口。
|
||||
5. 对千步队列做一次定位分析,优化确认的热点,保留文件身份与不确定状态保护。
|
||||
6. 按行为运行针对性 Qt/执行回归,复放真实证据副本,记录截图和性能;分批提交并推送。
|
||||
|
||||
已验证的 CAD 替换与 Part Label 证据继续有效。UI 和纯队列优化无需重复修改真实工程。
|
||||
@@ -0,0 +1,261 @@
|
||||
{
|
||||
"version": "1.1.2",
|
||||
"release_date": "2026-10-16",
|
||||
"release_tag": "v1.1.2",
|
||||
"classification": "evaluation-only",
|
||||
"code_commit": "a16914bc7221dbc62c467b7a89e06ab0c40c1fbc",
|
||||
"accepted_exe_sha256": "73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75",
|
||||
"exe_sha256": "73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75",
|
||||
"vbs_sha256": "9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc",
|
||||
"program_files": {
|
||||
"DxPartReplace.exe": "73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75",
|
||||
"_internal/api-ms-win-core-console-l1-1-0.dll": "015bd08815c7b934a8952c3a7578e9ce59f21136e8a880d42bbd414bec2c6058",
|
||||
"_internal/api-ms-win-core-datetime-l1-1-0.dll": "5534812cdbdae94ba45cb216e5eb9af686b853948df54365103555abbbaf9d9a",
|
||||
"_internal/api-ms-win-core-debug-l1-1-0.dll": "837d2b1b2cd03e03fc6ccb050698b6b5763af17c201304872342a5eae9e0a2d2",
|
||||
"_internal/api-ms-win-core-errorhandling-l1-1-0.dll": "de43b165f568c276c00e95acd454e3092f352a18e95874595f4f4658c06d2ec7",
|
||||
"_internal/api-ms-win-core-fibers-l1-1-0.dll": "3cebc45bf479ad74cfabf2c6bfd4994d7ad639ed1221025981d19cedf9ce0416",
|
||||
"_internal/api-ms-win-core-fibers-l1-1-1.dll": "5ef70308bcca628ce6b0e2856b15b1c7ae340c3f9bbbc4c1071d8c191a34a5c3",
|
||||
"_internal/api-ms-win-core-file-l1-1-0.dll": "250ac829f2617bcac1c6e5b8c4f630462e20765863ba573526a3e11bbfb94a9a",
|
||||
"_internal/api-ms-win-core-file-l1-2-0.dll": "ae14079a114733f60ce87b92cba42acd8083c2cd67594e53bc37dc0b97a4b465",
|
||||
"_internal/api-ms-win-core-file-l2-1-0.dll": "914bf26a298713119477ea0a8e7bd43171b91344ebe24fb47ad77c49686e3d87",
|
||||
"_internal/api-ms-win-core-handle-l1-1-0.dll": "ab5489955e371b15f77906c08ec3c7affe2c7a46a08c514ca628768b4478974b",
|
||||
"_internal/api-ms-win-core-heap-l1-1-0.dll": "c70f9644d8377fa39c5b71f2e9734c1400d7598904fdeb772e8502099982dcb7",
|
||||
"_internal/api-ms-win-core-interlocked-l1-1-0.dll": "f8129710188e407bb0e6f46d30aeba277d67b947ece5fe09e883fde2323f3ae6",
|
||||
"_internal/api-ms-win-core-kernel32-legacy-l1-1-1.dll": "5200b16cb2ddc61cfc07373a9a84aa85a3ab50806ca96c879c883275832944c1",
|
||||
"_internal/api-ms-win-core-libraryloader-l1-1-0.dll": "48786fb88b001dcd1f63acea903d3ca9cc0b3060d5a325e3f2f3cbc3bfd53166",
|
||||
"_internal/api-ms-win-core-localization-l1-2-0.dll": "9ec3898f7eba91faa28b51616c211a2689e3a13aeef8de6e13cb674e49d689eb",
|
||||
"_internal/api-ms-win-core-memory-l1-1-0.dll": "3a6cbc524c99e1cd80d5368f5601402a37ad602528b1ab628093573ef638eb3b",
|
||||
"_internal/api-ms-win-core-namedpipe-l1-1-0.dll": "97145ef89c44949fcf0f04ac834a8bc7d687ef49ee73ae9fc32f3c11136b7201",
|
||||
"_internal/api-ms-win-core-processenvironment-l1-1-0.dll": "8bc7c10b1851aea644e9c9f381cdb935e091fee6b0be3d3aedc6fffaac96adb7",
|
||||
"_internal/api-ms-win-core-processthreads-l1-1-0.dll": "d8030b777617c71f0f94564607699dbf7561487d779db9756aed378c5675213f",
|
||||
"_internal/api-ms-win-core-processthreads-l1-1-1.dll": "f5e676713340f73a03a3d41a6ec9883b431da7d16c7f07bd0a920fb80e6c0753",
|
||||
"_internal/api-ms-win-core-profile-l1-1-0.dll": "f023d47e44d3eea6b0743580f57e8c6ba81e79d5ebfa7da26250076c647b980e",
|
||||
"_internal/api-ms-win-core-rtlsupport-l1-1-0.dll": "9746d8930704153578a628c010638a5f818ffe5a927e25591b108e256dc6afca",
|
||||
"_internal/api-ms-win-core-string-l1-1-0.dll": "7c53ae24c982d16ffd1bf7f918d115b11b7f30e57bc7feaa18cb9781e4abb926",
|
||||
"_internal/api-ms-win-core-synch-l1-1-0.dll": "56d9d62ca5dba79a6581b8d574a7d8b2a64a5ecb71e47dcf06ed0285708b1859",
|
||||
"_internal/api-ms-win-core-synch-l1-2-0.dll": "f6482bbec5612c39ecb4822787a333f2b7570f7a5f922a4059be41ba957bb372",
|
||||
"_internal/api-ms-win-core-sysinfo-l1-1-0.dll": "272d02765fdd3582618236c2d309abba069642f9bc1062ede069d0c144e17007",
|
||||
"_internal/api-ms-win-core-sysinfo-l1-2-0.dll": "8a0900788859d0eb51c2f48f50cc6ed376a120b518100fa20e11d7702ccde260",
|
||||
"_internal/api-ms-win-core-timezone-l1-1-0.dll": "ff35de6c03812b332e140f17dade25c5dd4775156da9eeb1eaae3fddd27236ec",
|
||||
"_internal/api-ms-win-core-util-l1-1-0.dll": "191ef3e98641a57296f19d572d8eb62489470ff1ef6030d136af170c2f835173",
|
||||
"_internal/api-ms-win-crt-conio-l1-1-0.dll": "54ee5ec719a051496ff60aa00dbeaa94b9a7d2cdac27fe9b7317f1a666b6a2aa",
|
||||
"_internal/api-ms-win-crt-convert-l1-1-0.dll": "8b94662429171019fcd63c70bbf2095a075170599704a5e7dcdbe3da13f3a429",
|
||||
"_internal/api-ms-win-crt-environment-l1-1-0.dll": "39e5929593709e8af3bc9e0a75ec1155778d6f4a247f4cdfc58928ad6db88434",
|
||||
"_internal/api-ms-win-crt-filesystem-l1-1-0.dll": "5a8ecebac32edf4e1f3c5c6c1c8ea1a1add6cda4f9c9cb26f752fb295bea6865",
|
||||
"_internal/api-ms-win-crt-heap-l1-1-0.dll": "c71080cbcb43bf1f8f3e391deb12a582eb0abefc80946f340675a2c616e4feb4",
|
||||
"_internal/api-ms-win-crt-locale-l1-1-0.dll": "6c68648e524187e03c4ad9aaa4a99113c6ee9f29fb39cc0ed93f951975138e63",
|
||||
"_internal/api-ms-win-crt-math-l1-1-0.dll": "d4fbcccbe29371cbce431e43b2eb4f7ba9a6f04a3d740a071f02457a505e9dc8",
|
||||
"_internal/api-ms-win-crt-process-l1-1-0.dll": "47c1935942e3ac0812e4dcf18c0e265e565f0194a3349111c299712f5565f7ac",
|
||||
"_internal/api-ms-win-crt-runtime-l1-1-0.dll": "72adc1b3677e0814d9c4ebf0964000e84bb2acf67336c8963061665e44f78029",
|
||||
"_internal/api-ms-win-crt-stdio-l1-1-0.dll": "900afc3989673c9bb1a687ed38c192f46db9e6ba6d11a668898a539e7fc23798",
|
||||
"_internal/api-ms-win-crt-string-l1-1-0.dll": "fcf12466cc12fd3b73611fc0763a5a1f9d44e90349513c34a0c83b0f36421793",
|
||||
"_internal/api-ms-win-crt-time-l1-1-0.dll": "886e57c4a6adb299b38f02945369f590a67da4e79a798359fc60aaa067212d7c",
|
||||
"_internal/api-ms-win-crt-utility-l1-1-0.dll": "5f8f26b216ade615b67a41f6fbbb910972fc6153315a65bb8f09912be50215b1",
|
||||
"_internal/base_library.zip": "9524f278655c7799933d381bbcf061bcf5961e8541460c279083ae1c61da277b",
|
||||
"_internal/libcrypto-3-x64.dll": "deabf96c676dd3652b32da2cb38a7dcc2f2daa8197ad19aba3c7a99454933c1e",
|
||||
"_internal/libcrypto-3.dll": "ccfffddcd3defb8d899026298af9af43bc186130f8483d77e97c93233d5f27d7",
|
||||
"_internal/libffi-8.dll": "eff52743773eb550fcc6ce3efc37c85724502233b6b002a35496d828bd7b280a",
|
||||
"_internal/libssl-3-x64.dll": "e84dcc3caca7720b2b426cb408df3129406e3b4d4ce4e729632bab319013ef6c",
|
||||
"_internal/libssl-3.dll": "007142039f04d04e0ed607bda53de095e5bc6a8a10d26ecedde94ea7d2d7eefe",
|
||||
"_internal/pyexpat.pyd": "d615e193d1affcdbfe504e90d3621cbdcff94bf72b79d899126534507fd6d27a",
|
||||
"_internal/python3.dll": "fb975a606e7fbf74f64260e3f60c3490b4f74a183c0926fd6ed1ac4c52ac7b1c",
|
||||
"_internal/python312.dll": "9a0e3435aaa680d868150f87ab3e388ad2eebc22f87e036155c7b4eda8cd2120",
|
||||
"_internal/select.pyd": "d4d7181b11db0bd22a6cd5cda6f8583d1f5c77615fd0a6ca33350619d6e0438a",
|
||||
"_internal/sqlite3.dll": "8daa45684bf6688fca28d956b2e8942f2fa98f656675ce68e6d61dd869848a7a",
|
||||
"_internal/ucrtbase.dll": "3239227d27667ba20d10a880751924e5719de0078f9fce232d149d383f7681f6",
|
||||
"_internal/unicodedata.pyd": "208ee1cd3cbad0828433ca7246b05be2b1ff5569983d27d296c0b38888585488",
|
||||
"_internal/VCRUNTIME140.dll": "052ad6a20d375957e82aa6a3c441ea548d89be0981516ca7eb306e063d5027f4",
|
||||
"_internal/VCRUNTIME140_1.dll": "6a99bc0128e0c7d6cbbf615fcc26909565e17d4ca3451b97f8987f9c6acbc6c8",
|
||||
"_internal/_bz2.pyd": "65f610646d10d5babea080e060d244b546ec52c54012e5e937dc72dcc2e2e7bc",
|
||||
"_internal/_ctypes.pyd": "0e56107a891100535f2da79d85a5ae65ff1227b4765bd108f8593ac1a1110d81",
|
||||
"_internal/_decimal.pyd": "aeacfead2befcc0768063a037bb64bd32109ae09cb144e5f571b04dd7965db9d",
|
||||
"_internal/_elementtree.pyd": "5009a9a53c03ef8387443b5cf6ce08e5c3a79727466a0b931c5bbca915bf89ca",
|
||||
"_internal/_hashlib.pyd": "03d233dbace599168eaffec823de6ed7beec8c2a4ebfe9b8a3d8e042a59af3ba",
|
||||
"_internal/_lzma.pyd": "e3deecc1f59a3b811c608861decd84de1e8df8bafd5e2b39188861318c5a38cf",
|
||||
"_internal/_multiprocessing.pyd": "2c636df7059cb0dd7e978dd735c7c5c8ddb09cf94754cf9e232296b96c5c545a",
|
||||
"_internal/_queue.pyd": "48e76e0ad63f6932b4a77b5819f41c1e7595636ca8d9e824f0943a14b8bb5035",
|
||||
"_internal/_socket.pyd": "3efa4636cf9e350856f6927d67a4c2564bf9bd2758a00bbf17d3aece5b60016d",
|
||||
"_internal/_sqlite3.pyd": "64b51df2805c58b023a875e8ae3be7ac7f61ef664f32ca6c90f6315da47ef0bc",
|
||||
"_internal/_ssl.pyd": "0bc527d2dbc50009f43b2ed5d5982c4f63f4b647647ffa9eda612dcda80f6040",
|
||||
"_internal/_uuid.pyd": "acce4f281d7ffb2dec0997527faf25b1df62ad7bd3032c568ddcf65c90edc867",
|
||||
"_internal/_wmi.pyd": "a980f1e7a29842bd946863fc2693fbeb555a9dc0f9e1630dfed9a2fcdef3ece2",
|
||||
"_internal/PIL/_avif.cp312-win_amd64.pyd": "6731dce52baab0b96b0eeb3c664844b5b42c2168ea8668af2430e2fbdd2dfbd8",
|
||||
"_internal/PIL/_imaging.cp312-win_amd64.pyd": "c8c519ec72bf75b2945b4fc4afa854af2fca8b970a403134f9ddda3e164d85e9",
|
||||
"_internal/PIL/_imagingcms.cp312-win_amd64.pyd": "c89c633ae1bf3f26a327d14ff688db66628e19c9866ab925479f27dcb60a2d6f",
|
||||
"_internal/PIL/_imagingmath.cp312-win_amd64.pyd": "82ac45c41a008854d05f67deda298b65a7bed850d0d79a3af861ed583f6e7d62",
|
||||
"_internal/PIL/_imagingtk.cp312-win_amd64.pyd": "690cc1cae4a2dc8594a342b9241e691dcc89d81dad4cddcefdf285275365a2b1",
|
||||
"_internal/PIL/_webp.cp312-win_amd64.pyd": "9823cebb84f425af3ac1e7437259bc176e7ad7e25d7fa829b0e1a3e55c11be70",
|
||||
"_internal/PySide6/MSVCP140.dll": "4c667b706893593812cd111b369ba6a77f54d1f1b1ae87cf3bf37692663cfba2",
|
||||
"_internal/PySide6/MSVCP140_1.dll": "d419d24b0a76366f5c9d908b0e45fe70e9e9154bb8ad5f3de42070f2337f857b",
|
||||
"_internal/PySide6/MSVCP140_2.dll": "89917964abb6ca16a260cab258e180c3abc239b5af00eed659d0edf0efdd339c",
|
||||
"_internal/PySide6/opengl32sw.dll": "34b444c016289b560662ff896deceb7f4b2c0723aed3d319ae167c9186ce42b3",
|
||||
"_internal/PySide6/pyside6.abi3.dll": "d0b5c701fb3a8ea839e72b602058f3960935156ebeca084893c54c99e54dd707",
|
||||
"_internal/PySide6/Qt6Core.dll": "d6a3c37c5263c5d418fc0e80b722bc9fca7c0859e6f635f9624a2fde00bdc653",
|
||||
"_internal/PySide6/Qt6Gui.dll": "ae29b005f51b6850bf57fa06fced0dc8c7039fd6fafc3bfbcfe76e38adc7abf1",
|
||||
"_internal/PySide6/Qt6Network.dll": "dd3512d1c5ed062d30c98426cd0a850f13e0cf31437afb5b0b474132b9c52922",
|
||||
"_internal/PySide6/Qt6OpenGL.dll": "d51088f16db8c96dba7ef3c1474e611adb3ebdb211fea35b8e755d2a7407f7ad",
|
||||
"_internal/PySide6/Qt6Svg.dll": "1eac8f7415b311a88cb3cb4e25c3098d0e059c24c831fbbb13f43a80f0df06b7",
|
||||
"_internal/PySide6/Qt6VirtualKeyboard.dll": "a14fac89759569965dbeb45b2a13e592c0bce0cc559adaa32145fcb92de016f9",
|
||||
"_internal/PySide6/Qt6Widgets.dll": "ff0df9e2e6827e035f0731a4cedfc6333f4602bca00775e56346f27032406b74",
|
||||
"_internal/PySide6/QtCore.pyd": "74f96322c5e9cea73aefd2ed5870e5275336b31f552fcd32f12fc81d23f1bc6f",
|
||||
"_internal/PySide6/QtGui.pyd": "7bef20046045199c037b7cbfedaa1c5464730fa948b2c9ec8afbf718e63774d4",
|
||||
"_internal/PySide6/QtNetwork.pyd": "c5038bb71fc9d57330fa2d8eeec65aab69fcf02687cc8f54dbfb5995cfec6a71",
|
||||
"_internal/PySide6/QtWidgets.pyd": "f12f4ca641998e5706d5f7b0023147d573f0f2d2361e26dadf31bdbf05fbfd1d",
|
||||
"_internal/PySide6/VCRUNTIME140.dll": "f893ae75a1a24eea174d982f94bc80ce2448201eaa919a73c0653a5657685de4",
|
||||
"_internal/PySide6/VCRUNTIME140_1.dll": "48aa2783793ea18ab3c2c71d420d4fff9814e662a1ff810053c6e5250061a716",
|
||||
"_internal/pythonwin/win32ui.pyd": "1fc9f8875056b175077ed04e7d93599f58b3cff80bd2077f5f8c8aaa144ab833",
|
||||
"_internal/pywin32_system32/pythoncom312.dll": "18e5d69b62110f48da01842f9ddfd99d06cc561f0866371714ec6534fcb4e5ec",
|
||||
"_internal/pywin32_system32/pywintypes312.dll": "9bd7f8c39a84d7b1ea43bfcd33c04631c60f4ff28167e82bb21987cc1c353766",
|
||||
"_internal/shiboken6/MSVCP140.dll": "fd4a8c046fa3fea9ca6132f50cf8a56cf1e783b2d3093ba5c85fa063bc6b3845",
|
||||
"_internal/shiboken6/Shiboken.pyd": "2f6f3a694f675b1dafdae26903191613c02866ab48e02591ae34ca1a3b1284f1",
|
||||
"_internal/shiboken6/shiboken6.abi3.dll": "de3c6b2ed5f75c9ac0de4a6844b653b3b9d09263ce68c2b5fc25a96c5c3e8469",
|
||||
"_internal/shiboken6/VCRUNTIME140.dll": "de617641d82eac15595d2e39394163ac33e49bb032cf2c2ea0044ed39d3675e9",
|
||||
"_internal/shiboken6/VCRUNTIME140_1.dll": "fa577d54bd10a91e52472da784a619da6cf241af45f0a0c48b27e91fa0fe6104",
|
||||
"_internal/win32/win32api.pyd": "8e09d7aa57dc33b663afd219fab21b6a70e9d98cc74a044df4d6cd94799d98c2",
|
||||
"_internal/win32/win32event.pyd": "a6b896456443447a663fe25783dfa95929dc8ade8d7970fd78d3b4e65100371e",
|
||||
"_internal/win32/win32evtlog.pyd": "f6f8814147d3ca2761d351c0c86e7142b15b63605a502e5eb62d0bbd2b88e73f",
|
||||
"_internal/win32/win32file.pyd": "359ef2dc11546f619a9ac53c01a399d621c093b7cfc843fb9d7b211d0b15e103",
|
||||
"_internal/win32/win32gui.pyd": "f468a03be44633fdeabc08b4a9f8b135f9e31d74b935f85631c23c7fbb9367fa",
|
||||
"_internal/win32/win32job.pyd": "bfc31798ccf0bcf9b4453903918866abcfb546f5b1d6bd59e4691b83cbe44fa8",
|
||||
"_internal/win32/win32process.pyd": "6d02ff9b22afa97bdb26d99454462a612848efdc3d0beb54cea2b4912d07a14c",
|
||||
"_internal/win32/win32service.pyd": "5d159572b89146a13117f24ef0b232d6c24982d206c73189f4952259303de496",
|
||||
"_internal/win32/win32trace.pyd": "3dd640518a4fb1084cfc38a0e312b87ff1b0b0a74535e320bb9936441b9ed8ca",
|
||||
"_internal/win32/_win32sysloader.pyd": "db277aae2b8417dbd01435a8691cc74707f6699ae3199e1b205f609cefa5ad24",
|
||||
"_internal/legacy-runtime/dxdesigner795/QuickPartReplace.vbs": "9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc",
|
||||
"_internal/PySide6/translations/qtbase_ar.qm": "e03fe68d83201543698fd7fe267dd5dfc5bfd195147e74ff2f19ac3491401263",
|
||||
"_internal/PySide6/translations/qtbase_bg.qm": "e448ac9e3f16c29eb27af3012efe21052daa78fabfb34cd6dff2f69ee3bd3cdb",
|
||||
"_internal/PySide6/translations/qtbase_ca.qm": "5298532fc52ffbc4e2c549f277151a61e741921c834286f7c04d3753677b6b04",
|
||||
"_internal/PySide6/translations/qtbase_cs.qm": "03028b42df5479270371e4c3bdc7df2f56cbbe6dda956a2864ac6f6415861fe8",
|
||||
"_internal/PySide6/translations/qtbase_da.qm": "7d1e5ca3310b54d104c19bf2abd402b38e584e87039a70e153c4a9af74b25c22",
|
||||
"_internal/PySide6/translations/qtbase_de.qm": "ed828a83dfaa51944f166c842155b48ab3bd7cb2c46dcd96269eb5d48af4f63f",
|
||||
"_internal/PySide6/translations/qtbase_en.qm": "494ac9a2b2cb2fdeced353f4a9f898ed8dcf616e9bc667438c62681e3f7f79cf",
|
||||
"_internal/PySide6/translations/qtbase_es.qm": "4ffda56ba3bb5414ab0482d1dde64a6f226e3488f6b7f3f11a150e01f53fa4c8",
|
||||
"_internal/PySide6/translations/qtbase_fa.qm": "f78e59b5bdd586181a999034ba418868ed17fe9c05707fb65e523f70e92253d2",
|
||||
"_internal/PySide6/translations/qtbase_fi.qm": "e47fe13713e184d07fa4495dde0c589b0e8f562e91574a3558a9363443a4fa72",
|
||||
"_internal/PySide6/translations/qtbase_fr.qm": "314243a55c32679ad473fdfe48dc7d66e973ad0fc8bf2164480c58dddb50c1a7",
|
||||
"_internal/PySide6/translations/qtbase_gd.qm": "63b439dd44139aa3aed54c2ebe03fa9bc77f22c14ed8fba8eff2608445bb233d",
|
||||
"_internal/PySide6/translations/qtbase_he.qm": "e1ebca16afe8994356f81ca007fbdb9ddf865842010fe908923d873b687cad3f",
|
||||
"_internal/PySide6/translations/qtbase_hr.qm": "bb9eec9a9a652c1340dc75eb2e749be50df00f885b3d6900dfc76799c45b244d",
|
||||
"_internal/PySide6/translations/qtbase_hu.qm": "98463295539d769c8645a0b7fb95ad38454cfd0b14f36af485513f036ddbbbc6",
|
||||
"_internal/PySide6/translations/qtbase_it.qm": "7808ed542a7833c4bd94ec8bdfbbca00bb4f2fe15979b9121ce3249323687300",
|
||||
"_internal/PySide6/translations/qtbase_ja.qm": "2b9581c69b975f59be505b127cd3c19d403ef3d12e0e8386fb97238223e9c1df",
|
||||
"_internal/PySide6/translations/qtbase_ka.qm": "e55e4b72fa620bebee5297ca59dfe2f49894a1e544f2b7485b1cfd8829289d6f",
|
||||
"_internal/PySide6/translations/qtbase_ko.qm": "0179ed1b136e1cb3f583351eaa2c545ba3d83a6ee3f82c32505926a1a5f5f183",
|
||||
"_internal/PySide6/translations/qtbase_lg.qm": "31c0cc4ce13b1d74fe0c19ed0b47638fb31e20c93ee08092533e884007aebfb5",
|
||||
"_internal/PySide6/translations/qtbase_lv.qm": "846e047573ae40c83671c3ba7f73e27efc24b98c82701da0df9973e574178bb2",
|
||||
"_internal/PySide6/translations/qtbase_nl.qm": "f61513bcdbb6ad800585f9437a95d018aab17fa12ee414aa31462ff279d8240e",
|
||||
"_internal/PySide6/translations/qtbase_nn.qm": "f9f2fb7c60e7fcb38bbd3c1314ef122145594265e20b0659ff00004baab13ac7",
|
||||
"_internal/PySide6/translations/qtbase_pl.qm": "3cf6b5c14d5eb0cf81e9af2066e66b3aa579a6b9b3c323ed670761f6254a8c54",
|
||||
"_internal/PySide6/translations/qtbase_pt_BR.qm": "3475d61604b938d459949801a906dbd34a8ca824ade94120015d676e208da859",
|
||||
"_internal/PySide6/translations/qtbase_ru.qm": "3da6605668f9178d11a838c4515478084dcfb4f9cf22f99d7a92b492db9c224b",
|
||||
"_internal/PySide6/translations/qtbase_sk.qm": "d586ae2c314074cf398417fdecb40709d5478dfeb0a67c2fe60d509ee9b59ed7",
|
||||
"_internal/PySide6/translations/qtbase_sv.qm": "5a2178dd2c03cc4516697f1fb0049649c9ed53f5cde6b937786733dae06aeda8",
|
||||
"_internal/PySide6/translations/qtbase_tr.qm": "353fdfd7165659a49212e7a25bf91c0a71588e52c836f7496640f26782414634",
|
||||
"_internal/PySide6/translations/qtbase_uk.qm": "51b8ff55b37dc5907d637a8ddda12fbe816852b0244c74eb4f0fb84867a786e0",
|
||||
"_internal/PySide6/translations/qtbase_zh_CN.qm": "0481a9b92a6f0578400e960a7d5ee70217a6a450eaf7f98b7d32b8dbd0d58616",
|
||||
"_internal/PySide6/translations/qtbase_zh_TW.qm": "21012b2b427f8d09d31ce9cae582ca27955b478ca3dc2ec18a3068d808638c6a",
|
||||
"_internal/PySide6/translations/qt_ar.qm": "b11333c520ccd8e375cde20985df402d586a1a95e0796313bbeb9f717d4db22e",
|
||||
"_internal/PySide6/translations/qt_bg.qm": "1e22ee126ec9f76031d880285a907b3a0c4510392319ff700dcdee964abbb1ad",
|
||||
"_internal/PySide6/translations/qt_ca.qm": "17ab2623c7f6e8def44b3dbcb517544185817d65f1298ddb10ef71136f232bdc",
|
||||
"_internal/PySide6/translations/qt_cs.qm": "c585918fb1d4821a054ea40bdcf279f275ca76c88a5793f433dac6a611ac7e8f",
|
||||
"_internal/PySide6/translations/qt_da.qm": "f6773c672acb73fdef6e092060d69d1e5dfee840012bac912d1e92de28714386",
|
||||
"_internal/PySide6/translations/qt_de.qm": "0401c316aa3b50a172eb44a4ff1ec384924073beec7c928ef888ec48e4612688",
|
||||
"_internal/PySide6/translations/qt_en.qm": "494ac9a2b2cb2fdeced353f4a9f898ed8dcf616e9bc667438c62681e3f7f79cf",
|
||||
"_internal/PySide6/translations/qt_es.qm": "648ed4519bc45d7a4779479a7626ea16cf9aa23e93a0b178546cc47bea0591ab",
|
||||
"_internal/PySide6/translations/qt_fa.qm": "3f4c989c6b2990d80cc6299408214b31698923b52f154483b3371875de91f88e",
|
||||
"_internal/PySide6/translations/qt_fi.qm": "342d01c7eeb234e431d0506821c4cd03c0433115d8d63fee3357be2331858879",
|
||||
"_internal/PySide6/translations/qt_fr.qm": "c896a38892a92346b033793d56440993236b23e47e06f3974afdb0552f628387",
|
||||
"_internal/PySide6/translations/qt_gd.qm": "49df855a004a17950338af3146466f6df4d5852410bd0b58ea80e0d0203a9d24",
|
||||
"_internal/PySide6/translations/qt_gl.qm": "204a01ac7deb6b5bae193afecbd1e50d18c73bf7d94badeb2bbfdf6123c4ed93",
|
||||
"_internal/PySide6/translations/qt_he.qm": "36f01fff2f25e116d4b7af78097b7e49520fd5b7fb6fb120e40be228c05c045f",
|
||||
"_internal/PySide6/translations/qt_help_ar.qm": "222088c9752d1cc3bab985ef2dc77e5ae78578dce18a61ec15b39f02e588163d",
|
||||
"_internal/PySide6/translations/qt_help_bg.qm": "cbcdd1e0bbae332d80ddb0a286056f17c824fa28d353d7fdf12fc97d9f6fe054",
|
||||
"_internal/PySide6/translations/qt_help_ca.qm": "fe40962c814a9f489e18d033e4aaabe435232c9bcf760830c6165af507cca80e",
|
||||
"_internal/PySide6/translations/qt_help_cs.qm": "4ac56fc63e400943bab13f1d4c418502138908e1d488c24aee6131d3d17552aa",
|
||||
"_internal/PySide6/translations/qt_help_da.qm": "6bb092552a398687119f6d52145f04bf8373977446d8f00c0dcbd56b96829f0f",
|
||||
"_internal/PySide6/translations/qt_help_de.qm": "037bc99abf98571ae9375c2513536c15b571d66406c36c1de447b547ff539c07",
|
||||
"_internal/PySide6/translations/qt_help_en.qm": "494ac9a2b2cb2fdeced353f4a9f898ed8dcf616e9bc667438c62681e3f7f79cf",
|
||||
"_internal/PySide6/translations/qt_help_es.qm": "fd16b279f8cf69077f75e94d90c9c07a2afff3948a579e3789f5ffb5e5f4202d",
|
||||
"_internal/PySide6/translations/qt_help_fr.qm": "875ee2dcdc64e3dea888d84048e382d3921a175f12847de2e6b1cb12ad9add50",
|
||||
"_internal/PySide6/translations/qt_help_gl.qm": "7399a248609974773f60866c87b78ea7dfbc4f750313d692f7886cd763883c9f",
|
||||
"_internal/PySide6/translations/qt_help_hr.qm": "8c8cc3c5b1ab2b074f82937001b896603420ef75592b3b78172177360dd7ea61",
|
||||
"_internal/PySide6/translations/qt_help_hu.qm": "7be32e015119c969453abb6e8f3fb377963a69fafb10c27b796737b5eb283eaf",
|
||||
"_internal/PySide6/translations/qt_help_it.qm": "316fe8d0815e2b4b396895beb38ef1a40431915b5e054df80f4c0cd556f26e4b",
|
||||
"_internal/PySide6/translations/qt_help_ja.qm": "ae603b2c0d434d40cde433ffcba65f9ee27978a9e19316007be7fe782a5b8b47",
|
||||
"_internal/PySide6/translations/qt_help_ka.qm": "159c74f94b384b5ee6afdf38b6cfc4806bc99ecf73be02d4a7021d4ceba7ec7e",
|
||||
"_internal/PySide6/translations/qt_help_ko.qm": "f11c64694e8e34e1d2c46c1a1d15d6ba9f2db7b61de4fdf54eca5ab977c3e052",
|
||||
"_internal/PySide6/translations/qt_help_nl.qm": "44a8a0daf775d14352180052d13f623814d7bdf98e2c5c80144b7bf74214e3b0",
|
||||
"_internal/PySide6/translations/qt_help_nn.qm": "4c8a7213942078e4f72f5babd26c41b77ace70189714a58b5504a7d5ad0193dc",
|
||||
"_internal/PySide6/translations/qt_help_pl.qm": "cc6cb4d8c54086224672f2e49e623c8cb7c0c1cd65b8d5ecd42fc9ba3a6065bd",
|
||||
"_internal/PySide6/translations/qt_help_pt_BR.qm": "b4015c5d519b4fe93c00bf734d1742e4f0094d89862664d548eb64a46a2feae7",
|
||||
"_internal/PySide6/translations/qt_help_ru.qm": "557b644e6da5f1ec720ef93965617087e4d1f40b2494cc5aa524cf3796108de7",
|
||||
"_internal/PySide6/translations/qt_help_sk.qm": "f41e33e1d790bd0d3eb180f1f875bc191fe74773628f25c2cad95e1402e66867",
|
||||
"_internal/PySide6/translations/qt_help_sl.qm": "2ec955e662407ebcd8dcdae5aaa21e4108e0b5b0aee0e9db712c27072943535f",
|
||||
"_internal/PySide6/translations/qt_help_sv.qm": "95bdb03dbaa6dbdfda46c249e9ccce9a353f71ddb8b112961e8b005b2c60b13c",
|
||||
"_internal/PySide6/translations/qt_help_tr.qm": "81da2f88cd624097581f2d29b10311796bcd9ab289e65883346d276110542d28",
|
||||
"_internal/PySide6/translations/qt_help_uk.qm": "497cfc473684692ee44d7a3795e8fb2270c57069fd9eb98a615dd29ab9be8a7c",
|
||||
"_internal/PySide6/translations/qt_help_zh_CN.qm": "e256d1f6034a5a5521c62f129f91731216e474f71e1d9caea3d3dcb11b670deb",
|
||||
"_internal/PySide6/translations/qt_help_zh_TW.qm": "40112812abb43853d678cc6d97729f21f21b3a7321c827fc9d18f6c936447d1e",
|
||||
"_internal/PySide6/translations/qt_hr.qm": "fc9e4146f33be3d09b234be01e56235d3037d8d82d64f0700b4d4a6e253a61a7",
|
||||
"_internal/PySide6/translations/qt_hu.qm": "c2fa649f167cdb801d1cc0cb69c1d93594fd5bf8c0b7e79b969935da5c3e19aa",
|
||||
"_internal/PySide6/translations/qt_it.qm": "9e7a18bc20ebeec54baaaf41c918a74534511271f796dffffd0f9b9ec31c68d3",
|
||||
"_internal/PySide6/translations/qt_ja.qm": "0f5fe50452947d1ee9755249d860354bff6977279b4c496a5bc77e5b89dd745e",
|
||||
"_internal/PySide6/translations/qt_ka.qm": "00b67c6dfc255079b5b98a5640f82519c96b2520a028682fba4078b39d743eaa",
|
||||
"_internal/PySide6/translations/qt_ko.qm": "1d254b535e1cb35cbcad8210b15b89f4488159826bf35b4504696263dd102fa3",
|
||||
"_internal/PySide6/translations/qt_lg.qm": "6ba668501f4c040c66da1bdc022362da3c8cf663da6aa484cbdb599028da98ed",
|
||||
"_internal/PySide6/translations/qt_lt.qm": "47eb5f97467df769261421d54a5bea1131c9fb9b6388791d38bb6574335b64bf",
|
||||
"_internal/PySide6/translations/qt_lv.qm": "addeca285282338294f24ca50d37d08a5f68d3785d0a94af86dd4ec8f2a3b449",
|
||||
"_internal/PySide6/translations/qt_nl.qm": "39e870cbd25c0f97fa9b1828d5ea1ed9849857a2e26c5321b3f13c76be8f0548",
|
||||
"_internal/PySide6/translations/qt_nn.qm": "4e544e23f75eafe1553dc896973db23b5795cd243786d5c653cc0f36a46ca74f",
|
||||
"_internal/PySide6/translations/qt_pl.qm": "e6890afa0caf0f6db0248e4c94f6016b8ec8bc266f1e0e9b8f01e8ea912cf968",
|
||||
"_internal/PySide6/translations/qt_pt_BR.qm": "0e24c58e35271853f8cdfb3f0f7b0741b5a9a588e43cdec62ae85a3842771e0a",
|
||||
"_internal/PySide6/translations/qt_pt_PT.qm": "2c1e7bbf5168a64b43752dd4c547601c0bde6d610f8671fa3e3af38597e84783",
|
||||
"_internal/PySide6/translations/qt_ru.qm": "1b388e2d6d1bd405603e794e498c6d7ec5f5a5ad819243546f6399181da36758",
|
||||
"_internal/PySide6/translations/qt_sk.qm": "840c3b01c89df976fc1d2e5bfc6fc84b65666b8a3ceb4cbf5aa0c22af3d2a383",
|
||||
"_internal/PySide6/translations/qt_sl.qm": "c44e0313a9414cc0e490b65b0c036fa11bca959353b228886547bc2c8492034f",
|
||||
"_internal/PySide6/translations/qt_sv.qm": "daaae448e0814b469ac3d7a91096fde15491600a6b8bc6c01508425fb5e8b3ec",
|
||||
"_internal/PySide6/translations/qt_tr.qm": "59e8a0c411be3b0802a68561b090f182099d6b75c4fe46f398e55f11528e11b9",
|
||||
"_internal/PySide6/translations/qt_uk.qm": "053ec1f677c4dba48c6a97eb28f4fc78c1511324d1843d7f4cec2c7c00a66145",
|
||||
"_internal/PySide6/translations/qt_zh_CN.qm": "c0e29d32c9540a7e78643b74214e633c56f6ab11f018e516629f2c11b1fb09fc",
|
||||
"_internal/PySide6/translations/qt_zh_TW.qm": "24e226954491689549a1a1990db3b8cb78888008d8163b2fd2442b772b6d1b5f",
|
||||
"_internal/PySide6/plugins/generic/qtuiotouchplugin.dll": "aa9080fa8b1c3cf4d3790c1eecf4a1f5c796ce58f31f80910357578f20fd80ac",
|
||||
"_internal/PySide6/plugins/iconengines/qsvgicon.dll": "5bb97b6f114682ae0b5f42b23b6818aece6499bad88dac80a138efa8a88c12bc",
|
||||
"_internal/PySide6/plugins/imageformats/qgif.dll": "d301d7e9a68327692e4c76faa6b125517730b22c68f4de7f09fda9d4ac0ddee1",
|
||||
"_internal/PySide6/plugins/imageformats/qicns.dll": "49db148fea9f01e9953fd0a771d16cfaf364599f07aab3634d4f5c7c25abd78a",
|
||||
"_internal/PySide6/plugins/imageformats/qico.dll": "1684fd56f1758167f7b3ac011264ae5859b3cf6113e381626ec3dc1d3122fe52",
|
||||
"_internal/PySide6/plugins/imageformats/qjpeg.dll": "6517345ac19f5c489daeadc029d0018bbdc09d8e1031c60d714557972f22c6d4",
|
||||
"_internal/PySide6/plugins/imageformats/qsvg.dll": "4b7d65ba39be58cb469b54b5fdee2987871d67e5050cd70724016e09966e54f6",
|
||||
"_internal/PySide6/plugins/imageformats/qtga.dll": "6b0381150070fcd4224597fe73c68b47055b30b418aa14794c94c5007d14ca5d",
|
||||
"_internal/PySide6/plugins/imageformats/qtiff.dll": "3d6ea04da215ee2a9459399fb9f6d73cad8787944b9d450399025bcd39d020b5",
|
||||
"_internal/PySide6/plugins/imageformats/qwbmp.dll": "1a4596509987e9557edda69ed13cdd0d33f4ebda72e464ddc00a566bec05f151",
|
||||
"_internal/PySide6/plugins/imageformats/qwebp.dll": "6b2c53cc4423140c29a6a1eb6dd908016e09d794b5739a05a3a39c8c49a0df8a",
|
||||
"_internal/PySide6/plugins/networkinformation/qnetworklistmanager.dll": "e571a4b4e582738cd1bc4889cb2896635c2543baff408442701b6706a1b4a86e",
|
||||
"_internal/PySide6/plugins/platforminputcontexts/qtvirtualkeyboardplugin.dll": "e10c64dd2ae4f9b756ec1ebe3950a05e345ba40834b7be2900af426623d85475",
|
||||
"_internal/PySide6/plugins/platforms/qdirect2d.dll": "56f41ad523d016fe2cf2c90fae158e21766d1fcd021bced1a3704c6da0f00c98",
|
||||
"_internal/PySide6/plugins/platforms/qminimal.dll": "768a9c6dbb1c86abbefa2ff9d7e98cdfb4fdc9292eb8d64195bb6d23939a5344",
|
||||
"_internal/PySide6/plugins/platforms/qoffscreen.dll": "e776251668440169ed18a2fe1b236762d514ef5244639cbb559b5a77ddd38954",
|
||||
"_internal/PySide6/plugins/platforms/qwindows.dll": "bf6dbc3009f386fa22f0ced560bea6bbf3e0e0b4442d2fb855db67cffce49dbf",
|
||||
"_internal/PySide6/plugins/styles/qmodernwindowsstyle.dll": "a7a6424c23bf371bd28a404a196b210971726f6f2a87b63aac185a5e6e40da71",
|
||||
"_internal/PySide6/plugins/tls/qcertonlybackend.dll": "67be4d333a0f489d02714169a6ec54eaa80efa649d733fcbeb81881ecb02b4f3",
|
||||
"_internal/PySide6/plugins/tls/qopensslbackend.dll": "7a0727417b8e21e64d9a7cf0f390bc85b3e337b4eef5ac977f49659d97e6b552",
|
||||
"_internal/PySide6/plugins/tls/qschannelbackend.dll": "14abc5b245c0f2e03f7bc0b474a8db2ecb441c7300a8a8b16fb865eaf2674619"
|
||||
},
|
||||
"program_files_equal_accepted": true,
|
||||
"data_directory_excluded": true,
|
||||
"gif_sha256": "4b3fed6694ab08d921ca88f92babb0af16380489533d9ed43b143e720d6e04d3",
|
||||
"bom_sha256": "13e0f1f45b117f3fd18db80790881e932842c4cabfe750f744fab8cb884f5589",
|
||||
"acceptance_report": "docs/testing/2026-10-15-packaged-acceptance.md",
|
||||
"build_checks": {
|
||||
"passed": 369,
|
||||
"seconds": 63.39
|
||||
},
|
||||
"final_source_checks": {
|
||||
"passed": 369,
|
||||
"seconds": 83.97
|
||||
},
|
||||
"zip_sha256": "2fc74a711e6c5876425d9ece3445ae322d67db9cb34260c4b8ed80f8bbd60f80",
|
||||
"zip_bytes": 55257821,
|
||||
"file_count": 238,
|
||||
"extracted_zip_smoke": true,
|
||||
"binary_unchanged_since_native_acceptance": true
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
# V1.1.2 发布构建记录
|
||||
|
||||
发布日期:2026-10-16。本次沿用 `a16914bc7221dbc62c467b7a89e06ab0c40c1fbc` 构建并完成实机验收的程序文件,更新中文 README、使用说明、恢复说明、版本说明、通用 BOM 空表和离线 GIF 后重新压缩。版本标签另包含后续文档与验收工具;`src`、`integration`、`packaging` 和 `pyproject.toml` 与该构建提交无差异。
|
||||
|
||||
- 原标准构建检查:369 passed,63.39 秒。
|
||||
- 本次发布前源码检查:369 passed,83.97 秒,1 条 pywinauto COM STA 提示。
|
||||
- 发布包:`DxPartReplace-1.1.2.zip`,55,257,821 字节,238 个文件,无本机 `data`、数据库、任务日志或工程备份。
|
||||
- ZIP SHA256:`2fc74a711e6c5876425d9ece3445ae322d67db9cb34260c4b8ed80f8bbd60f80`。
|
||||
- EXE SHA256:`73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75`。
|
||||
- VBS SHA256:`9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc`。
|
||||
- 完整 EXE 与 `_internal` 文件清单逐一哈希核对,与实机验收版本一致。清单见 [JSON](v1.1.2-build.json)。
|
||||
- 最终 ZIP 再次解压,移除源码导入路径后运行 `--smoke-test`,退出码 0,启动版本和正常退出日志通过;离线 GIF 与仓库文件哈希相符,BOM 空表为原模板 11 列且不含工程数据。
|
||||
|
||||
本轮未重新执行 CAD 替换。真实两工程替换、独立读取、Part Label→Value、未选位号保留、新轮次、旧版元数据兼容及 10 个后台会话释放使用同一程序文件的 [成品验收证据](../testing/2026-10-15-packaged-acceptance.md)。程序身份不变,不能把此次启动检查描述成又完成一次实际替换。
|
||||
|
||||
附件为便携 ZIP、`SHA256SUMS-1.1.2.txt`、`release-manifest-1.1.2.json`、`BOM-template.xlsx`、`window-tutorial-1.1.2.gif`。仓库默认分支和版本标签均包含中文 README 及 GIF。发布时逐项回下载核对本地 SHA256,未通过时不解除草稿状态。
|
||||
@@ -0,0 +1,37 @@
|
||||
# DxPartReplace V1.1.2
|
||||
|
||||
发布日期:2026-10-16。交付级别:**evaluation-only(评估试用)**。
|
||||
|
||||
V1.1.2 完善工程任务、BOM 计划和结果查看流程,加入窗口 GIF 中文教程。沿用已完成本机实际替换验收的程序文件,发布包重新整理中文说明与离线 GIF,不包含本机任务数据库、日志或工程备份。
|
||||
|
||||
## 下载与上手
|
||||
|
||||
下载附件 `DxPartReplace-1.1.2.zip`,完整解压后运行 `DxPartReplace.exe`。无需安装 Python,本机需要可用的 DxDesigner / Expedition Enterprise 7.9.5、许可证和中央库。
|
||||
|
||||
[中文教程与 GIF](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/src/tag/v1.1.2/README.md) · [窗口 GIF](https://git.simgreek.com/simgreek/dxdesigner-part-replacement/raw/tag/v1.1.2/docs/user/media/v1.1.2-window-bom-tutorial.gif)
|
||||
|
||||
## 主要更新
|
||||
|
||||
- 一工程一任务,同批工程顺序执行;左侧搜索和显示排序不改变执行范围。
|
||||
- 已导入工程即可导出默认 11 列 BOM,同批工程共用一张表,按工程路径分配至任务,无需先采集。
|
||||
- 一行支持多个位号,只替换启用目标;NC 默认开启,可逐行关闭,自定义 Value 优先。
|
||||
- BOM 先整批校验再预览,报告通过、失败、未检查数量及 Excel 行号;点击保存才原子写入计划,有错误不部分保存。
|
||||
- 规则表、位号表、结果表使用模型视图;详情按需创建,关闭释放,隐藏页不反复渲染,草稿独立保留。
|
||||
- 显示实际回读的位号、旧新料号和核验状态,日志支持分页;已完成任务可创建新轮次,旧证据归档保留。
|
||||
- 完善工程和证据长路径访问、受监督后台执行、清理与不确定状态保护。
|
||||
|
||||
## 本机验收
|
||||
|
||||
- 标准构建检查 369 项通过,冻结 EXE 启动与退出通过。
|
||||
- 两工程实际 BOM 流程、原生替换、保存重开和全新 CAD 独立回读通过;RV05 替换、RV11 保留,启用复制后 Value 与目标 Part Label 均回读为 0R。
|
||||
- 297 字符工程路径、错误/正确 BOM 导入、旧 1.1.1 元数据任务副本兼容、开始新一轮通过。
|
||||
- 原工程全文件哈希未变;10 个观察到的自有 CAD 和私有桌面均释放,主桌面及原 CAD 未被接管。
|
||||
- GIF 20 步、47.5 秒,仅含应用窗口与弹窗,实际等待压缩。详见[成品验收记录](../testing/2026-10-15-packaged-acceptance.md)。
|
||||
|
||||
## 更新与限制
|
||||
|
||||
更新前关闭旧程序并备份 `data`,保留旧数据,用新包中的 EXE 与 `_internal` 配套运行。不同版本不要同时打开同一数据目录。
|
||||
|
||||
本次验收不替代其他机器、库版本或 Packager/ERC 验收。已知 CAD COM 偶发启动阻塞根因仍待定位;程序保留有界等待、取消检查与清理保护。首次采集可能需要数分钟。出现不确定状态时先核验恢复,避免重复执行。
|
||||
|
||||
程序构建及验收提交为 `a16914bc7221dbc62c467b7a89e06ab0c40c1fbc`;版本标签另包含后续文档与验收工具,产品运行代码未改变。附件 `release-manifest-1.1.2.json` 记录 EXE、VBS、GIF 和完整程序文件清单;`SHA256SUMS-1.1.2.txt` 可校验下载附件。
|
||||
@@ -0,0 +1,54 @@
|
||||
# 1.1.2 代码精简与启动/BOM 审查
|
||||
|
||||
审查起点:`136d7ff`。本轮不打包、不发布,不启动 CAD;原始工程、BOM 与既有实测证据不参与写入。
|
||||
|
||||
## 结论与已处理项
|
||||
|
||||
代码确实有历史包袱,但不能按文件大小直接删除。审查起点 Python 生产源码 86 个文件、22,564 行,其中旧 `part_replace` 为 7,503 行;测试目录约 30,337 行,不属于生产包源码。通过检查 GUI、CLI、VBS 动态调用和打包入口,本轮确认并处理以下内容。
|
||||
|
||||
1. 删除 `ui/project_table.py` 的孤立工程列表控件(122 行)。当前窗口使用单工程摘要与位号计划;生产代码、工具、菜单和打包配置均未引用旧控件。
|
||||
2. 删除 `TargetTable.item()` / `_CellAdapter`。它们只为测试模拟旧 QTableWidget 接口;相关用例现直接通过真实 QTableView model 修改、勾选与读取,排序后的 UID 绑定覆盖继续保留。
|
||||
3. 删除未使用的私有导入,保留真实使用的批量备份、协议和包导出。
|
||||
4. 合并 BOM 普通预览与报告校验引擎。`preview_batch` 保留严格调用接口,以同一份 `inspect_batch` 结果返回预览或报错,不再独立维护采集、路由、匹配和编辑保留逻辑。
|
||||
5. `BomMatcher` 对一个工程的位号清单只建立一次索引,逐行仅返回实际命中的目标。每行校验与最终合并校验均保留,继续拒绝重复目标、歧义位号、替换链和循环;未导入位号的原编辑保留。
|
||||
6. 修复损坏 Excel 在普通预览中被误报为未处理异常的问题;按 BOM 导入错误报告。
|
||||
7. 修复读表过程中取消被 ValueError 捕获并转成 BOM 错误的问题。`TaskCenterError` 是 ValueError 子类,需先传播操作异常;inspect/strict 两入口均验证保留 `operation_cancelled`,没有采集或部分保存。
|
||||
8. 启动恢复统一由 runner 完成,删除 application 提前恢复。旧顺序会先修改数据库,使 runner 来不及记录恢复前/后事件。迁移恢复、确认迁移记录和旧运行任务协调均保留。
|
||||
9. 通过按中断状态过滤的一次 SQL 查询替代逐任务读取工程;30 个空闲任务场景不再产生 30 次逐任务工程读取。
|
||||
10. Windows 启动诊断改用 `sys.getwindowsversion()`,避免仅为了记录 OS 信息就启动 WMI 查询。审查期间真实遇到 `platform._wmi_query` 的 `0x8007000e` 异常;这项修正与 CAD COM 绑定问题分别处理。
|
||||
|
||||
生产源码相对起点净减少 **186 行**,减少 1 个模块。新增的索引类替代重复构建和扫描,不是简单把大文件挪到另一个文件。
|
||||
|
||||
## 保留依据
|
||||
|
||||
| 范围 | 仍存在的调用 |
|
||||
| --- | --- |
|
||||
| 旧 `part_replace` CLI | pyproject 公开入口、`python -m dx_productivity`、Start-PartReplacement.ps1 的 discover/status/create/operator-step |
|
||||
| 人工 runner / comparison / evidence | 旧服务入口、历史任务恢复、迁移事件与证据校验;GUI 的规则检查仍跨包复用 inputs |
|
||||
| SceneOS | application 的 `--sceneos-cli` 分派仍存在 |
|
||||
| 菜单和 VBS 桥 | MenuRuntime 的 ExecuteGlobal 动态加载,不能仅依靠 Python import 搜索判死 |
|
||||
| QuickPartReplace / native_helper | 当前原生替换、私有桌面子进程仍使用,打包配置显式包含 VBS |
|
||||
|
||||
`quick_run.py`、`service.py`、`store.py` 仍然偏大。进一步分职责需要检查协议和兼容入口;本轮未引入另一套执行架构或删除仍被调用的功能。
|
||||
|
||||
## 验证
|
||||
|
||||
- 位号编辑、排序和单工程 UI:11 passed。
|
||||
- BOM、库存扩展、事务、任务上下文、UI 草稿和重复轮次选定回归:99 passed,31.19 秒。
|
||||
- 启动、旧人工流程和应用引导:37 passed,21.39 秒,包括历史迁移恢复和恢复前/后事件。
|
||||
- 审查末尾读表取消与启动恢复检查:12 passed,23.55 秒。上述检查有重叠,不相加为总用例数。
|
||||
- 另运行真实 Qt 的 offscreen 应用启动/关闭 smoke;数据目录位于 `build/code-pruning-startup-smoke-20261015`。
|
||||
- 只读复核代理确认原生保存/恢复事务、目标身份、NC 与 Value 处理边界未削弱;其指出的读表取消错误已修复。
|
||||
|
||||
## BOM 模拟规模测量
|
||||
|
||||
使用 1000 个模拟位号、真实 XLSX 的 200 条替换行,包含工程匹配、逐行校验和预览构建,不启动 CAD。
|
||||
|
||||
| 版本 | 结果 |
|
||||
| --- | --- |
|
||||
| 精简前 | 探针进程运行 285.36 秒仍未完成,主动停止;该值包含建库和生成模板,不能视为完整匹配耗时 |
|
||||
| 精简后 | 校验阶段 5.920 秒,200 行通过、0 行失败,1000 个位号中恰好启用 200 个 |
|
||||
|
||||
临时探针位于 `build/probe-bom-scale-audit.py`,前后结果分别保留在 `build/bom-scale-before-20261015/metrics.json` 和 `build/bom-scale-after-20261015/metrics.json`。未将一次性探针加入生产代码。
|
||||
|
||||
此结果不能换算成完整 CAD 替换速度。上一轮千步执行测试未达到 30 秒目标、CAD COM 启动偶发阻塞,仍是独立的未解决项。
|
||||
@@ -0,0 +1,41 @@
|
||||
# 1.1.2 位号计划响应与内存审查
|
||||
|
||||
起点 `224f4e7`。本轮不打包;使用模拟库存、真实 Excel 和 Qt 事件循环进行验证,不启动 CAD。
|
||||
|
||||
## 已处理
|
||||
|
||||
- `ComponentTarget.key` 被循环调用时重复访问文件系统。500 个启用位号的规则编译原需 1500 次解析,同规模库存合并需 3500 次。增加单次校验内的 `ProjectIdentityResolver`,按原始路径字符串复用解析结果;编译、合并、数据库保存及 BOM 索引各有独立作用域。
|
||||
- BOM 表格路由重复解析同一个工程路径;改为仅在本次读表阶段复用,原生采集后不复用该路由缓存检查工程身份。
|
||||
- UI 修改一个单元格时,摘要会复制并统计全表,执行按钮保护又以元组成员查询扫描全部任务。现在模型维护启用数量,摘要读取源模型数量;任务 ID 使用集合,同次按钮更新只计算一次本批未保存状态。
|
||||
- 已保存或放弃的 BOM 报表仍强引用整份预览,包括原库存和计划。现在只释放结束的预览,保留校验行、数量和说明;未保存预览和失败后可重试的数据继续保留。
|
||||
|
||||
## 保护边界
|
||||
|
||||
解析器不跨刷新、采集或保存操作持续缓存;单独访问 `ComponentTarget.key` 仍即时解析。大小写规范、原理图/图页/UID、位号、旧料号、旧 Value 的比对仍保留。数据库事务、保存前基线复核、原生路径访问检查和恢复保护没有减少。
|
||||
|
||||
排序和筛选后的编辑继续按原始 UID 写回;摘要按当前工程全部源数据统计。只有相关 BOM 工程全部保存成功或明确放弃时,才释放报告中的预览引用。
|
||||
|
||||
## 本机测量
|
||||
|
||||
| 场景 | 优化前 | 优化后 |
|
||||
| --- | --- | --- |
|
||||
| 500 位号规则编译 | 0.543 秒 / 1500 次路径解析 | 0.00274 秒 / 1 次 |
|
||||
| 500 位号库存合并 | 1.299 秒 / 3500 次路径解析 | 0.00666 秒 / 1 次 |
|
||||
| 模拟 3000 任务、3000 位号,本地改单元格,5 次平均 | 41.56 毫秒 | 1.60 毫秒 |
|
||||
| 1000 模拟位号、200 行真实 XLSX 校验 | 上轮 5.920 秒 | 0.143 秒;200 行通过、0 行失败 |
|
||||
|
||||
这些数值只覆盖上述本地处理,不包含 CAD 启动、采集和实际替换。路径耗时为单次对照,不能视为所有机器的固定收益。
|
||||
|
||||
临时探针和结果保留在 build:
|
||||
|
||||
- `probe-plan-identity.py`;`plan-identity-before-20261015/metrics.json`、`plan-identity-after-20261015/metrics.json`。
|
||||
- `probe-local-plan-edit.py`;`local-plan-edit-before-20261015/metrics.json`、`local-plan-edit-after-20261015/metrics.json`。
|
||||
- `probe-bom-scale-audit.py`;`bom-scale-identity-after-20261015/metrics.json`。
|
||||
|
||||
## 验证
|
||||
|
||||
先复现重复解析和保存/放弃后预览未释放,再修正。路径用例还确认下一次操作会重新解析;弱引用用例确认预览可回收而报告仍可查看。
|
||||
|
||||
本轮针对目标身份、命令、恢复、BOM、库存扩展、长路径、UI、草稿和新轮次共 **169 passed,22.58 秒**。只读审查复核了缓存范围、完整基线字段、筛选统计和保存失败保护,未发现新的重要问题。未为本轮局部优化重复运行整套测试或 CAD。
|
||||
|
||||
仍待解决:CAD COM 偶发启动阻塞、千步执行的 30 秒目标,以及大执行模块进一步按职责整理。本轮不对这些项目作完成声明。
|
||||
@@ -0,0 +1,55 @@
|
||||
# 1.1.2 可用性与发布条件评估
|
||||
|
||||
评估基线:`ce574dd`,2026-10-15。本轮查询公开官方资料、运行构建脚本采用的源码检查、审查现有成品和使用说明;没有构建、启动 CAD、改工程、打标签或发布。
|
||||
|
||||
## 判断
|
||||
|
||||
| 问题 | 当前判断 | 证据边界 |
|
||||
| --- | --- | --- |
|
||||
| 可以用吗 | 支持本机已验证环境内的工程副本试用 | 核心 BOM、多工程顺序执行、部分位号替换、保存重开回读、完成后新轮次有实机证据;不同现场/库未统一验收 |
|
||||
| 好用了吗 | 日常流程已成形,UI 的重复构建问题已改善;首次采集和 CAD 启动仍慢 | UI 与本地数据性能不能代表原生 CAD 速度,不能把一个审查者的判断等同于用户验收 |
|
||||
| 可直接正式发布吗 | 暂不建议宣称稳定正式版 | 最新源码尚无对应冻结成品全流程验收;偶发原生启动阻塞根因未闭环;交付文档存在旧界面说明 |
|
||||
| 能否准备试用版 | 可以进入候选包验证,完成下列交付检查后提供评估包 | 仍按原有 evaluation-only 定位,不需要为试用另起 UI 框架或做全部扩展功能 |
|
||||
|
||||
本轮按 `packaging/Build-DxPartReplace.ps1` 的源码检查范围执行:
|
||||
|
||||
```powershell
|
||||
python -m pytest -q tests/v1_1 tests/trial_task_center/test_application.py tests/trial_task_center/test_execution_safety.py tests/part_replace/test_verification.py --junitxml=build/release-research-20261015/current-release-gate.xml
|
||||
```
|
||||
|
||||
结果:**369 passed,1 warning,76.47 秒**。警告为 pywinauto 的 COM STA 模式提示。此结果不包含 PyInstaller 构建、冻结包运行、真实 CAD 替换或默认目录之外的千步性能用例,不能概括成“全部发布验收通过”。
|
||||
|
||||
## 已有真实能力
|
||||
|
||||
- 两工程创建任务、导出默认 11 列 BOM、填写部分位号、失败行提示、修正后导入、预览和整批保存;失败导入不保存半批。
|
||||
- 两轮真实替换及全新 CAD 会话独立回读,未选中的同料号位号保持不变;302 字符工程路径与 284 字符模板路径完成实际流程。
|
||||
- Part Label 复制开关实际改变 Value 写入结果;NC 开关有单独原生验证。
|
||||
- 后台私有桌面和自有 CAD 退出有观察证据,主桌面文件读取与用户原 CAD 未被接管。
|
||||
- 规则/结果使用 Model/View,详情按需创建、关闭释放,隐藏 tab 不渲染;草稿、结果数据与控件生命周期独立。
|
||||
|
||||
证据:`docs/testing/2026-10-15-bom-live-roundtrip.md`、`2026-10-15-part-label-live.md`、`2026-10-15-project-session-and-read-model.md`,及 `docs/reviews/2026-10-15-ui-component-lifetime.md`。后续 UI 修改使用复制数据库复放和专项回归,没有在每个提交重复运行真实替换。
|
||||
|
||||
## 发布前实际缺口
|
||||
|
||||
1. **最新成品身份和冻结运行验证。** 当前 `dist/DxPartReplace` 对应旧的 `714ac0b` 候选,不是本次 `ce574dd`;已发布 1.1.1 对应 `7610a0f`。先固定待发布提交、构建并生成版本/commit/EXE/VBS/ZIP 哈希清单,再从最终 ZIP 解压运行。确认源码路径不参与加载,实际打开按需日志/结果/BOM 窗口、完成模板导入,并在旧 `data` 副本上验证升级。现有 `--smoke-test` 只覆盖空白根目录启动退出,不覆盖这些交互。正式承诺新版完整替换前,再用最终冻结包的独立工程副本做有代表性的 BOM→替换→回读→释放验收。
|
||||
2. **CAD 启动稳定性和等待体验。** 已观察到 GetActiveObject/QueryInterface 偶发阻塞;120 秒预算和清理机制限制了等待,不代表根因已修。既有成功样本的 CAD 启动约 27–67 秒,首次采集也可能超过一分钟。应对已有失败条件定位和补测,明确启动/就绪/取消状态;保留超时、身份及退出证据。不能仅凭 UI 更快就承诺执行更快。
|
||||
3. **干净分发目录和正确说明。** 构建脚本会保存并恢复本机 `data`,这是保护本机数据;应另建干净 staging 排除本机任务、日志、数据库和备份,再压缩。使用说明仍有“完成任务自动显示全部日志”“当前界面保留 Capture Before/After”等过期描述,需要按实际按需分页和一工程一任务流程统一。README 当前仍明示未发布和 evaluation-only,发布时不能只改标题为稳定版。
|
||||
|
||||
本轮另单独执行 `tests/trial_task_center/test_batch.py::test_thousand_item_multisheet_mixed_queue_has_bounded_runtime_and_memory`,结果 **1 passed,测试总计 33.17 秒**。其中被断言的执行区间 **29.517 秒**,通过原有 `<30秒` 门槛;1000 步、91 步保存、909 步未命中,唯一性和完成状态通过,tracemalloc 峰值 2,200,063 字节,约 33.88 步/秒。原始指标为 `build/release-research-20261015/queue-stress-metrics.json`,JUnit 为同目录 `queue-performance-gate.xml`。此次达标应更新之前“尚未通过”的当前状态;但接近门槛、仅单次测量,不承诺跨机器稳定达标。该测试是模拟 worker 的兼容队列,不能作为新任务模式实际 CAD 的吞吐量。
|
||||
|
||||
## 网上可借鉴的规则
|
||||
|
||||
| 官方资料 | 原则 | 本工具的落点 |
|
||||
| --- | --- | --- |
|
||||
| [Microsoft PowerRename](https://learn.microsoft.com/en-us/windows/powertoys/powerrename) | 批量操作前对照原值与新值、预览实际变更,可筛选仅显示匹配项 | 保留计划预览;后续可增加本批“仅看将修改项”的统一视图,而非仅展示工程数量。CAD 恢复必须沿用快照核验,不能直接照搬文件重命名 Ctrl+Z |
|
||||
| [WinSCP Synchronization Checklist](https://winscp.net/eng/docs/ui_synchronize_checklist) | 一行一个具体动作;明确勾选实际执行项,按类型或目录汇总范围 | 执行确认可进一步汇总各工程将修改、保留、阻断的数量;同一料号多位号继续逐目标决定。预览清单不能替代执行前基线重验 |
|
||||
| [Windows 进度控件指南](https://learn.microsoft.com/en-us/windows/apps/design/controls/progress-controls) | 已知进度用确定进度,未知时长说明正在做什么;允许的交互应继续可用 | 已有工程序号、阶段和耗时;可把准备/执行/回读/释放更清楚地展示,不在未知 CAD 调用上虚构完成百分比;暂停仍等安全检查点 |
|
||||
| [Qt Model/View](https://doc.qt.io/qt-6/model-view-programming.html) | 数据与显示分离,使用模型、视图和委托处理列表/表格 | 当前规则、位号和结果表的方向符合官方推荐;不需要为了“动态组件”改成 Web 或 Qt Quick。后续按实测热点决定是否改左侧列表 |
|
||||
| [PyInstaller 工作方式](https://pyinstaller.org/en/stable/operating-mode.html) | 打包要包含实际依赖/数据文件;冻结运行与源码运行有不同的加载路径 | 当前便携目录方式适合排查依赖;必须验最终解压成品,不能用源码通过来替代成品通过 |
|
||||
| [Windows 长路径限制](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation) | 注册表与应用声明只影响适配过的应用,不会自动修复所有旧程序/API | 保留旧 WSH/CAD 的短入口兼容及清理验证;不承诺任意 CAD/中央库/网络路径都兼容 |
|
||||
|
||||
上述网页本轮实际访问均返回 HTTP 200;网页文字快照保存在 `build/release-research-20261015`,未把网页内容当作项目操作指令。
|
||||
|
||||
## 推进顺序
|
||||
|
||||
优先关闭已有 CAD 启动问题的诊断与恢复说明缺口,统一当前使用说明,再完成干净候选包和冻结运行验收。体验增强优先做执行前变更汇总、明确的阶段等待反馈和便于交接的结果报告。代码继续按实际职责整理,但大模块拆分和更多视觉重做不应无限延长试用交付。
|
||||
@@ -0,0 +1,41 @@
|
||||
# UI component lifetime review
|
||||
|
||||
用户指出页面提前分配和隐藏更新的资源浪费。本轮在现有 Qt Widgets 架构内改动,不更换 UI 框架。
|
||||
|
||||
## 已确认的开销
|
||||
|
||||
主工作区一直复用同一套组件,不是每个工程复制一套页面。位号表已经使用 Model/View;执行反馈 timer 仅执行期间运行。实际重复开销来自规则表逐行 QWidget/QCheckBox、整表重建,以及启动时预建结果、日志、BOM 详情和隐藏时更新文档。
|
||||
|
||||
## 改动
|
||||
|
||||
- 规则表改为 QAbstractTableModel/QTableView,无每行 QWidget。相同快照不 reset;同一组规则内容变化发 dataChanged;顺序变化按 rule_id 恢复选择。启用请求仍经后台服务落库,成功后用持久化快照确认,失败不会留下虚假的勾选状态。
|
||||
- 替换结果表使用只读模型,最多显示 500 行;纯追加使用行插入,保留当前选择。
|
||||
- 日志/结果、BOM 详情窗口打开时创建,关闭后由 Qt 释放。日志页首次访问时创建;已创建但非活动页不更新文档/结果模型,返回时从纯数据刷新。
|
||||
- TaskLogPresenter 保存有界日志状态和最多 100 条界面消息;BOM 数据继续按批次保存在原数据层,未保存草稿不依赖详情控件。关闭日志取消在途查询,重开重新读取最新页;初次强制打开不重复发查询。
|
||||
- 保留分页滚动语义:最新/轮转后到底、上一页到顶、普通追加保留阅读位置或跟随底部。
|
||||
|
||||
## 资源与耗时
|
||||
|
||||
运行 `python tools/measure_ui_components.py --revision 84d8f9c` 与省略 revision 的当前版本。每版独立进程,各三次,表格 1000 条规则;耗时为中位数。
|
||||
|
||||
| 指标 | 修改前 | 修改后 |
|
||||
| --- | ---: | ---: |
|
||||
| 规则表首次绑定数据 | 405.44 ms | 0.25 ms |
|
||||
| 相同规则刷新 | 383.80 ms | 0.02 ms |
|
||||
| 规则表 QWidget 子控件 | 2018 | 18 |
|
||||
| 独立 QCheckBox | 1000 | 0 |
|
||||
| 执行面板未打开详情时的 QWidget 子控件 | 49 | 12 |
|
||||
|
||||
以上计时包含 populate 的同步工作,不包含窗口首次绘制、数据库读取或 CAD;控件数量不等同于进程内存。新模型仍保存规则数据,只在可见区域绘制。
|
||||
|
||||
原始 JSON:`build/ui-components-20261015/before.json`、`after.json`。复现工具已纳入 Git。
|
||||
|
||||
## 验证范围
|
||||
|
||||
针对 Qt 生命周期、原生委托勾选/服务持久化、选中保留、分页滚动、关闭期间在途查询、立即重开、切换任务、BOM 校验/批次草稿以及原工作区回归进行验证。
|
||||
|
||||
最终针对性回归 **63 passed, 30.72s**,范围为 `test_lazy_components.py`、`test_execution_results_view.py`、`test_ui_responsiveness.py`、`test_ui_workspace.py`、`test_replacement_logs.py`、`test_bom_batch.py`、`test_bom_import_report.py`、`test_ui_remediation.py`。新增资源生命周期用例在修改前观察到 4 项预期失败,修改后通过。只读审查指出的分页滚动和结果追加选择丢失均已修正并覆盖。
|
||||
|
||||
使用 `tools/probe_workspace_layout.py` 复制 `build/bom-native-roundtrip-fixed-20261015` 证据数据库复放,输出在 `build/ui-components-layout-20261015`。980×700 实际尺寸保持,位号表 viewport 高 135px;执行、BOM 模板、Value 策略可见;执行结果显示已有真实回读记录;跨批报告隐藏、返回恢复;源数据库 SHA256 不变。检查了结果截图。
|
||||
|
||||
本轮未运行真实替换、未启动 CAD、未打包或发布。此前 CAD 原生连接偶发阻塞、千步执行性能问题不属于本轮结论。
|
||||
@@ -0,0 +1,16 @@
|
||||
# Packaged acceptance and window-only tutorial
|
||||
|
||||
Goal: validate the current frozen candidate and provide an instructional GIF captured solely from the application's own windows.
|
||||
|
||||
Scope: local candidate, no tag or remote release; preserve all existing data and user CAD processes. Use independent project/data copies. Do not inject fake successful replacement events.
|
||||
|
||||
- [x] Review prior evidence, current packaging and recording dependencies.
|
||||
- [x] Correct obsolete log-window and historical-interface instructions.
|
||||
- [x] Run the standard build checks and build the current source.
|
||||
- [x] Stage a clean candidate, hash it, archive and extract it; use that extracted EXE for acceptance.
|
||||
- [x] Operate the actual candidate UI to create project tasks, export/fill/import BOM, inspect rejected and accepted rows, edit/save, execute and inspect genuine results.
|
||||
- [x] Verify saved engineering state, old-data-copy startup, lazy details and owned-process/desktop cleanup.
|
||||
- [x] Produce window-only GIF(s) with step labels and explicit shortened waits; inspect exported frames.
|
||||
- [x] Write the acceptance result and limitations in `docs/testing/2026-10-15-packaged-acceptance.md`.
|
||||
|
||||
Integration: commit and push the reproducible tooling, report, and GIF on the development branch. No tag or remote release.
|
||||
@@ -0,0 +1,11 @@
|
||||
# 按工程区分的批量 BOM
|
||||
|
||||
用户已明确选择:同批所有工程放在一张表,导入按工程列分配至各任务;先不要发布新版本。本地 1.1.2 旧候选不上传,不创建发布标签,不再次打包。
|
||||
|
||||
1. `bom_plan.py` 保留表格格式与单工程兼容,增加工程路径列;分离单次 Excel 解析和位号匹配。空白工程占位行允许未填写;未知工程、歧义位号、重复项及公式拒绝。
|
||||
2. 新增 `bom_batch.py` 管理同批工程模板和不可变导入预览。模板在未采集时每个工程一行,旧/新料号和位号留空。导入先验证全部工程及可编辑状态;已有清单直接匹配,缺失清单按 BOM 旧料号只读采集。预览不写入数据库。
|
||||
3. service 暴露整批预览/保存。保存重新检查原任务/工程归属和基线,在单个 SQLite 事务中写入所有受影响任务;一个失败则全部回滚。
|
||||
4. 现有位号视图保留各任务预览草稿,允许切换任务检查和编辑;显示“保存本批位号计划”,保存整批后统一清理草稿。执行仍沿用每工程一任务和原串行队列,不重新维护多工程链表。
|
||||
5. 针对测试:未采集即可导出全部工程、两个工程同名位号分别路由、未知工程不采集、不保存半批、新清单仅在确认后写入、未列出工程保持原计划、UI 跨任务预览和整批保存。运行相关回归;提供本地示例文件,及时提交,不发布。
|
||||
|
||||
完成:以上五项已实现。额外验证了已有库存不重复采集、任务重排后重导入可保存,以及无预设料号规则时整批保存后执行入口可用。相关回归 252 项通过;审查修正后 BOM/UI 最终定向回归 17 项通过。原生长路径采集 318 字符、13 位号通过;旧候选仅本地留存,未创建 1.1.2 标签或上传包。证据见 `docs/testing/data/2026-10-15-project-bom-and-long-path.json`。
|
||||
@@ -0,0 +1,16 @@
|
||||
# UI component lifetime implementation plan
|
||||
|
||||
**Goal:** Reduce unnecessary UI allocation and hidden-page updates while retaining the existing workflow.
|
||||
|
||||
**Architecture:** Reuse the main task workspace. Render rules and results through Qt item models. Keep task logs and BOM report data outside disposable detail dialogs; create views only when opened and render only the active detail tab.
|
||||
|
||||
**Constraints:** Remain on the 1.1.2 development branch, preserve BOM/direct editing and batch drafts, do not package or release, do not launch CAD or alter original project/evidence data.
|
||||
|
||||
- [x] Establish allocation/timing baseline and failing resource-lifetime regressions.
|
||||
- [x] Replace per-rule item widgets with QAbstractTableModel/QTableView; keep ordering, rule identity, persisted confirmation, lock gates and selection.
|
||||
- [x] Extract disposable detail dialogs, lazy-load log tab, retain data independently, invalidate reads on closing and read latest on reopening.
|
||||
- [x] Migrate UI callers, tests and evidence tools to explicit view/data APIs.
|
||||
- [x] Verify lifecycle, paging, visible-only rendering, BOM drafts and actual Qt delegate interaction; reproduce UI layout using copied evidence.
|
||||
- [x] Review changes and record measured results in `docs/reviews/2026-10-15-ui-component-lifetime.md`.
|
||||
|
||||
Integration: commit and push these changes on the existing `codex/execution-responsiveness` development branch; no release/tag/package.
|
||||
@@ -0,0 +1,99 @@
|
||||
# BOM 界面流程、长路径与完成任务重跑
|
||||
|
||||
本轮使用 1.1.2 开发源码;没有打包、打标签或发布。所有 CAD 写入都在两份独立副本上完成,原工程和原 CAD 进程 PID 18732 不参与执行。证据目录为 `build/bom-native-roundtrip-fixed-20261015`,`report.json` 保留历次失败与恢复记录。
|
||||
|
||||
## 验证方式
|
||||
|
||||
`tools/probe_bom_live_roundtrip.py` 通过真实 Qt 控件点击新建、扫描、选择工程、导出模板、导入 BOM、保存、执行和开始新一轮。操作系统文件选择的返回路径和确认框由探针提供;界面使用 offscreen 渲染,因此这属于自动模拟用户操作,并非人工逐次操作鼠标。实际读取、Replace Part、保存和回读均调用本机 DxDesigner;未用模拟 CAD 代替。
|
||||
|
||||
| 项目 | 实际输入与结果 |
|
||||
| --- | --- |
|
||||
| 工程 | Audio_D2128、Audio_T605A,一工程一任务 |
|
||||
| 工程完整路径 | 分别 302、138 个字符 |
|
||||
| 默认模板路径 | 284 个字符,实际导出和重新导入成功 |
|
||||
| 模板 | 沿用 11 列,填写导出的真实单元格,不另造模板 |
|
||||
| 替换范围 | 两工程各选择 RV05;同旧料号 RV11 不替换 |
|
||||
| 第一轮 | `4100-CA0000-T7` → `4100-CA0000-T0` |
|
||||
| 第二轮 | `4100-CA0000-T0` → `4100-CA0000-T7` |
|
||||
|
||||
探针在自身进程内禁用 8.3 路径回退,强制验证目录 junction 入口;不修改 Windows 长路径设置或持久环境变量。命令、快照、任务库始终使用原工程身份,运行短入口只用于旧式文件接口与 CAD 打开工程,结束后删除入口。
|
||||
|
||||
## 导入与再次编辑
|
||||
|
||||
1. 从弹窗扫描目录、创建两个任务,耗时 0.565 秒。
|
||||
2. 点击 BOM 模板,实际导出带两个工程区分的 11 列默认文件到 284 字符路径。
|
||||
3. 填写两个有效 RV05 替换项,另加不存在的 `R_DOES_NOT_EXIST`:3 行中 2 行通过、1 行失败,报告准确标出 Excel 第 4 行及无法唯一匹配的原因。失败导入既不写入库存,也不保存部分计划。
|
||||
4. 删除错误项重新导入:2 行通过、0 失败,复用仍有效缓存,耗时 2.680 秒。预览后点击保存,两个工程共保存 4 个库存器件、2 个启用目标。
|
||||
5. 第一轮完成核验后点击“开始新一轮”,同批两个已完成任务均恢复为草稿;旧计划、命令、快照、执行及恢复证据归档到各任务的 `rounds/<round_id>/`,新轮清除过期器件基线,保留绑定及料号默认规则。界面操作耗时 0.332 秒。
|
||||
6. 按当前工程状态填写第二轮 BOM:每工程一条启用 RV05 和一条停用 RV11,共 4 行全部通过。重新采集并核对当前库存耗时 348.311 秒;该步骤不能沿用第一轮旧基线。
|
||||
|
||||
界面报告区持续显示行数、工程数、通过/失败/未检查数量及逐行原因;通过只代表已暂存预览,点击保存后才写入计划。有错误时整批不生成新的可保存预览。
|
||||
|
||||
## 现场发现并修复的问题
|
||||
|
||||
- 旧 WSH 的 FSO 对真实存在的长路径返回不存在。补齐实际工程路径的短入口;首次打开、保存后的重新打开和恢复都走同一入口。单独跑真实 FSO 回归验证了保存重开边界。
|
||||
- 部分 COM 绑定把 `GetProjectFilePath` 暴露为字符串属性,退出代码却按方法调用。统一兼容属性/方法两种形式,私有会话能够正常结束。
|
||||
- 原生修改后的失败曾被当作可直接重试:首轮长路径任务停在 `pin_promotion_started`,原生报告缺少异常信息。独立读取确认 RV05 已是新料号,不能依据“不保存关闭”推断工程已回滚。新增中断判定,阻止归档、直接重试、继续下一步或下一任务,必须先核验恢复;已核验的原生回滚仍可解除该类保护。
|
||||
- 核验恢复原来不识别 `batch_failed` 的修改证据,且拒绝自动队列产生的 FAILED 工程。补齐选择中断步骤、严格绑定原快照和事务、允许恢复原生失败工程以及成功后的任务状态同步;手动失败流程仍拒绝混用。
|
||||
- Windows 同时读取报告或命令文件时会短暂拒绝原子替换。通过真实 Win32 文件共享句柄复现后,补齐最长 1 秒的 PermissionError 重试。原始 helper 中止的根因仍无法单凭旧报告确定;此修复不被描述为已证明解决原始中止。
|
||||
- 千步队列还复现了 `status.tsv` 短暂拒绝读取。新增最长 1 秒的只读打开重试;打开后仍核对文件身份、偏移、长度、完整行及前后时间戳,持续拒绝或真实内容变化仍停止并保留不确定保护。真实 Win32 独占句柄回归通过。
|
||||
- 原生 helper 增加退出码、引脚提升阶段和 fault 日志。任务上下文的批规则同时纳入一次数据库只读快照,避免在已有快照后再读另一代任务数据。
|
||||
|
||||
恢复使用原来的长路径副本,没有重复制工程掩盖失败。旧构建已经把原始修改证据归档,因此仅在这个可抛弃测试任务中,将原证据逐字节校验后放回当前队列,把后续预检失败保留到历史,再通过界面的“核验并恢复”执行;操作记录位于该任务根目录 `manual-evidence-selection-for-regression.json`。
|
||||
|
||||
未勾选复制 Value 时,沿用既有语义:保留原生替换后的目标 Value,不强制恢复旧 Value。选中器件的空 Value 不能单独作为替换失败依据;未选中 RV11 则应保持料号、位号、UID 和 Value 不变。
|
||||
|
||||
后续补测已开启复制开关,真实替换后独立读取确认 `Part Label=0R`、`Value=0R`,详见 [Part Label 实测记录](2026-10-15-part-label-live.md)。
|
||||
|
||||
## 最终回读与回归
|
||||
|
||||
两个任务第二轮均返回 `saved_ok / session_verified`,包括真实保存、关闭、重开回读;之后另开全新后台 CAD 独立读取,得到:
|
||||
|
||||
| 工程 | 位号 / UID | 最终料号 | 最终 Value | 独立读取耗时 |
|
||||
| --- | --- | --- | --- | ---: |
|
||||
| Audio_T605A | RV05 / `$2I2014` | 4100-CA0000-T7 | 空,保留原生目标 Value 策略 | 106.165 秒(本工程合计) |
|
||||
| Audio_T605A | RV11 / `$2I2022` | 4100-CA0000-T7 | 0R,与原值一致 | 同上 |
|
||||
| Audio_D2128(302 字符路径) | RV05 / `$2I2014` | 4100-CA0000-T7 | 空,保留原生目标 Value 策略 | 108.927 秒(本工程合计) |
|
||||
| Audio_D2128(302 字符路径) | RV11 / `$2I2022` | 4100-CA0000-T7 | 0R,与原值一致 | 同上 |
|
||||
|
||||
最后两次独立读取前曾连续三次遇到 `GetActiveObject` 启动阻塞,尚未打开工程或调用替换;各失败会话均通过拥有的 job/desktop 清理,没有触碰主桌面 CAD。调用栈证据已保留。单独启动探针也曾成功建立绑定,不能据此认定原阻塞根因已消除。启动等待从 75 秒调整为有界的 120 秒,保留取消和强制收尾,新增 90 秒成功及持续无响应的虚拟时钟回归。最终两次实际启动身份确认分别约 64.906、67.109 秒,读取和退出均 `clean=true`;**这次成功不能证明增加预算就是之前偶发阻塞的唯一修复原因**。
|
||||
|
||||
`report.json` 最终 `verified=true`、`source_projects_unchanged=true`、`aliases_removed=true`,别名清理无错误。最终观察到的 11 个后台 CAD PID 均确认退出、11 个私有 desktop 均确认不存在;主输入桌面始终为 Default,845 次采样均能读取主桌面文件,未观察到自有 CAD 抢前台或出现在输入桌面。第二轮全流程的上一份观察另外保存在 `desktop-observation-second-round.json`,19 个已观察自有 CAD/desktop 均释放。最后系统仅留下原始 `viewdraw.exe` PID 18732。
|
||||
|
||||
- 默认完整回归:**303 passed,168.18 秒**,在增加最后两条启动等待用例和状态读取重试前完成,后续改动由对应专项核验。此前一条多工程模拟器将“修改前失败”错误写成“已开始原生修改但缺少报告”,已校正模拟协议;生产保护未放宽。
|
||||
- 启动/退出、COM 路径 getter 与新增有界等待专项:**18 passed,13.52 秒**。
|
||||
- 恢复与快照专项:**33 passed**;随后新增状态文件占用后的 I/O 与快照专项:**14 passed**。
|
||||
- 千步队列最终确实执行完 **20 工程 × 5 图页 × 10 规则 = 1000 步**,91 步保存、909 步未命中,作业编号无重复、顺序与状态断言全部通过,峰值分配约 **1.98 MiB**。但耗时 **52.434 秒**,约 **19.07 步/秒**,**未通过既有 `<30 秒` 的性能断言**。未放宽阈值或把该测试标为通过;这属于本轮尚未达到的性能目标。此前并行 CAD 时的另一轮为 32.313 秒,不作为当前性能结论。
|
||||
|
||||
现场探针结束后只重做独立读取,没有重新执行任何已完成的替换任务。再次运行这个探针的 `--resume` 会识别第二轮已完成记录,并自动只读核验。源码测试过程将 TEMP、TMP、LOCALAPPDATA 仅对测试进程指向 F 盘;原本在 C 盘的本仓库旧 pytest 产物经哈希校验后迁移到 F 盘 build 目录保留,没有清理用户工程或原始 BOM。
|
||||
|
||||
可查看的短路径证据:
|
||||
|
||||
- `build/bom-native-roundtrip-fixed-20261015/bom-default-template.xlsx`
|
||||
- `build/bom-native-roundtrip-fixed-20261015/bom-with-invalid-row.xlsx`
|
||||
- `build/bom-native-roundtrip-fixed-20261015/bom-first-round.xlsx`
|
||||
- `build/bom-native-roundtrip-fixed-20261015/bom-second-round.xlsx`
|
||||
- `build/bom-native-roundtrip-fixed-20261015/06-import-current-engineering-state.png`
|
||||
- `build/bom-native-roundtrip-fixed-20261015/07-second-round-completed.png`
|
||||
|
||||
前述短路径 XLSX 是本轮实际文件的副本;长路径原件完整保留。初次截图因 offscreen 中文字体缺失不适合审阅,恢复探针显式加载微软雅黑后生成的第二轮截图可以正常显示中文。
|
||||
|
||||
## 第二轮执行计时
|
||||
|
||||
两任务顺序完成的墙钟时间为 465.509 秒。下列时间来自真实任务事件和私有会话元数据,不是模拟执行;完整阶段与历史失败项由 `execution-measurements.csv` 导出。
|
||||
|
||||
| 阶段 | Audio_D2128 长路径(秒) | Audio_T605A(秒) |
|
||||
| --- | ---: | ---: |
|
||||
| CAD 启动身份确认 | 58.578 | 48.562 |
|
||||
| 打开工程累计(含重开) | 31.000 | 20.281 |
|
||||
| 打开图页累计 | 19.344 | 16.141 |
|
||||
| 原生替换 | 43.344 | 36.125 |
|
||||
| 属性恢复预检 | 14.437 | 9.875 |
|
||||
| 属性字段恢复 | 8.828 | 5.766 |
|
||||
| 保存关闭阶段累计 | 8.515 | 4.969 |
|
||||
| 单步总耗时 | 252.992 | 192.477 |
|
||||
| 整个任务耗时 | 262.275 | 202.886 |
|
||||
| 任务速率(任务/分钟) | 0.229 | 0.296 |
|
||||
| 私有会话收尾 | 3.281 | 2.797 |
|
||||
|
||||
控制器总耗时、worker 子阶段和启动/收尾属于不同计时层,不能跨层相加。阶段数据还受本机 CAD 启动、COM 调用及现场负载影响;本次用于证明真实步骤与定位耗时,不据此宣称性能提升。BOM 的首次读取和新轮读取会重新验证工程稳定性,缓存有效的纠错导入则无需重复启动 CAD。
|
||||
@@ -0,0 +1,38 @@
|
||||
# 任务导航与 CBB BOM 格式转换(1.1.2 开发中,未发布)
|
||||
|
||||
## 任务导航
|
||||
|
||||
左侧支持按任务名称、目录、备注搜索,以及执行顺序、名称正反序、创建时间正反序、最近更新排序。名称按自然顺序排列,例如 Board2 在 Board10 前面。排序选择在重启后保留。
|
||||
|
||||
搜索、排序在缓存的任务列表上进行,不重复查询数据库,也不改写批次执行位置。隐藏当前任务时保留右侧上下文,清空搜索后恢复选中。顺序执行仍处理原批次的全部任务。清空搜索、选择执行顺序后,才可用上移/下移调整执行位置。
|
||||
|
||||
## 本次转换
|
||||
|
||||
输入:`F:\ABS-file\ABS-file\CBB_BOM_替换清单2026.10.12(1).xlsx`。
|
||||
|
||||
以“结果”表为主,共 1803 行、104 种工程标签。转换使用现有 `write_bom_template`,没有修改模板的 11 列、工作表结构或导入约定,也没有修改原文件、任务数据库或 CAD 工程。
|
||||
|
||||
复现命令:
|
||||
|
||||
```powershell
|
||||
python tools/convert_cbb_bom.py 'F:/ABS-file/ABS-file/CBB_BOM_替换清单2026.10.12(1).xlsx' --project-root 'F:/Sync Tool Skyworth/Work Maps/Skyworth_CBB_Lib/CBB' --output-dir 'dist/CBB-BOM-converted'
|
||||
```
|
||||
|
||||
M 列作为方案候选,V 列只保留作对照,不在 M 缺失时自动补入 V。V 与“缓存”表 O 列的 1803 行一致;M/V 有 90 行同时为明确料号但不同,其中 88 行是 `4300-CB1040-A100` 与 `4300-CC1040-7100` 的差异,另外 2 行以 `431R` 开头。列用途是基于数据关系作出的判断,不代表电气可替换性已经确认。
|
||||
|
||||
输出位于 `dist/CBB-BOM-converted`,不随源码提交原始业务数据:
|
||||
|
||||
| 文件 | 内容与限制 |
|
||||
| --- | --- |
|
||||
| CBB_转换模板_全量待核对.xlsx | 441 行候选、1019 个位号;未定位的工程路径留空,需补齐后才能批量导入 |
|
||||
| CBB_转换模板_已匹配工程.xlsx | 当前目录能定位的候选:10 个工程、63 行、170 个位号;50 行启用,13 行存在差异,默认停用 |
|
||||
| CBB_逐行转换核对.csv | 保留所有 1803 行原始数据、原行号、路径匹配结果和转换说明;不是导入文件 |
|
||||
| conversion-report.json | 转换计数与文件位置 |
|
||||
|
||||
当前指定的 CBB 目录可定位 14 种工程标签,其中 10 种有可转换行。没有新料号、包含“删除该CBB”“不可更换”等说明的行保留在核对清单,不转换为替换操作。M 中仅含一个料号的说明文字可提取为停用候选;多料号、公式和系列后缀不自动解释。M/V 差异、手工处理、未绑定路径等候选默认停用。完成标记不用于删除或筛选行,原 VALUE 不自动写入 custom_value,NC 同步使用原模板默认开启。原行号、M/V、完成标记、VALUE 和相关备注保存在新料号单元格批注中。
|
||||
|
||||
## 验证与尚待完善
|
||||
|
||||
27 项针对任务搜索/排序、选中状态、设置持久化、异步响应、原 BOM 导入和此次转换的检查通过(13.16 秒)。两份输出由工具实际的 `read_bom_records` 重新解析,并检查列名、单工作表、无公式、自动换行以及已匹配路径存在。没有启动 CAD,也没有验证这些业务料号在当前工程/中央库中的实际替换结果;导入仍需同批工程绑定与位号采集匹配。
|
||||
|
||||
建议后续补充:导入时选择工作表与列映射;工程名称到任务路径的匹配预览;一次列出全部未命中、跨页重号和冲突行;在界面展示转换来源和停用原因。它们属于后续功能,本次没有改动 BOM 模板或导入界面。
|
||||
@@ -0,0 +1,52 @@
|
||||
# CBB BOM 真实工程导入验证
|
||||
|
||||
2026-10-15,1.1.2 开发版本,未打包发布。原始 BOM 和原工程未改动,没有执行 Replace Part。
|
||||
|
||||
## 结论
|
||||
|
||||
原转换文件的 63 条候选不能整表通过当前工程校验:15 条在 7 个工程中完整匹配,另外 48 条未完整匹配。不能将格式解析成功等同于真实位号匹配成功。
|
||||
|
||||
使用原生采集到的真实 UID、位号、图页、旧料号、Value,在隔离任务库里回放导入这 15 条规则,已走通 **界面导入 → 跨任务预览 → 批量保存 → 关闭数据库 → 重新打开核对**。7 个工程共保存 39 个采集位号,其中 25 个启用,其余保留或停用;11 条启用规则展开为 25 个实际替换目标。预览没有改写已有库存或保存计划。
|
||||
|
||||
这次测试分成真实 CAD 采集和界面回放两层。界面回放复用实际采集的库存,没有伪造 UID 或位号,也没有再次启动 CAD。它证明导入、分配和持久化正确,不代表所有工程在最终版本上重新完成了完整原生采集,更不代表电气替换已经验证。
|
||||
|
||||
## 实际输入与证据
|
||||
|
||||
- 原始文件:`F:\ABS-file\ABS-file\CBB_BOM_替换清单2026.10.12(1).xlsx`。
|
||||
- 转换文件:`dist/CBB-BOM-converted/CBB_转换模板_已匹配工程.xlsx`。
|
||||
- 原始工程复制到 `build/cbb-bom-import-live-20261015/projects`。副本仅将 CentralLibrary 改到本机已存在的库路径;测试表仅将工程路径改到副本。
|
||||
- 原始表的多个工作表、全量转换表缺少工程路径,均在启动 CAD 前被明确拒绝,任务计划没有部分写入。
|
||||
- `build/cbb-bom-import-verified-20261015/report.json`:10 个工程的原生诊断、导入拒绝和局部导入日志。
|
||||
- `build/cbb-native-verified-input/evidence.json`:每个工程最近两次成功原生采集的证据目录。只有这两次的图页和器件集合一致时才接受快照;完整旧料号请求范围也保留在证据中。
|
||||
- `build/cbb-bom-ui-verified-7-projects/report.json`:最终 7 工程界面回放和保存回读结果。
|
||||
- `build/cbb-cache-fixed-native/report.json`:最终代码在 `1PEF7071_PHY` 上再次进行的新鲜原生采集,5 个真实器件通过并成功复用缓存。
|
||||
|
||||
## 修复的问题
|
||||
|
||||
1. **原生只读打开也更新数据库**。ICDB 会更新 `database/icdb.dat`,自动备份会更新日志及备份文件。旧校验会反复打开工程并拒绝采集。现在排除明确的备份审计输出;数据库仍计算完整哈希。仅数据库在读取期间变化时,需要两次原生采集结果一致,而且其他设计文件跨两次读取保持稳定。首次工程配置规范化后允许一次额外读取完成这两次核验。库存不同、设计文件持续变化、不可验证等情况仍拒绝使用;数据库后续变化也仍使缓存失效。
|
||||
2. **失败提示无法判断是哪一个工程**。采集及匹配异常现在带工程名称和完整路径,保留原错误编号。VBS 也记录枚举、打开图页、查询器件、读取器件、关闭图页与关闭工程的阶段。
|
||||
|
||||
诊断过程中 `1GPHY_RTL8211F_A` 曾返回 COM 服务器异常;其他成功采集记录提供了该工程两份一致的真实库存。该异常没有被认定为已修复。另有工程的旧料号库存为空,原因需结合原表与当前工程版本核对,不能直接假定为已经替换。
|
||||
|
||||
## 耗时与资源
|
||||
|
||||
| 检查 | 结果 / 耗时 |
|
||||
| --- | --- |
|
||||
| 原表格式拒绝 | 0.136 秒,未写计划 |
|
||||
| 未绑定路径拒绝 | 0.155 秒,未写计划 |
|
||||
| 最终 7 工程界面预览 | 0.282 秒 |
|
||||
| 最终 7 工程批量保存 | 0.364 秒 |
|
||||
| 最终代码新鲜原生采集 | 76.998 秒,5 个器件 |
|
||||
| 同工程缓存复用 | 0.266 秒,库存一致 |
|
||||
| 原生诊断期间界面计时器最大间隔 | 0.234 秒 |
|
||||
| 最终界面回放期间计时器最大间隔 | 0.112 秒 |
|
||||
|
||||
原生采集仍是主要耗时点:诊断阶段单工程耗时约 62–134 秒,包含 CAD 启动、多次读取和关闭。首次诊断是在完整兼容修复之前运行,失败耗时不能当成最终版本的成功吞吐量。后续应优先研究连续采集时复用受控 CAD 会话,并补充逐工程进度与安全取消。
|
||||
|
||||
私有桌面观察确认诊断轮的 19 个会话均已退出,桌面均已释放;最终新鲜采集也独立观察清理结果。输入桌面始终为 Default,受控 CAD 未成为前台或出现在主桌面;原 CAD 进程 18732 保留。原工程文件哈希保持不变。
|
||||
|
||||
## 交付与回归
|
||||
|
||||
`dist/CBB-BOM-converted/真实工程验证` 中包含按原模板 11 列导出的匹配行、全部 63 条候选逐行核对 CSV、统计和保存后的界面截图。匹配行文件恢复为原工程路径,没有覆盖原转换文件,也没有改变原模板列。
|
||||
|
||||
75 项针对缓存、BOM、任务导航、异步界面、库存和目标执行的回归检查通过(19.37 秒)。没有构建、更新发布包或创建版本标签。
|
||||
@@ -0,0 +1,64 @@
|
||||
# 1.1.2 本机冻结候选验收与窗口教程
|
||||
|
||||
结论:**本轮列出的本机成品验收通过,可用于限定环境的小范围试用交付**。不是所有 CAD、中央库和机器环境的稳定性认证;没有创建远端 Release 或版本标签。
|
||||
|
||||
## 候选身份
|
||||
|
||||
- 构建提交:`a16914bc7221dbc62c467b7a89e06ab0c40c1fbc`;产品代码与此前通过源码检查的 `ce574dd` 一致,期间仅增加发布评估和说明文档。
|
||||
- 标准构建脚本源码检查:**369 passed,1 warning,63.39 秒**;PyInstaller 构建与冻结 EXE 启动/退出检查通过。
|
||||
- 候选从 `dist/DxPartReplace` 另复制到干净 staging,排除 `data`,再压缩、解压。实际操作的是 `build/packaged-acceptance-20261015/extracted/DxPartReplace/DxPartReplace.exe`。运行进程路径、EXE 哈希和副本工程身份另行核对。
|
||||
- EXE SHA256:`73d6deb81d52ce34ce9c6d2958275a9b7376f316ae1872552882f0d65070ce75`。
|
||||
- VBS SHA256:`9997d8a41ad3820e7fd905c8024fc10c765c0e6218eb7f3c091301e3c73db9dc`,与源码一致。
|
||||
- ZIP SHA256:`bfbc089c4362a9a9c43320b81ee9d4f7af0750bee6da25d16fc58733130319c2`,52,589,346 字节。
|
||||
|
||||
候选、完整工程副本、原始记录均在 `build/packaged-acceptance-20261015`。候选 ZIP 为本地验收包,不改变当前已发布版本。
|
||||
|
||||
## 实际操作及断言
|
||||
|
||||
使用 Windows UI Automation 定位真实控件,向目标窗口发送鼠标消息,操作原生文件选择与确认弹窗。没有导入产品内部 UI 类驱动主流程,没有模拟 CAD worker,也没有向数据库或日志注入成功状态。数据库检查使用只读连接。
|
||||
|
||||
| 验收项 | 结果 |
|
||||
| --- | --- |
|
||||
| 创建任务 | 实际创建弹窗读取 Audio_D2128、Audio_T605A 的独立副本;一工程一任务 |
|
||||
| 长路径 | 两工程路径分别 297、131 字符;长路径实际采集、替换、保存重开与独立读取均完成;本轮使用本机可用的 8.3 短入口,未重复强制 junction 路线 |
|
||||
| 默认 BOM | 点击导出原模板,确认 11 列、两个工程;只填写原表单元格,不改模板结构 |
|
||||
| 错误导入 | 两条有效 RV05 + 不存在的 R_DOES_NOT_EXIST:通过 2、失败 1、未检查 0,明确 Excel 第 4 行;没有部分保存 |
|
||||
| 修正导入 | 通过 2、失败 0、未检查 0;预览不写计划,点击保存后形成 4 个库存位号,只有两个 RV05 启用 |
|
||||
| 任务搜索 | T605A 过滤为 1 个,清空后恢复 2 个;执行成员未变 |
|
||||
| Value 策略 | 逐任务通过界面启用 Part Label → Value,并核对数据库中的选项持久化 |
|
||||
| 顺序执行 | 实际确认两个工程范围,分别执行原生 Replace Part、保存、关闭和重开核验;两工程各一条真实 saved_ok 事件,均含 RV05 的旧新料号 |
|
||||
| 结果/日志 | 实际结果单元格包含 RV05、新料号和“已保存并核验”;切换完整日志、关闭再打开,结果仍正确 |
|
||||
| 独立读取 | 使用全新私有 CAD 会话读取实际保存工程,结果如下;启动/退出 helper 使用同一冻结 EXE,属性读取器为独立源码诊断脚本 |
|
||||
| 新轮次 | 独立核验后实际点击开始新一轮,两任务恢复 draft,旧目标计划清空;两份 plan.json 及执行证据归档保留;本轮不重复执行已完成的原生替换 |
|
||||
| 旧版数据兼容 | 实际 1.1.1 发布 EXE 创建两个元数据测试任务;复制其数据库交给候选打开,正常退出,两个任务 ID/名称均保留,旧数据库未变;不是对任意历史数据的全量迁移认证 |
|
||||
| 工程与资源 | 两个原工程的全部文件 SHA256 未变;10 个观察到的自有 CAD 进程退出、10 个私有桌面释放,无观察错误,未抢主桌面;最后仅保留用户原 CAD PID 18732 |
|
||||
| 应用退出 | 验收和录制后候选主窗口正常关闭,没有遗留候选 GUI 或自有 CAD |
|
||||
|
||||
独立实际结果:
|
||||
|
||||
| 工程 | 位号 | UID | 实际保存料号 | Part Label | Value |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Audio_D2128 | RV05 | $2I2014 | 4100-CA0000-T0 | 0R | 0R |
|
||||
| Audio_D2128 | RV11(保留) | $2I2022 | 4100-CA0000-T7 | 0R | 0R |
|
||||
| Audio_T605A | RV05 | $2I2014 | 4100-CA0000-T0 | 0R | 0R |
|
||||
| Audio_T605A | RV11(保留) | $2I2022 | 4100-CA0000-T7 | 0R | 0R |
|
||||
|
||||
## 耗时及记录
|
||||
|
||||
- 含错误项的首次 BOM 导入和实际库存核验:285.406 秒;修正后有效缓存下重新导入:5.735 秒。
|
||||
- 点击确认执行到两工程完成并恢复界面:258.984 秒,约 4 分 19 秒;这是两个工程合计,包含原生处理及保存回读,不代表每个位号都需要同等耗时。
|
||||
- 独立读取:37.922、46.172 秒,分别包含全新会话启动、打开读取和退出。
|
||||
- 阶段计时:`execution-measurements.csv`;实际状态、导入标题、保存事件及调试尝试保存在 `ui-acceptance.json`,失败的驱动适配尝试没有删除。驱动修正没有修改产品代码或绕过原生核验。
|
||||
- 其他记录:`candidate-manifest.json`、`independent-report.json`、`source-integrity.json`、`v111-upgrade-report.json`、`desktop-observation-{bom,execute,independent}.json`、`tutorial-report.json`。
|
||||
|
||||
## 窗口 GIF
|
||||
|
||||
[打开操作教程](../user/media/v1.1.2-window-bom-tutorial.gif):20 个步骤,47.5 秒,约 2.65 MB,1280×980。
|
||||
|
||||
GIF 由本轮实际窗口操作的分步截图组成,使用 PrintWindow 仅读取指定候选进程的主窗口及其弹窗,不读取桌面图像,不包含 Excel 或 CAD 窗口。模板填项在窗口录制之外由脚本完成。字幕说明实际等待被压缩;数分钟的 CAD 等待没有按实时长度保留。抽查了导出 GIF 中的错误报告、成功回读和新轮次帧,中文及内容可读。
|
||||
|
||||
可复用工具:`packaged_window_driver.py`、`accept_packaged_ui.py`、`probe_packaged_upgrade.py`、`verify_packaged_saved_state.py`、`finalize_window_tutorial.py`。工具有副本路径和成品身份守卫,执行错误时不自动重复替换。UIA 与窗口绘制接口仍属于同步调用,本次工具用于有人监督的本机验收,不作为具有硬超时保证的无人值守门禁。
|
||||
|
||||
## 保留的限制
|
||||
|
||||
既有 COM 偶发启动阻塞的根因仍未解决;本轮所有会话最终成功并释放,不能据此证明问题消失。超长任务名称在执行反馈中占用较多空间、任务列表状态在批次结束前可能滞后,是后续体验改善项,不影响本轮真实回读结论。未新增其他库版本、其他机器或 Packager/ERC 验收。之前千步性能单次 29.517 秒达标的范围仍仅为模拟 worker,不与本轮实际 CAD 时间混用。
|
||||
@@ -0,0 +1,42 @@
|
||||
# Part Label 写入 Value 的实际替换验证
|
||||
|
||||
本次补测开启“替换后将 Part Label 写入 Value”的路径。功能代码没有修改;新增可重复运行的探针 `tools/probe_part_label_live.py`。证据位于 `build/part-label-live-20261015`,没有打包或发布。
|
||||
|
||||
使用原始 Audio_T605A 的新副本,导出默认 BOM 模板后填写 RV05 替换项,通过界面导入、保存、勾选复制开关,再点击执行当前任务。Qt 使用真实鼠标事件,文件选择返回值由探针注入,Excel 单元格用 openpyxl 编辑;CAD 替换、保存和读取均为本机真实 DxDesigner 调用。第一次探针鼠标坐标落在复选框留白,停在修改前;修正探针点击坐标后复用已保存计划继续,实际替换只执行一次。
|
||||
|
||||
## 结果
|
||||
|
||||
| 检查项 | 实际结果 |
|
||||
| --- | --- |
|
||||
| BOM 导入 | 1 行通过、0 行失败;库存 RV05、RV11 共 2 项,只启用 RV05 |
|
||||
| 界面开关 | 已勾选,并持久化到任务 |
|
||||
| 实际执行策略 | 命令的 `value_mode`、`base_value_mode` 均为 `part_label`;自定义 Value 关闭 |
|
||||
| RV05 料号 | `4100-CA0000-T7` → `4100-CA0000-T0` |
|
||||
| RV05 独立读取 | UID `$2I2014`,Part Label **0R**,Value **0R** |
|
||||
| RV11 未选中 | UID `$2I2022`、料号 `4100-CA0000-T7`、Value **0R** 均保持原样 |
|
||||
| 保存核验 | 原生替换、属性回读、保存、关闭、重开核验通过,任务完成 |
|
||||
| 额外独立核验 | 另开全新私有 CAD 会话,直接读新料号、Part Label 和 Value;成功后不保存关闭 |
|
||||
| 原工程 | 全目录文件哈希未变,且与上一轮对照测试的原工程哈希一致 |
|
||||
| 主桌面及释放 | 1231 次采样均能读取主桌面文件,输入桌面保持 Default,自有 CAD 未抢前台;观察到的 7 个自有 CAD PID、7 个私有 desktop 均释放 |
|
||||
|
||||
本次没有出现 CAD 启动超时,独立读取会话启动约 27.484 秒、收尾约 1.531 秒。最终系统仍只有用户原来的 CAD PID 18732,临时路径别名清理无错误。
|
||||
|
||||
与上一轮相同料号替换的对照:
|
||||
|
||||
| 复制开关 | 替换后的料号 | 独立取得的 Value |
|
||||
| --- | --- | --- |
|
||||
| 关闭(上轮) | 4100-CA0000-T0 | 空,保留原生目标 Value |
|
||||
| 开启(本轮) | 4100-CA0000-T0 | **0R,与 Part Label 一致** |
|
||||
|
||||
关闭时的证据来自上一轮 `report.json` 的新轮采集结果;本次检查了两轮原工程哈希一致。对照数据另存为 `control-comparison.json`。因此本次验证了开关实际改变写入结果,而不只是界面状态或命令字段发生变化。
|
||||
|
||||
## 耗时与证据
|
||||
|
||||
- BOM 导入及真实库存采集:126.910 秒。
|
||||
- 点击执行至保存重开核验完成:231.631 秒,包含重新确认库存、启动 CAD 和实际替换。
|
||||
- 全新会话独立读取及退出:45.771 秒。
|
||||
- 分阶段计时:`execution-measurements.csv`;原生事务、日志和私有会话记录保存在任务 `quick-run` 及 `quick-run-history` 中。
|
||||
- 独立结果:`independent-attributes.json`;最终 `report.json` 为 `verified=true`、`source_project_unchanged=true`。
|
||||
- 界面截图:`01-part-label-enabled.png`、`02-part-label-completed.png`。
|
||||
|
||||
本次仅补齐普通 Part Label 复制路径的真实验证,没有把既有 COM 偶发启动阻塞或千步性能目标记作已解决,也没有重新跑整套基础测试。
|
||||
@@ -0,0 +1,37 @@
|
||||
# 全流程审查修复记录
|
||||
|
||||
1.1.2 开发版,修复 2026-10-15 审查确认的八项问题;本轮不打包、打标签或发布。
|
||||
|
||||
| 审查问题 | 修复后的行为 |
|
||||
| --- | --- |
|
||||
| 修改规则与实际执行不一致 | 修改默认值时,更新仍沿用旧默认值的位号;保留手动新料号、NC、Value 和勾选。界面说明实际执行依据保存的位号计划。Value 开关及文本作为一组覆盖。删除或停用默认规则不删除用户已保存计划。 |
|
||||
| 本批规则实际上只作用于当前任务 | 增删改及排序在同一事务中作用于未删除的同批任务;冻结成员阻止整个修改。历史缺失规则可合并,冲突规则须显式统一;合并规则仍执行链式替换、循环校验。 |
|
||||
| 首次保存后不能补充旧料号 | 缺少请求旧料号时,重新采集既有与新增旧料号的合集;验证既有身份全部未变再扩展库存,保留编辑。BOM 预览不写数据库。 |
|
||||
| 成员变化后旧 BOM 预览无法恢复 | 新预览替换重叠范围;未重新导入的编辑保留。已删除成员保留其暂存库存及基线,恢复后可保存或通过新导入合并;永久删除才清理其草稿。 |
|
||||
| 关闭窗口静默丢草稿 | 检查所有任务的当前表格、隐藏草稿及暂存 BOM;保存全部、放弃、取消。保存全部为一个事务,任一失败整体回滚且窗口保留草稿。 |
|
||||
| 无入口恢复删除任务 | 左侧新增独立回收站按钮,支持搜索、排序、恢复、永久删除。原状态下拉框继续隐藏。新建任务后返回正常任务列表。 |
|
||||
| 原生枚举顺序变化误报工程变化 | 按图页、匹配内容及完整器件身份比较,忽略枚举顺序;拒绝重复身份及真实字段变化,保留 ICDB 全量指纹和两次读取核验。 |
|
||||
| 采集及 BOM 导入没有进度和取消 | 显示工程序号、名称及读取阶段;取消传到原生启动及监控。只读脚本先在安全边界退出,再释放自有 CAD 会话;异常清理保留诊断并阻止自动关闭。 |
|
||||
|
||||
另补齐恢复保护对 `native_replace_applied`、`pin_promotion_started` 的识别;工程继续指令因 Windows 短暂共享拒绝而读取失败时有界重试,token 与 checkpoint 校验不变。
|
||||
|
||||
## 验证
|
||||
|
||||
- 适用的完整默认回归:**260 passed,57.34 秒**。最后补充回收站中新建任务返回正常列表后,相关界面回归 **24 passed,12.79 秒**。
|
||||
- 原生控制、规则事务和会话监控专项(含默认套件之外的 worker-monitor 检查):**36 passed,11.03 秒**。
|
||||
- 子代理交叉审查发现并修复“保存全部部分提交”“恢复任务缺失暂存库存”“历史规则合并漏检链式替换”;对应回归及复审通过。
|
||||
- 真实 WSH 读取被 Windows 独占打开的控制文件:短暂拒绝后成功读取;使用真实子进程检查协作取消确认收尾,再返回结果。无 CAD 或用户工程写入。
|
||||
|
||||
本机 C 盘在首轮完整回归中已无剩余空间,SQLite 报 disk full。最终测试仅在测试进程中将 TEMP、TMP、LOCALAPPDATA 指向 F 盘隔离目录,未修改用户环境变量或清理用户文件。
|
||||
|
||||
## 七工程 CBB 复放
|
||||
|
||||
复用先前实际原生采集并核对过的库存,运行真实 Qt 导入与保存界面:
|
||||
|
||||
- 7 个工程、39 个库存位号、25 个启用目标。
|
||||
- 预览前后保存计划一致;跨任务预览、批量保存、关闭数据库并重新打开核对全部通过。
|
||||
- 输入工程哈希未变;没有启动新的 CAD 会话,没有执行本轮实际替换。
|
||||
- 本次与完整回归并行时预览 6.060 秒、保存 4.515 秒;这些受并发负载影响的数字不作为性能提升结论。
|
||||
- 完整证据:`build/cbb-review-remediation-replay-20261015/report.json`,同目录包含预览与保存后截图。
|
||||
|
||||
该复放只使用先前完整匹配的 15 条 BOM 记录。原表其余 48 条与工程信息不完整匹配的问题仍需核对数据;本轮没有猜测位号或伪造匹配。此前出现过的 COM 服务器异常亦未据此宣称根因已修复。
|
||||
@@ -0,0 +1,42 @@
|
||||
# 1.1.2 工作区与结果展示优化验证
|
||||
|
||||
本轮为开发版迭代,不打包、不新增 tag 或 release。
|
||||
|
||||
## 已修复
|
||||
|
||||
- BOM 校验报告按导入发起批次归属;跨批次隐藏,切回同批任务恢复。导入回调捕获批次,不按回调时的选中任务猜测归属。
|
||||
- BOM 数量摘要留在主界面,详细报告和执行日志可独立打开、关闭,不再挤占位号表。重新打开已完成任务不强制展开日志。
|
||||
- 上方保留本批规则与位号计划。Value 策略独立可见,表格的“新 Value”改为“自定义内容”,避免误解为实际回读值。
|
||||
- 工程路径单行省略,完整路径可通过 tooltip 和复制按钮获取;内部 quick_run_result 状态不直接显示给用户。
|
||||
- 默认 BOM 模板保持直接入口;原位号 Excel 导入/导出收进菜单。批量替换/保留明确作用于当前工程或搜索可见行。
|
||||
- 位号表支持表头排序,排序/筛选后的编辑、勾选和批量修改仍映射原始 UID;QTableView 使用一致的表格和选中样式。
|
||||
- 执行确认说明更新为当前受监督私有桌面方式,要求待处理工程不被其他 CAD 会话占用。
|
||||
- 结果窗口显示日志页内实际执行回读的图页、位号、旧料号、回读料号和核验状态。失败、未命中及未执行计划不生成成功记录;每页结果视图最多显示最近 500 条,完整日志可翻页。
|
||||
- 日志序号仅在文件身份、大小、mtime、ctime 均未变化时复用;外部追加、替换、轮转或写入失败后重新读取。缓存最多 64 个文件,保留原有 flush/fsync。
|
||||
|
||||
## 界面复放
|
||||
|
||||
默认回归套件:313 passed,261.25 秒。最后补充的无数据行表头错误用例及相关 BOM/结果用例:12 passed,10.45 秒;结果/日志末尾微调:10 passed。未为样式修改重跑 CAD 或重复整套测试。
|
||||
|
||||
执行命令:
|
||||
|
||||
```powershell
|
||||
python tools/probe_workspace_layout.py --source build/bom-native-roundtrip-fixed-20261015 --output build/ui-workspace-final-20261015
|
||||
```
|
||||
|
||||
脚本只复制历史测试数据库与证据进行复放,不启动 CAD。原测试数据库 SHA-256 未变化。
|
||||
|
||||
- 使用含 302 字符工程路径的两工程真实执行证据。
|
||||
- 1280×880 与 980×700 均检查;窄窗口位号表 viewport 为 135 像素(修复前为 0),最小尺寸提示高度从 850 降为 650。
|
||||
- 执行、开始新一轮、BOM 模板、Value 开关均在主窗口范围内;表格与下方批量按钮无重叠。
|
||||
- 跨批次无前批工程报告残留,切回恢复报告。
|
||||
- 实际结果页显示 RV05:4100-CA0000-T0 → 4100-CA0000-T7,状态为已保存并核验。
|
||||
- 截图与机器可读结果位于上述 output 目录。历史列宽设置会继续保留,窄窗口可横向滚动。
|
||||
|
||||
## 性能边界
|
||||
|
||||
千步原测试:20 工程 × 5 图页 × 10 规则,模拟执行器并启用 tracemalloc。共 1000 步,91 saved、909 no_match,顺序与唯一编号断言全部通过。
|
||||
|
||||
本次耗时 **33.387 秒,29.95 步/秒,峰值 2,201,853 字节**。原 `<30 秒` 性能断言仍失败,未调整阈值。定位证据 `build/queue-before.prof` 显示文件 open/stat、原子发布和持久写入为主要开销;文件锁与同步盘环境会影响耗时。此次序号缓存减少重复尾部读取,不能据此声称整体吞吐已达标。未移除持久写入或核验保护。
|
||||
|
||||
COM 启动偶发阻塞的根因和跨进程采集缓存仍待独立优化;本轮没有扩大启动时限,也没有减少采集一致性检查。历史日志没有单独记录的实际 Value 不由计划或库信息推算。本轮采用真实执行证据复放验证界面,原生替换与私有桌面释放沿用此前的实机验证证据。
|
||||
@@ -0,0 +1,124 @@
|
||||
{
|
||||
"release_status": "development only; user explicitly stopped packaging/publication",
|
||||
"bom_contract": "one workbook for all projects in imported group; project name/path prefilled; preview and atomically confirm per-task plans",
|
||||
"regression": {
|
||||
"prior_related_passed": 252,
|
||||
"prior_related_seconds": 53.67,
|
||||
"final_bom_ui_passed": 17,
|
||||
"final_bom_ui_seconds": 5.62,
|
||||
"counts_overlap": true
|
||||
},
|
||||
"covered_behaviors": [
|
||||
"export before inventory",
|
||||
"route identical refdes by project",
|
||||
"unknown project rejected before collection",
|
||||
"no DB plan change during preview",
|
||||
"automatic read-only collection when inventory absent",
|
||||
"reuse existing inventory",
|
||||
"atomic rollback of all affected tasks",
|
||||
"stale preview rejection",
|
||||
"untouched project scaffolds ignored",
|
||||
"task reorder and reimport",
|
||||
"cross-task UI editing and batch save",
|
||||
"execution enabled after confirmed import without separately entered rules"
|
||||
],
|
||||
"native_long_evidence_path": {
|
||||
"passed": true,
|
||||
"seconds": 54.78491889999714,
|
||||
"sheets": [
|
||||
[
|
||||
"1GPHY_8211",
|
||||
"8211_1GPHY_48PIN"
|
||||
]
|
||||
],
|
||||
"component_count": 13,
|
||||
"evidence_path_length": 318,
|
||||
"alias_paths": [
|
||||
"C:\\Users\\ABS_Windows\\AppData\\Local\\DxProductivity\\path-links\\dxp-qyr7umy5\\9e4825fbe28f7eeec038"
|
||||
],
|
||||
"aliases_removed": true,
|
||||
"original_evidence_retained": true,
|
||||
"session": {
|
||||
"desktop": "dx-325ab7da547e495abda9e92ae53c51c0",
|
||||
"token": "325ab7da547e495abda9e92ae53c51c0",
|
||||
"state": "released",
|
||||
"cad_pid": 21520,
|
||||
"guid": "{EE1C86F6x9590x41D1x90DAxF4116093AC87}",
|
||||
"startup_seconds": 34.171999999991385,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 1.75
|
||||
}
|
||||
},
|
||||
"native_desktop_observation": {
|
||||
"samples": 250,
|
||||
"file_read_samples": 250,
|
||||
"input_desktop_before": "Default",
|
||||
"input_desktop_after": "Default",
|
||||
"foreground_pids": [
|
||||
10104
|
||||
],
|
||||
"owned_cad_became_foreground": false,
|
||||
"owned_cad_on_input_desktop": false,
|
||||
"baseline_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"observed_default_cad_pids": [
|
||||
18732
|
||||
],
|
||||
"cad_exit_confirmed": {
|
||||
"21520": true
|
||||
},
|
||||
"desktop_absent": {
|
||||
"dx-325ab7da547e495abda9e92ae53c51c0": true
|
||||
},
|
||||
"sessions": {
|
||||
"dx-325ab7da547e495abda9e92ae53c51c0": {
|
||||
"desktop": "dx-325ab7da547e495abda9e92ae53c51c0",
|
||||
"token": "325ab7da547e495abda9e92ae53c51c0",
|
||||
"state": "released",
|
||||
"cad_pid": 21520,
|
||||
"guid": "{EE1C86F6x9590x41D1x90DAxF4116093AC87}",
|
||||
"startup_seconds": 34.171999999991385,
|
||||
"clean": true,
|
||||
"shutdown_seconds": 1.75,
|
||||
"evidence_path": "independent-read\\quick-run-history\\sheet-discovery-7f404713e9ed4ac7b59ea68d6973e118\\private-desktop.json"
|
||||
}
|
||||
},
|
||||
"observer_errors": []
|
||||
},
|
||||
"example_template": {
|
||||
"example": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\dist\\按工程区分BOM模板示例.xlsx",
|
||||
"rows": [
|
||||
{
|
||||
"project_name": "工程A/board.prj",
|
||||
"project_path": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\project-bom-template-preview\\projects\\工程A\\board.prj",
|
||||
"old_part_number": null,
|
||||
"new_part_number": null,
|
||||
"refdes": null,
|
||||
"schematic_name": null,
|
||||
"sheet_number": null,
|
||||
"uid": null,
|
||||
"enabled": true,
|
||||
"custom_value": null,
|
||||
"sync_nc": true
|
||||
},
|
||||
{
|
||||
"project_name": "工程B/board.prj",
|
||||
"project_path": "F:\\Sync Tool Skyworth\\Work Maps\\dxdesigner-part-replacement\\build\\project-bom-template-preview\\projects\\工程B\\board.prj",
|
||||
"old_part_number": null,
|
||||
"new_part_number": null,
|
||||
"refdes": null,
|
||||
"schematic_name": null,
|
||||
"sheet_number": null,
|
||||
"uid": null,
|
||||
"enabled": true,
|
||||
"custom_value": null,
|
||||
"sync_nc": true
|
||||
}
|
||||
],
|
||||
"sha256": "4e573f3eb920651d7482beadc7b2056939ef16c85de993b99099ef19d5e4bd2c",
|
||||
"cad_started": false,
|
||||
"published": false
|
||||
},
|
||||
"publication": "No v1.1.2 release/tag/upload; old candidate quarantined locally; v1.1.1 retained."
|
||||
}
|
||||
@@ -15,3 +15,5 @@
|
||||
真实多工程测量与压力回归记录见 [2026-10-15 多工程回归](2026-10-15-multi-project-regression.md)。
|
||||
|
||||
私有桌面正式后端的原生替换、恢复、暂停及资源释放见 [2026-10-15 私有桌面执行验证](2026-10-15-private-desktop-execution.md)。`tools/probe_private_single_step.py` 验证独立副本单步保存及故障注入后的恢复,`tools/probe_private_failures.py` 验证启动取消和 watchdog 超时后的进程/桌面释放。两者会真实启动 CAD,须单独、串行运行;普通 pytest 不启动 CAD。
|
||||
|
||||
1.1.2 的 `tools/probe_long_path_discovery.py` 在独立真实工程副本上强制走无 8.3 短名的兼容分支,读取长目录下的工程采集证据,检查 CAD/桌面释放、短入口清理及原证据保留;不会更改 Windows 的短文件名设置。
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.5 MiB |
@@ -1,5 +1,7 @@
|
||||
# DxPartReplace 器件批量替换
|
||||
|
||||
> 本文保留早期多工程任务、人工证据及 CLI 的历史说明。**当前 V1.1.x 主界面请按 [一工程一任务使用说明](v1.1.0-project-tasks.md) 操作**:通过创建弹窗选择工程,编辑位号计划,执行当前任务或顺序执行同批任务。下文早期按钮名称不代表当前界面仍提供相应入口。
|
||||
|
||||
本工具用于 DxDesigner 7.9.5 工程的器件批量替换。正式桌面流程在任何写入前创建并校验原理图精简备份,按“工程 → 图页 → 规则”严格串行执行;不会并发打开或同时修改多个工程。精简备份不复制 PCB、CES 日志、历史工程备份和数据库运行日志。桌面程序、人工证据流程和原批处理 CLI 是三条不同路径,工作范围和安全保障不能混用。
|
||||
|
||||
## 启动与诊断位置
|
||||
@@ -39,7 +41,7 @@
|
||||
|
||||
## 人工证据流程
|
||||
|
||||
界面中保留的 **启动任务 / Capture Before / Capture After / Retry** 属于 `TrialRunner` 人工证据流程,不是桌面一键自动替换的第二阶段。
|
||||
早期界面中的 **启动任务 / Capture Before / Capture After / Retry** 属于 `TrialRunner` 人工证据流程,当前 V1.1.x 主界面不再显示这些入口;它不是自动替换的第二阶段。
|
||||
|
||||
1. 启动任务并对当前项目执行 Capture Before。
|
||||
2. 由操作员在 DxDesigner 中完成受控替换,不保存。
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# DxPartReplace V1.1 使用说明(当前版本 1.1.1)
|
||||
# DxPartReplace V1.1.2 中文使用说明
|
||||
|
||||
V1.1.0 沿用原有任务视图和料号规则编辑,增加按工程拆分的任务、按位号选择的替换计划及可选 Excel 操作。
|
||||
|
||||
[窗口 GIF 操作教程](media/v1.1.2-window-bom-tutorial.gif):创建任务、导出/导入 BOM、错误行提示、保存、顺序执行、查看结果和开始新一轮。仅含工具窗口及其弹窗,实际 CAD 等待已压缩。
|
||||
|
||||
## 日常流程
|
||||
|
||||
1. 点击“新建”,填写或选择根目录,点击“读取工程”。勾选要处理的 `.prj` 后创建任务,每个工程对应一个任务。已存在未完成任务的工程不会重复创建。
|
||||
@@ -15,19 +17,21 @@ V1.1.0 沿用原有任务视图和料号规则编辑,增加按工程拆分的
|
||||
|
||||
## 执行日志与修改明细
|
||||
|
||||
任务执行结束或暂停后,底部自动展开日志。每个完成步骤按位号列出旧、新物料号,例如:`图页 MAIN:1 · 已保存并核验 · 位号 R1:4100-CA0000-T7 → 4100-CA0000-T0`;识别到 NC 并同步时另列说明。未命中、失败和保存后待核验分别显示状态,不计为成功修改。
|
||||
任务执行结束或暂停后,可以在“替换结果 / 日志”窗口查看修改明细。每个完成步骤按位号列出旧、新物料号,例如:`图页 MAIN:1 · 已保存并核验 · 位号 R1:4100-CA0000-T7 → 4100-CA0000-T0`;识别到 NC 并同步时另列说明。未命中、失败和保存后待核验分别显示状态,不计为成功修改。
|
||||
|
||||
明细来自执行器实际回读结果,不以勾选计划代替执行结果。同一工程的不同图页、规则分别保留记录;重新打开已完成任务会自动显示其日志。运行时显示最近 100 条事件,结束后显示所有保留的事件(包括轮转日志)。历史版本未记录的中间步骤无法事后补全。
|
||||
明细来自执行器实际回读结果,不以勾选计划代替执行结果。同一工程的不同图页、规则分别保留记录;重新打开已完成任务时保留计划工作区,点击“替换结果 / 日志”按需查看。日志每页读取 200 条事件,可用“上一页日志”和“最新日志”翻页,包括保留的轮转记录;结果表最多显示当前页最近 500 条位号回读记录。详情窗口关闭后释放,重新打开读取最新页。历史版本未记录的中间步骤无法事后补全。
|
||||
|
||||
执行日志同时记录采集、图页枚举及队列准备、工程备份、每个“图页 × 规则”步骤、进度同步和任务合计的耗时及速率。一个步骤可能修改多个位号,步骤速率不等于器件替换速率;失败或暂停不会计为成功完成的任务。执行器的进度阶段耗时随该步骤证据保留,用于区分打开工程、原生替换、属性恢复、保存与回读的时间。任务合计包含子步骤,统计时不能重复相加。
|
||||
|
||||
## 可选 Excel 操作
|
||||
|
||||
无需导出也能完成全部编辑。需要在 Excel 中操作时,可导出完整位号计划,或点击“BOM 模板”生成更适合物料工程师编辑的 BOM 表。BOM 一行可以填写多个位号(逗号、分号、空格或顿号分隔),并填写旧料号、新料号、替换开关、Value 和同步 NC。
|
||||
无需导出也能完成全部编辑。读取工程创建任务后,点击“BOM 模板”会生成同批所有工程的一张表:工程名称和工程路径自动填写,每个工程预留一行,旧料号、新料号和位号留空,不要求先采集或填写规则。需要同一工程多条替换时复制该工程行;工程路径用于唯一分配任务,应保持原样。发布附件另提供通用空表;已创建任务时优先使用工具生成的本批模板。
|
||||
|
||||
导入先显示到表格中预览,点击“保存位号计划”后才生效。工程、图页、UID、位号、旧料号及原 Value 是身份校验字段,应保持原样。无法添加未采集器件、重复器件或跨工程目标;不接受公式。布尔选项可使用 TRUE/FALSE 或 是/否。
|
||||
表头批注包含中文填写说明,一行可以填写多个位号(逗号、分号、空格或顿号分隔),并填写替换开关、Value 和同步 NC。只填写工程信息的空白行会被忽略,未填写替换行的工程保留原计划。需要导出已采集的完整数据时,保存编辑后使用“导出位号计划”。
|
||||
|
||||
BOM 导入会把未列出的采集位号保留为“不替换”,并要求每个填写的位号在当前工程清单中唯一匹配;同名位号跨图页时应填写图页或 UID。导入失败不会改变已保存计划。
|
||||
导入先核对所有工程归属,再按工程匹配位号;缺少清单时,按该工程 BOM 中的旧料号只读采集。不会执行替换。切换任务可查看、编辑各自预览,点击“保存本批位号计划”才一次写入所有受影响任务。保存失败全部回滚,预览期间不改已保存计划。工程、图页、UID、位号、旧料号及原 Value 用于身份校验,未知工程、重复器件或跨工程目标都会拒绝;不接受公式。布尔选项可使用 TRUE/FALSE 或 是/否。
|
||||
|
||||
BOM 首次采集或新增的位号默认“不替换”;已有计划中未列出的行保留原勾选和编辑状态,不会因后续 BOM 省略而自动停用。如果本次仅执行 BOM 列出的目标,请在预览中检查并取消其他启用行,或在 BOM 中显式填写对应的 `enabled=FALSE` 行。每个填写的位号须在当前工程清单中唯一匹配;同名位号跨图页时应填写图页或 UID。导入失败不会改变已保存计划。
|
||||
|
||||
“同步 NC”默认勾选,可以按行关闭;仅按原规则识别独立 `/NC` 标记。Value 复制选项和每行自定义 Value 延续原工具的处理方式。替换计划不允许旧、新料号相同,也不允许同批链式或循环替换。
|
||||
|
||||
@@ -47,10 +51,12 @@ BOM 导入会把未列出的采集位号保留为“不替换”,并要求每
|
||||
|
||||
任务中心的自动采集、替换和中断核验恢复已默认接入私有 Windows 桌面。工具显式启动并持有自己的 CAD,通过私有桌面、会话 GUID 和活动图页窗口所属 PID 校验连接,不接管主桌面已有 CAD,也不自动退回主桌面执行。
|
||||
|
||||
主桌面可以继续查看其他文件。开始前仍须保存并关闭本次目标工程,运行中不要在其他软件内打开或修改同一工程;共享的许可证、CPU、磁盘和中央库资源仍会影响速度。当前本机实测私有 CAD 启动约 22~35 秒,不承诺启动更快。
|
||||
主桌面可以继续查看其他文件。开始前仍须保存并关闭本次目标工程,运行中不要在其他软件内打开或修改同一工程;共享的许可证、CPU、磁盘和中央库资源仍会影响速度。本机不同轮次的私有 CAD 启动约 22~67 秒,也曾出现启动阻塞;1.1.2 的启动等待有 120 秒上限和取消检查,超时后收尾并保留诊断,不把增加等待上限视为已修复阻塞根因。
|
||||
|
||||
同一工程连续步骤复用后台会话,任务仍顺序执行。界面显示“启动后台 CAD”和“关闭 CAD 并释放后台会话”。任务完成或在步骤检查点暂停后,工具关闭自有工程、正常退出 CAD,确认进程退出,再清理自有 Job 子进程及句柄,并确认私有桌面消失。每次会话的启动、退出和清理证据单独保留在 `private-desktop-sessions` 下。
|
||||
|
||||
单步入口也执行备份、保存、重开核验和关闭。恢复成功会显示属性已保存并重开回读,无需用户另开后台工程手动保存。启动阶段尚未进入工程执行且清理成功时可以重试;执行超时、状态不确定或清理失败仍保留保护状态,由核验恢复入口处理。
|
||||
|
||||
该后端已在独立真实副本上完成替换、保存回读、暂停、恢复、启动取消及超时退出验证,详见 [验证记录](../testing/2026-10-15-private-desktop-execution.md)。1.1.1 发布包已包含此更新,详见 [版本说明](../releases/v1.1.1.md)。
|
||||
|
||||
1.1.2 增加执行证据长路径兼容:系统没有可用短文件名时,程序自动通过内部短目录入口访问,原任务数据、备份和日志仍在原目录;正常退出后清理入口。无需为了执行证据路径过长而先搬动工具目录。该兼容不代表旧版 CAD 支持任意长度的工程文件或中央库路径,相关路径仍受 CAD 本身限制。冻结 EXE 的长路径及 BOM 流程详见 [成品验收](../testing/2026-10-15-packaged-acceptance.md)。
|
||||
@@ -35,6 +35,7 @@ Dim QP_NcSyncSummary
|
||||
Dim QP_SessionMode, QP_SessionToken, QP_SessionProject, QP_MonitorJobId
|
||||
Dim QP_OwnedProjectPath, QP_SessionWaiting, QP_SessionExternalChange
|
||||
Dim QP_CheckpointSchematic, QP_CheckpointSheet
|
||||
Dim QP_ProjectAccess, QP_AccessProject
|
||||
Dim FailureState, CloseError
|
||||
Set QP_Fso = CreateObject("Scripting.FileSystemObject")
|
||||
QP_RootTemplate = "%LOCALAPPDATA%\DxProductivity\trial-task-center\quick-run"
|
||||
@@ -124,7 +125,7 @@ Else
|
||||
QP_FailureDescription = QP_FailureDescription & "; failed project close was not verified: " & CloseError
|
||||
End If
|
||||
End If
|
||||
WScript.StdErr.WriteLine CStr(QP_FailureSource) & ": " & CStr(QP_FailureDescription)
|
||||
WScript.StdErr.WriteLine "stage=" & QP_Stage & " " & CStr(QP_FailureSource) & ": " & CStr(QP_FailureDescription)
|
||||
QPFail QP_Root, FailureState, QP_FailureNumber, QP_FailureSource, QP_FailureDescription
|
||||
If Len(CStr(QP_CurrentJobId)) = 0 Then
|
||||
QP_ExitCode = 3
|
||||
@@ -301,7 +302,7 @@ Sub QPSessionNext()
|
||||
QPProgress "session_wait", 1, 1
|
||||
For Attempt = 1 To 1500
|
||||
If QP_Fso.FileExists(Path) Then
|
||||
Fields = Split(Trim(QPReadUtf8(Path)), vbTab)
|
||||
Fields = Split(Trim(QPReadContinuation(Path)), vbTab)
|
||||
If UBound(Fields) <> 1 Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "invalid continuation"
|
||||
If Fields(0) <> QP_SessionToken Then Err.Raise vbObjectError + 873, "QuickPartReplace.ProjectSession", "continuation token mismatch"
|
||||
QP_Fso.DeleteFile Path, True
|
||||
@@ -520,6 +521,7 @@ Function QPConfirmedProjectPath()
|
||||
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed sheet columns are incomplete"
|
||||
If (Len(QP_TargetSchematic) = 0) <> (Len(QP_TargetSheet) = 0) Then _
|
||||
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed sheet identity is incomplete"
|
||||
TargetPath = QPProjectAccessPath(TargetPath)
|
||||
If Not QP_Fso.FileExists(TargetPath) Then _
|
||||
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath
|
||||
If LCase(QP_Fso.GetExtensionName(TargetPath)) <> "prj" Then _
|
||||
@@ -589,6 +591,7 @@ End Function
|
||||
Sub QPEnsureProject(ByRef App, ByVal TargetPath)
|
||||
Dim ProjectData, CurrentPath, Opened, View, Documents
|
||||
Dim Schematics, Schematic, Sheets, Sheet, SheetCount, OnlySchematic, OnlySheet, Document
|
||||
TargetPath = QPProjectAccessPath(TargetPath)
|
||||
If Not QP_Fso.FileExists(TargetPath) Then _
|
||||
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath
|
||||
QP_Stage = "check_project"
|
||||
@@ -656,6 +659,7 @@ Sub QPDiscoverSheets()
|
||||
Dim Documents, Schematics, Schematic, Sheets, Sheet, Text, Count
|
||||
If Not QP_DiscoveryMode Or Not QP_OwnedProject Then _
|
||||
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "sheet discovery does not own the project"
|
||||
QP_Stage = "discovery_enumerate_sheets"
|
||||
Set Documents = QP_App.SchematicSheetDocuments()
|
||||
Set Schematics = Documents.GetAvailableSchematics()
|
||||
Text = "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbCrLf
|
||||
@@ -674,6 +678,7 @@ Sub QPDiscoverSheets()
|
||||
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "sheets.tsv"), Text
|
||||
If QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root, "inventory-request.tsv")) Then _
|
||||
QPDiscoverInventory Documents
|
||||
QP_Stage = "discovery_close_project"
|
||||
QP_App.CloseProject
|
||||
If Len(CStr(QP_App.GetProjectData().GetProjectFilePath())) > 0 Then _
|
||||
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "project did not close after sheet discovery"
|
||||
@@ -696,6 +701,7 @@ Sub QPDiscoverInventory(ByRef Documents)
|
||||
For Each Schematic In Schematics
|
||||
Set Sheets = Documents.GetAvailableSheets(CStr(Schematic))
|
||||
For Each Sheet In Sheets
|
||||
QP_Stage = "inventory_open_sheet " & CStr(Schematic) & ":" & CStr(Sheet)
|
||||
Set Document = Documents.Open(CStr(Schematic), CStr(Sheet))
|
||||
If Document Is Nothing Then Err.Raise vbObjectError + 872, _
|
||||
"QuickPartReplace.Discovery", "inventory sheet could not be opened"
|
||||
@@ -705,8 +711,10 @@ Sub QPDiscoverInventory(ByRef Documents)
|
||||
"QuickPartReplace.Discovery", "inventory sheet did not become active"
|
||||
If CStr(View.GetName(0)) <> CStr(Schematic) Or CStr(View.Block.SheetNum) <> CStr(Sheet) Then _
|
||||
Err.Raise vbObjectError + 872, "QuickPartReplace.Discovery", "inventory sheet identity changed"
|
||||
QP_Stage = "inventory_query " & CStr(Schematic) & ":" & CStr(Sheet)
|
||||
Set Components = View.Query(VDM_COMP, VD_ALL)
|
||||
For Each Comp In Components
|
||||
QP_Stage = "inventory_read_component " & CStr(Schematic) & ":" & CStr(Sheet)
|
||||
PartNumber = ""
|
||||
Set PartAttr = QPFindCurrentAttribute(Comp, "Part Number")
|
||||
If Not PartAttr Is Nothing Then PartNumber = QPEffectiveAttributeValue(PartAttr)
|
||||
@@ -732,6 +740,7 @@ Sub QPDiscoverInventory(ByRef Documents)
|
||||
End If
|
||||
End If
|
||||
Next
|
||||
QP_Stage = "inventory_close_sheet " & CStr(Schematic) & ":" & CStr(Sheet)
|
||||
Document.Close False, ""
|
||||
Count = Count + 1
|
||||
QPProgress "inventory_sheets", Count, 0
|
||||
@@ -994,6 +1003,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||
QP_NativeCallActive = True
|
||||
QPProgress "native_replace", 0, 1
|
||||
ExitCode = Shell.Run(CommandLine, 0, True)
|
||||
QPLog QP_Root, "INFO", "native_helper_exit code=" & CStr(ExitCode)
|
||||
QP_NativeMutationPossible = QPNativeReportShowsMutation(SnapshotPath & ".native.json")
|
||||
QP_NativeCallActive = False
|
||||
QPInvalidatePinIndex
|
||||
@@ -1008,7 +1018,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||
"; report: " & SnapshotPath & ".native.json"
|
||||
Else
|
||||
Err.Raise vbObjectError + 839, "QuickPartReplace", _
|
||||
"automatic native replacement failed; see " & SnapshotPath & ".native.json"
|
||||
"automatic native replacement failed (exit=" & CStr(ExitCode) & "); see " & SnapshotPath & ".native.json"
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
@@ -2492,7 +2502,7 @@ Function QPProjectPath()
|
||||
If Len(Trim(ProjectPath)) = 0 Then
|
||||
Err.Raise vbObjectError + 827, "QuickPartReplace", "no active project"
|
||||
End If
|
||||
QPProjectPath = ProjectPath
|
||||
QPProjectPath = QPCanonicalPath(ProjectPath)
|
||||
End Function
|
||||
|
||||
Function QPSheetIdentity()
|
||||
@@ -2844,6 +2854,27 @@ Function QPReadUtf8(ByVal Path)
|
||||
Stream.Close
|
||||
End Function
|
||||
|
||||
Function QPReadContinuation(ByVal Path)
|
||||
Dim Attempt, Text, Number, Description
|
||||
' Atomic Windows replacement and background readers may briefly deny access.
|
||||
' Only the continuation read retries; token and checkpoint checks remain strict.
|
||||
For Attempt = 1 To 20
|
||||
On Error Resume Next
|
||||
Err.Clear
|
||||
Text = QPReadUtf8(Path)
|
||||
Number = Err.Number
|
||||
Description = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
If Number = 0 Then
|
||||
QPReadContinuation = Text
|
||||
Exit Function
|
||||
End If
|
||||
WScript.Sleep 50
|
||||
Next
|
||||
Err.Raise Number, "QuickPartReplace.ProjectSession", Description
|
||||
End Function
|
||||
|
||||
Sub QPWriteUtf8(ByVal Path, ByVal Text)
|
||||
Dim Stream
|
||||
Set Stream = CreateObject("ADODB.Stream")
|
||||
@@ -2902,8 +2933,49 @@ Function QPDecode(ByVal Value)
|
||||
End Function
|
||||
|
||||
Function QPCanonicalPath(ByVal Value)
|
||||
QPCanonicalPath = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), _
|
||||
"/", "\"))
|
||||
Dim Identity
|
||||
QPEnsureProjectAccess
|
||||
Identity = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), "/", "\"))
|
||||
If QP_AccessProject.Exists(Identity) Then Identity = QP_AccessProject(Identity)
|
||||
QPCanonicalPath = Identity
|
||||
End Function
|
||||
|
||||
Sub QPEnsureProjectAccess()
|
||||
Dim Path, Lines, Fields, Index, Canonical, Access
|
||||
If IsObject(QP_ProjectAccess) Then Exit Sub
|
||||
Set QP_ProjectAccess = CreateObject("Scripting.Dictionary")
|
||||
Set QP_AccessProject = CreateObject("Scripting.Dictionary")
|
||||
QP_ProjectAccess.CompareMode = 1
|
||||
QP_AccessProject.CompareMode = 1
|
||||
Path = QP_Fso.BuildPath(QP_Root, "project-access.tsv")
|
||||
If Not QP_Fso.FileExists(Path) Then Exit Sub
|
||||
Lines = Split(QPReadUtf8(Path), vbLf)
|
||||
If Replace(Lines(0), vbCr, "") <> "project_path" & vbTab & "access_path" Then _
|
||||
Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "invalid project access header"
|
||||
For Index = 1 To UBound(Lines)
|
||||
If Len(Replace(Lines(Index), vbCr, "")) > 0 Then
|
||||
Fields = Split(Replace(Lines(Index), vbCr, ""), vbTab)
|
||||
If UBound(Fields) <> 1 Then _
|
||||
Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "invalid project access row"
|
||||
Canonical = LCase(Replace(QP_Fso.GetAbsolutePathName(Fields(0)), "/", "\"))
|
||||
Access = LCase(Replace(QP_Fso.GetAbsolutePathName(Fields(1)), "/", "\"))
|
||||
If QP_ProjectAccess.Exists(Canonical) Or QP_AccessProject.Exists(Access) Then _
|
||||
Err.Raise vbObjectError + 874, "QuickPartReplace.ProjectAccess", "duplicate project access identity"
|
||||
QP_ProjectAccess.Add Canonical, Fields(1)
|
||||
QP_AccessProject.Add Access, Canonical
|
||||
End If
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Function QPProjectAccessPath(ByVal Value)
|
||||
Dim Identity
|
||||
QPEnsureProjectAccess
|
||||
Identity = LCase(Replace(QP_Fso.GetAbsolutePathName(CStr(Value)), "/", "\"))
|
||||
If QP_ProjectAccess.Exists(Identity) Then
|
||||
QPProjectAccessPath = QP_ProjectAccess(Identity)
|
||||
Else
|
||||
QPProjectAccessPath = Value
|
||||
End If
|
||||
End Function
|
||||
|
||||
Sub QPRaiseCaptured(ByVal Number, ByVal Source, ByVal Description, ByVal Fallback)
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "dx-productivity"
|
||||
version = "1.1.1"
|
||||
version = "1.1.2"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
|
||||
|
||||
|
||||
@@ -75,11 +75,15 @@ def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
|
||||
|
||||
def _log_startup(context: LoggingContext, data_root: Path, database_path: Path) -> None:
|
||||
# platform.platform() queries WMI on Windows; diagnostics must not delay or
|
||||
# fail CAD startup because the WMI provider is slow or out of resources.
|
||||
version = sys.getwindowsversion() if os.name == 'nt' else None
|
||||
os_description = f'Windows {version.major}.{version.minor}.{version.build}' if version else platform.platform()
|
||||
context.logger.info(
|
||||
"application_start version=%s executable=%s os=%s data_root=%s database=%s application_log=%s",
|
||||
VERSION,
|
||||
sys.executable,
|
||||
platform.platform(),
|
||||
os_description,
|
||||
data_root,
|
||||
database_path,
|
||||
context.application_log_path,
|
||||
@@ -117,11 +121,6 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
database_path = data_root / "task-center.db"
|
||||
_log_startup(logging_context, data_root, database_path)
|
||||
store = TaskStore(database_path)
|
||||
recovered = store.recover_interrupted_work()
|
||||
if recovered:
|
||||
logging_context.logger.warning("recovered_interrupted_projects=%s", ",".join(recovered))
|
||||
else:
|
||||
logging_context.logger.info("recovered_interrupted_projects=none")
|
||||
service = TaskCenterService(store, logging_context)
|
||||
qt_application = QApplication([sys.executable, *(argv or ())])
|
||||
window = _load_window()(service)
|
||||
|
||||
@@ -21,12 +21,7 @@ from .quick_run import (
|
||||
from .retention import maintain_quick_run_storage
|
||||
from .schematic_backup import create_schematic_backup
|
||||
from .execution_metrics import measure_phase
|
||||
# Keep legacy helper imports patchable for queue integrations.
|
||||
from .batch_backup import (
|
||||
BatchBackupCoordinator,
|
||||
_BACKUP_STATE_NAME, _BACKUP_DIRECTORY_NAME,
|
||||
_backup_key, _read_backup_state, _write_backup_state, _reusable_backup,
|
||||
)
|
||||
from .batch_backup import BatchBackupCoordinator, _write_backup_state
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Transactional batch defaults, kept separate from per-component choices."""
|
||||
from dataclasses import replace
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskStatus
|
||||
from .rule_validation import validate_mapping_pairs
|
||||
|
||||
|
||||
def members(store, task_id):
|
||||
task = store.get_task(task_id)
|
||||
if not task.group_id:
|
||||
return (task,)
|
||||
return tuple(t for t in store.list_project_group(task.group_id) if t.status is not TaskStatus.DELETED)
|
||||
|
||||
|
||||
def _signature(rule):
|
||||
return (rule.old_part_number.casefold(), rule.new_part_number, rule.enabled,
|
||||
rule.custom_value_enabled, rule.custom_value, rule.sync_nc)
|
||||
|
||||
|
||||
def batch_rule_view(store, task_id, *, strict=False):
|
||||
"""Read legacy groups too; expose conflicting rows so users can resolve them."""
|
||||
with store.transaction():
|
||||
tasks = members(store, task_id)
|
||||
task = store.get_task(task_id)
|
||||
if task.status is TaskStatus.DELETED or not task.group_id:
|
||||
return store.list_rules(task_id)
|
||||
local = {r.old_part_number.casefold(): r for r in store.list_rules(task_id)}
|
||||
return merge_rule_view((rule for item in tasks for rule in store.list_rules(item.task_id)), local, strict=strict)
|
||||
|
||||
|
||||
def merge_rule_view(rules, local, *, strict=False):
|
||||
"""Merge already captured rows without reading a newer database generation."""
|
||||
seen, result = {}, []
|
||||
for rule in rules:
|
||||
key = rule.old_part_number.casefold()
|
||||
if key in seen and seen[key] != _signature(rule):
|
||||
if strict:
|
||||
raise TaskCenterError('batch_rules_conflict', f'同批料号规则不一致:{rule.old_part_number},请编辑该规则统一默认值')
|
||||
result.append(rule)
|
||||
elif key not in seen:
|
||||
seen[key] = _signature(rule)
|
||||
preferred = local.get(key)
|
||||
result.append(preferred if preferred and _signature(preferred) == _signature(rule) else rule)
|
||||
if strict:
|
||||
validate_mapping_pairs((r.old_part_number, r.new_part_number) for r in result if r.enabled)
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _options(rule):
|
||||
return dict(old_part_number=rule.old_part_number, new_part_number=rule.new_part_number,
|
||||
enabled=rule.enabled, custom_value_enabled=rule.custom_value_enabled,
|
||||
custom_value=rule.custom_value, sync_nc=rule.sync_nc)
|
||||
|
||||
|
||||
def seed_defaults(rows, rules):
|
||||
"""Fill new inventory rows only; callers retain every existing edited row."""
|
||||
defaults = {r.old_part_number.casefold(): r for r in rules if r.enabled}
|
||||
return tuple(replace(row, new_part_number=rule.new_part_number,
|
||||
custom_value_enabled=rule.custom_value_enabled,
|
||||
custom_value=rule.custom_value, sync_nc=rule.sync_nc)
|
||||
if (rule := defaults.get(row.target.old_part_number.casefold())) else row for row in rows)
|
||||
|
||||
|
||||
def _propagate(store, task_id, before, after):
|
||||
if not store.get_task(task_id).target_plan_mode:
|
||||
return
|
||||
rows = store.list_target_plan(task_id)
|
||||
defaults_before = {r.old_part_number.casefold(): r for r in before}
|
||||
defaults_after = {r.old_part_number.casefold(): r for r in after}
|
||||
updated = []
|
||||
for row in rows:
|
||||
key = row.target.old_part_number.casefold()
|
||||
prior, rule = defaults_before.get(key), defaults_after.get(key)
|
||||
changes = {}
|
||||
if rule:
|
||||
# A rule's enabled flag controls discovery, never the user's selection.
|
||||
if prior:
|
||||
for field in ('new_part_number', 'sync_nc'):
|
||||
if getattr(row, field) == getattr(prior, field):
|
||||
changes[field] = getattr(rule, field)
|
||||
if (row.custom_value_enabled, row.custom_value) == (prior.custom_value_enabled, prior.custom_value):
|
||||
changes.update(custom_value_enabled=rule.custom_value_enabled, custom_value=rule.custom_value)
|
||||
elif not row.new_part_number:
|
||||
changes['new_part_number'] = rule.new_part_number
|
||||
if row.sync_nc:
|
||||
changes['sync_nc'] = rule.sync_nc
|
||||
if not row.custom_value_enabled and not row.custom_value:
|
||||
changes.update(custom_value_enabled=rule.custom_value_enabled, custom_value=rule.custom_value)
|
||||
updated.append(replace(row, **changes))
|
||||
if tuple(updated) != rows:
|
||||
store.replace_target_plan(task_id, updated)
|
||||
|
||||
|
||||
def mutate_batch_rules(service, task_id, operation, *, rule_id=None, offset=0, **options):
|
||||
store = service._store
|
||||
with store.transaction():
|
||||
task = store.get_task(task_id)
|
||||
tasks = members(store, task_id)
|
||||
if task.status is TaskStatus.DELETED or not tasks:
|
||||
raise TaskCenterError('rules_locked', '已删除任务不能编辑料号规则')
|
||||
for member in tasks:
|
||||
if member.group_id and member.status not in {TaskStatus.DRAFT, TaskStatus.READY, TaskStatus.FAILED}:
|
||||
raise TaskCenterError('rules_locked', f'同批任务「{member.name}」已冻结,不能修改本批料号规则')
|
||||
service._editable_rules(member.task_id, lambda: None)
|
||||
before = {t.task_id: store.list_rules(t.task_id) for t in tasks}
|
||||
selected = store.get_rule(rule_id) if rule_id else None
|
||||
selected_key = selected.old_part_number.casefold() if selected else None
|
||||
if operation == 'update':
|
||||
for field in ('custom_value_enabled', 'custom_value', 'sync_nc'):
|
||||
if options.get(field) is None:
|
||||
options[field] = getattr(selected, field)
|
||||
union = {}
|
||||
# Existing per-project rules are merged when unambiguous. An explicit
|
||||
# edit/delete may resolve its own old-number conflict, never other keys.
|
||||
for rules in before.values():
|
||||
local_keys = set()
|
||||
for rule in rules:
|
||||
key = rule.old_part_number.casefold()
|
||||
if key in local_keys:
|
||||
raise TaskCenterError('batch_rules_conflict', f'同批旧料号重复:{rule.old_part_number},请先整理重复规则')
|
||||
local_keys.add(key)
|
||||
if key in union and _signature(union[key]) != _signature(rule):
|
||||
if key != selected_key or operation not in {'update', 'delete'}:
|
||||
raise TaskCenterError('batch_rules_conflict', f'同批料号规则不一致:{rule.old_part_number},请编辑该规则统一默认值')
|
||||
else:
|
||||
union.setdefault(key, rule)
|
||||
for member in tasks:
|
||||
local = {r.old_part_number.casefold(): r for r in before[member.task_id]}
|
||||
if selected_key in local and operation in {'update', 'delete'}:
|
||||
# Resolve a historical chain/conflict before copying other keys.
|
||||
# Disabling is temporary and remains inside this batch transaction.
|
||||
prior = local[selected_key]
|
||||
if operation == 'delete':
|
||||
store.delete_rule(prior.rule_id)
|
||||
del local[selected_key]
|
||||
else:
|
||||
store.update_rule(prior.rule_id, **(_options(prior) | {'enabled': False}))
|
||||
for key, rule in union.items():
|
||||
if key == selected_key and operation == 'delete':
|
||||
continue
|
||||
if key not in local:
|
||||
settings = _options(rule)
|
||||
if key == selected_key and operation == 'update':
|
||||
settings['enabled'] = False
|
||||
local[key] = store.add_rule(member.task_id, **settings)
|
||||
# Historical per-project additions may have different positions.
|
||||
# Normalize to the same batch order before applying a relative move.
|
||||
store._write_rule_positions([local[key] for key in union if key in local])
|
||||
if operation == 'add':
|
||||
if options['old_part_number'].strip().casefold() in local:
|
||||
raise TaskCenterError('batch_rules_conflict', '该旧料号已有本批规则,请编辑已有规则')
|
||||
result = store.add_rule(member.task_id, **options)
|
||||
elif operation == 'update':
|
||||
new_key = options['old_part_number'].strip().casefold()
|
||||
if new_key != selected_key and new_key in local:
|
||||
raise TaskCenterError('batch_rules_conflict', '该旧料号已有本批规则,请编辑已有规则')
|
||||
result = store.update_rule(local[selected_key].rule_id, **options)
|
||||
elif operation == 'delete':
|
||||
result = None
|
||||
elif operation == 'move':
|
||||
result = store.move_rule(local[selected_key].rule_id, offset)
|
||||
else:
|
||||
raise ValueError(operation)
|
||||
_propagate(store, member.task_id, before[member.task_id], store.list_rules(member.task_id))
|
||||
if member.task_id == task_id:
|
||||
chosen = result
|
||||
return chosen
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Project routing, staged previews and atomic confirmation for a batch BOM."""
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .bom_plan import write_bom_template
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskStatus
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BomProjectPreview:
|
||||
task_id: str
|
||||
project_path: Path
|
||||
baseline: tuple
|
||||
inventory: tuple
|
||||
rows: tuple
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BomBatchPreview:
|
||||
anchor_task_id: str
|
||||
scope: tuple
|
||||
projects: tuple[BomProjectPreview, ...]
|
||||
|
||||
|
||||
def _scope(store, task_id):
|
||||
task = store.get_task(task_id)
|
||||
tasks = store.list_project_group(task.group_id) if task.group_id else (task,)
|
||||
result = []
|
||||
for item in tasks:
|
||||
if item.status is TaskStatus.DELETED:
|
||||
continue
|
||||
projects = store.list_projects(item.task_id)
|
||||
if len(projects) != 1:
|
||||
raise TaskCenterError('project_binding', '批量 BOM 需要一个工程对应一个任务')
|
||||
result.append((item, projects[0]))
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _identity(scope):
|
||||
# BOM ownership depends on membership, not the order of later execution.
|
||||
return tuple(sorted((task.task_id, str(project.path.resolve()).casefold()) for task, project in 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)
|
||||
|
||||
|
||||
def _assert_editable(service, task_id):
|
||||
context = service.task_context(task_id)
|
||||
if (context.task.status not in {TaskStatus.DRAFT, TaskStatus.READY} or context.has_evidence
|
||||
or context.interrupted or not context.project or not context.project.available):
|
||||
raise TaskCenterError('target_plan_locked', f'工程任务当前不能修改 BOM 计划:{context.task.name}')
|
||||
|
||||
|
||||
def preview_batch(service, task_id, path, *, stop_event=None, on_progress=None):
|
||||
"""Strict adapter to the same validation engine used by the import report."""
|
||||
from .bom_import_report import inspect_batch
|
||||
|
||||
report = inspect_batch(service, task_id, path, stop_event=stop_event, on_progress=on_progress)
|
||||
if report.preview is not None:
|
||||
return report.preview
|
||||
failed = next((row for row in report.rows if row.status == 'failed'), None)
|
||||
message = (f'工程「{failed.project_name}」({failed.project_path}) · '
|
||||
f'Excel 第 {failed.excel_row} 行:{failed.reason}' if failed else
|
||||
'\n'.join(report.errors) or 'BOM 校验未通过')
|
||||
raise TaskCenterError('bom_import', message)
|
||||
|
||||
|
||||
def save_batch(service, preview, rows_by_task):
|
||||
store = service._store
|
||||
expected = {project.task_id for project in preview.projects}
|
||||
if not expected or set(rows_by_task) != expected:
|
||||
raise TaskCenterError('bom_import', '本批 BOM 预览的工程范围已改变')
|
||||
result = {}
|
||||
with store.transaction():
|
||||
if _identity(_scope(store, preview.anchor_task_id)) != preview.scope:
|
||||
raise TaskCenterError('project_binding', '本批工程范围已改变,请重新导入 BOM')
|
||||
for project in preview.projects:
|
||||
_assert_editable(service, project.task_id)
|
||||
if tuple(store.list_target_plan(project.task_id)) != project.baseline:
|
||||
raise TaskCenterError('target_identity', '工程位号计划在 BOM 预览后已改变,请重新导入')
|
||||
for project in preview.projects:
|
||||
store.record_target_inventory(project.task_id, project.inventory)
|
||||
result[project.task_id] = store.replace_target_plan(project.task_id, rows_by_task[project.task_id])
|
||||
return result
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Read-only, exhaustive BOM validation with an all-or-nothing preview."""
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
from zipfile import BadZipFile
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .bom_batch import BomBatchPreview, BomProjectPreview, _assert_editable, _identity, _scope
|
||||
from .bom_plan import BomMatcher, _normal_headers, _text, parse_bom_row
|
||||
from .errors import TaskCenterError
|
||||
from .store_target_plan import merge_target_inventory
|
||||
from .target_plan import ProjectIdentityResolver, compile_target_rules
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BomRowResult:
|
||||
excel_row: int
|
||||
project_path: str
|
||||
project_name: str
|
||||
status: str # passed, failed, unchecked
|
||||
reason: str = ''
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BomProjectResult:
|
||||
project_path: str
|
||||
project_name: str
|
||||
status: str
|
||||
excel_rows: tuple[int, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BomImportReport:
|
||||
rows: tuple[BomRowResult, ...]
|
||||
projects: tuple[BomProjectResult, ...]
|
||||
preview: BomBatchPreview | None = None
|
||||
errors: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def total_rows(self):
|
||||
return len(self.rows)
|
||||
|
||||
@property
|
||||
def passed_rows(self):
|
||||
return sum(row.status == 'passed' for row in self.rows)
|
||||
|
||||
@property
|
||||
def failed_rows(self):
|
||||
return sum(row.status == 'failed' for row in self.rows)
|
||||
|
||||
@property
|
||||
def unchecked_rows(self):
|
||||
return sum(row.status == 'unchecked' for row in self.rows)
|
||||
|
||||
@property
|
||||
def total_projects(self):
|
||||
return len(self.projects)
|
||||
|
||||
@property
|
||||
def passed_projects(self):
|
||||
return sum(project.status == 'passed' for project in self.projects)
|
||||
|
||||
@property
|
||||
def failed_projects(self):
|
||||
return sum(project.status == 'failed' for project in self.projects)
|
||||
|
||||
@property
|
||||
def unchecked_projects(self):
|
||||
return sum(project.status == 'unchecked' for project in self.projects)
|
||||
|
||||
|
||||
def _report(rows, preview=None, errors=()):
|
||||
grouped = {}
|
||||
for row in rows:
|
||||
grouped.setdefault((row.project_path, row.project_name), []).append(row)
|
||||
projects = tuple(BomProjectResult(path, name,
|
||||
'failed' if any(row.status == 'failed' for row in items) else
|
||||
'unchecked' if any(row.status == 'unchecked' for row in items) else 'passed',
|
||||
tuple(row.excel_row for row in items)) for (path, name), items in grouped.items())
|
||||
return BomImportReport(tuple(rows), projects, preview, tuple(errors))
|
||||
|
||||
|
||||
def inspect_batch(service, task_id, path, *, stop_event=None, on_progress=None):
|
||||
"""Validate all independent rows; never persist inventory or return partial plans.
|
||||
|
||||
Operational failures (including cancellation and native cleanup) propagate so
|
||||
callers cannot accidentally continue opening CAD after an unsafe failure.
|
||||
"""
|
||||
def check_cancelled():
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', 'BOM 导入已取消')
|
||||
|
||||
check_cancelled()
|
||||
scope = _scope(service._store, task_id)
|
||||
routing = ProjectIdentityResolver()
|
||||
owners = {routing.project(project.path): (task, project) for task, project in scope}
|
||||
if len(owners) != len(scope):
|
||||
raise TaskCenterError('project_binding', '同批任务存在重复工程')
|
||||
rows, records, grouped = [], {}, {}
|
||||
workbook = None
|
||||
try:
|
||||
workbook = load_workbook(Path(path), read_only=True, data_only=False)
|
||||
sheet = workbook.active
|
||||
cells = list(sheet.iter_rows())
|
||||
header_error = ''
|
||||
if len(workbook.worksheets) != 1:
|
||||
header_error = 'BOM 工作簿只能包含一个工作表'
|
||||
elif not cells:
|
||||
header_error = 'BOM 工作表为空'
|
||||
headers = _normal_headers(tuple(cell.value for cell in cells[0])) if cells else ()
|
||||
names = tuple(name for name in headers if name)
|
||||
if not header_error and len(set(names)) != len(names):
|
||||
header_error = 'BOM 列名重复'
|
||||
if not header_error and not {'old_part_number', 'new_part_number', 'refdes'} <= set(headers):
|
||||
header_error = 'BOM 必须包含旧料号、新料号和位号列'
|
||||
if cells and any(cell.data_type == 'f' for cell in cells[0]):
|
||||
header_error = 'BOM 表头不接受公式'
|
||||
positions = {name: index for index, name in enumerate(headers) if name}
|
||||
for number, row_cells in enumerate(cells[1:], 2):
|
||||
check_cancelled()
|
||||
values = tuple(cell.value for cell in row_cells)
|
||||
if not any(value not in (None, '') for value in values):
|
||||
continue
|
||||
project_path = _text(values, positions, 'project_path')
|
||||
project_name = _text(values, positions, 'project_name')
|
||||
if project_path:
|
||||
owner = owners.get(routing.project(project_path))
|
||||
if owner is not None:
|
||||
project_path, project_name = str(owner[1].path), owner[0].name
|
||||
elif len(scope) == 1:
|
||||
project_path, project_name = str(scope[0][1].path), scope[0][0].name
|
||||
reason = header_error
|
||||
record = None
|
||||
if not reason:
|
||||
try:
|
||||
record = parse_bom_row(row_cells, positions)
|
||||
if record is None:
|
||||
continue
|
||||
except (ValueError, TypeError, TaskCenterError) as error:
|
||||
reason = str(error)
|
||||
key = ''
|
||||
if not reason:
|
||||
if not record.project_path and len(scope) != 1:
|
||||
reason = '多工程 BOM 必须填写工程路径列,不能按位号猜测工程'
|
||||
else:
|
||||
key = routing.project(record.project_path) if record.project_path else next(iter(owners))
|
||||
if key not in owners:
|
||||
reason = f'BOM 工程不属于当前批次:{record.project_path}'
|
||||
else:
|
||||
task, project = owners[key]
|
||||
project_path, project_name = str(project.path), task.name
|
||||
records[len(rows)] = record
|
||||
grouped.setdefault(key, []).append(len(rows))
|
||||
rows.append(BomRowResult(number, project_path, project_name,
|
||||
'failed' if reason else 'unchecked', reason or '尚未匹配工程位号'))
|
||||
if header_error:
|
||||
return _report(rows, errors=(f'Excel 第 1 行:{header_error}',))
|
||||
except TaskCenterError:
|
||||
raise
|
||||
except (OSError, ValueError, TypeError, KeyError, BadZipFile) as error:
|
||||
return _report(rows, errors=(str(error),))
|
||||
finally:
|
||||
if workbook is not None:
|
||||
workbook.close()
|
||||
if not rows:
|
||||
return _report(rows, errors=('BOM 尚未填写替换行,请填写旧料号、新料号和位号',))
|
||||
# Do not start any reader until all spreadsheet/routing/editability checks pass.
|
||||
for key, indices in grouped.items():
|
||||
try:
|
||||
_assert_editable(service, owners[key][0].task_id)
|
||||
except TaskCenterError as error:
|
||||
for index in indices:
|
||||
rows[index] = replace(rows[index], status='failed', reason=error.message)
|
||||
if any(row.status == 'failed' for row in rows):
|
||||
return _report(rows)
|
||||
previews = []
|
||||
for position, (key, indices) in enumerate(grouped.items(), 1):
|
||||
check_cancelled()
|
||||
task, project = owners[key]
|
||||
def progress(message):
|
||||
if on_progress is not None:
|
||||
on_progress(f'工程 {position}/{len(grouped)} · {message}')
|
||||
progress(f'正在读取工程「{task.name}」({project.path})')
|
||||
baseline = tuple(service._store.list_target_plan(task.task_id))
|
||||
requested = tuple(dict.fromkeys(records[index].old for index in indices))
|
||||
known = tuple(dict.fromkeys(row.target.old_part_number for row in baseline))
|
||||
if baseline and {part.casefold() for part in requested} <= {part.casefold() for part in known}:
|
||||
inventory = tuple(row.target for row in baseline)
|
||||
else:
|
||||
controls = {}
|
||||
if stop_event is not None:
|
||||
controls['stop_event'] = stop_event
|
||||
if on_progress is not None:
|
||||
controls['on_progress'] = progress
|
||||
inventory = tuple(service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory(
|
||||
project.path, tuple(dict.fromkeys((*known, *requested))), **controls))
|
||||
check_cancelled()
|
||||
merged = merge_target_inventory(baseline, inventory)
|
||||
matched_rows, touched = {}, {}
|
||||
matcher = BomMatcher(merged) if merged else None
|
||||
for index in indices:
|
||||
try:
|
||||
# A per-record match reports independent row errors without hiding later rows.
|
||||
if matcher is None:
|
||||
raise TaskCenterError('target_inventory', '未采集到可匹配的工程位号')
|
||||
matched = matcher.match_record(records[index])
|
||||
compile_target_rules(tuple(matched.values()))
|
||||
for target_key, row in matched.items():
|
||||
touched.setdefault(target_key, []).append(index)
|
||||
matched_rows[target_key] = row
|
||||
rows[index] = replace(rows[index], status='passed', reason='校验通过')
|
||||
except TaskCenterError as error:
|
||||
rows[index] = replace(rows[index], status='failed', reason=error.message)
|
||||
for target, indices_for_target in touched.items():
|
||||
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) + ')')
|
||||
combined = tuple(matched_rows.get(key, row) for key, row in matcher.by_key.items()) if matcher else ()
|
||||
try:
|
||||
compile_target_rules(combined)
|
||||
except TaskCenterError as error:
|
||||
for index in indices:
|
||||
if rows[index].status == 'passed':
|
||||
rows[index] = replace(rows[index], status='failed', reason=error.message)
|
||||
previews.append(BomProjectPreview(task.task_id, project.path, baseline, inventory, combined))
|
||||
progress(f'「{task.name}」校验完成')
|
||||
check_cancelled()
|
||||
preview = None if any(row.status != 'passed' for row in rows) else BomBatchPreview(
|
||||
task_id, _identity(scope), tuple(previews))
|
||||
return _report(rows, preview)
|
||||
@@ -3,20 +3,37 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.comments import Comment
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.worksheet.datavalidation import DataValidation
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .target_plan import TargetPlanRow, compile_target_rules
|
||||
from .target_plan import ProjectIdentityResolver, TargetPlanRow, compile_target_rules
|
||||
|
||||
|
||||
BOM_HEADERS = ('old_part_number', 'new_part_number', 'refdes', 'schematic_name',
|
||||
BOM_HEADERS = ('project_name', 'project_path', 'old_part_number', 'new_part_number', 'refdes', 'schematic_name',
|
||||
'sheet_number', 'uid', 'enabled', 'custom_value', 'sync_nc')
|
||||
_HEADER_HELP = (
|
||||
'工程名称:自动填写,便于查看;导入时按工程路径分配任务。',
|
||||
'工程路径:自动填写,用于区分同批工程,请保持原样;需要更多规则时复制该工程行。',
|
||||
'旧料号,必填。按文本填写,保留前导零。',
|
||||
'新料号,必填。按文本填写,保留前导零。',
|
||||
'位号,必填。一行可填 R1,R2,R3,支持逗号、分号、空格或顿号分隔。',
|
||||
'原理图名称,可选。位号重复时用于精确匹配。',
|
||||
'图页,可选。位号跨页重复时应填写图页或 UID。',
|
||||
'器件 UID,可选;填写时必须与采集结果一致。',
|
||||
'是否替换:TRUE/FALSE 或 是/否;留空默认替换。未列出的位号保留。',
|
||||
'自定义 Value,可选;留空沿用工具原有 Value 策略。',
|
||||
'同步 NC:TRUE/FALSE 或 是/否;留空默认开启。',
|
||||
)
|
||||
_REFDES_SPLIT = re.compile(r'[,,;;、\s]+')
|
||||
_ALIASES = {
|
||||
'工程名称': 'project_name', '项目名称': 'project_name',
|
||||
'工程': 'project_path', '工程路径': 'project_path', '项目路径': 'project_path',
|
||||
'旧料号': 'old_part_number', '旧物料编码': 'old_part_number', 'old_part': 'old_part_number',
|
||||
'新料号': 'new_part_number', '新物料编码': 'new_part_number', 'new_part': 'new_part_number',
|
||||
'位号': 'refdes', '参考标号': 'refdes', 'refdes': 'refdes', 'reference_designator': 'refdes',
|
||||
@@ -34,32 +51,47 @@ def write_bom_template(path: Path, records=()) -> Path:
|
||||
sheet.append(BOM_HEADERS)
|
||||
for record in records:
|
||||
sheet.append(tuple(record.get(header, '') for header in BOM_HEADERS))
|
||||
for cell in sheet[1]:
|
||||
wrapped = Alignment(wrap_text=True, vertical='top')
|
||||
for row in sheet.iter_rows():
|
||||
for cell in row:
|
||||
cell.alignment = wrapped
|
||||
# Leave row heights automatic so Excel can fit wrapped text after editing.
|
||||
for cell, help_text in zip(sheet[1], _HEADER_HELP):
|
||||
cell.font = Font(bold=True, color='FFFFFF')
|
||||
cell.fill = PatternFill('solid', fgColor='1D3557')
|
||||
sheet.freeze_panes = 'A2'
|
||||
cell.comment = Comment(help_text, 'DxPartReplace')
|
||||
sheet.freeze_panes = 'C2'
|
||||
sheet.auto_filter.ref = sheet.dimensions
|
||||
for column in ('G', 'I'):
|
||||
for column in ('I', 'K'):
|
||||
validation = DataValidation(type='list', formula1='"TRUE,FALSE"', allow_blank=False)
|
||||
sheet.add_data_validation(validation)
|
||||
validation.add(f'{column}2:{column}{max(2, sheet.max_row + 500)}')
|
||||
for column, width in {'A': 22, 'B': 22, 'C': 28, 'D': 18, 'E': 14,
|
||||
'F': 28, 'G': 12, 'H': 24, 'I': 12}.items():
|
||||
for column, width in {'A': 30, 'B': 64, 'C': 22, 'D': 22, 'E': 28, 'F': 18, 'G': 14,
|
||||
'H': 28, 'I': 12, 'J': 24, 'K': 12}.items():
|
||||
sheet.column_dimensions[column].width = width
|
||||
sheet.column_dimensions[column].alignment = wrapped
|
||||
for column in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J'):
|
||||
sheet.column_dimensions[column].number_format = '@'
|
||||
path = Path(path)
|
||||
workbook.save(path)
|
||||
return path
|
||||
|
||||
|
||||
def read_bom_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
|
||||
baseline = store.list_target_plan(task_id)
|
||||
if not baseline:
|
||||
raise TaskCenterError('target_inventory', 'collect component inventory before importing a BOM')
|
||||
by_key = {row.target.key: row for row in baseline}
|
||||
by_identity: dict[tuple[str, str], list[TargetPlanRow]] = {}
|
||||
for row in baseline:
|
||||
by_identity.setdefault((row.target.old_part_number.casefold(), row.target.refdes.casefold()), []).append(row)
|
||||
matched: dict[tuple[str, str, str, str], TargetPlanRow] = {}
|
||||
@dataclass(frozen=True)
|
||||
class BomRecord:
|
||||
project_path: str
|
||||
old: str
|
||||
new: str
|
||||
refs: tuple[str, ...]
|
||||
schematic: str
|
||||
sheet: str
|
||||
uid: str
|
||||
enabled: bool
|
||||
custom: str
|
||||
sync_nc: bool
|
||||
|
||||
|
||||
def read_bom_records(path: Path) -> tuple[BomRecord, ...]:
|
||||
workbook = None
|
||||
try:
|
||||
workbook = load_workbook(Path(path), read_only=True, data_only=False)
|
||||
@@ -70,41 +102,19 @@ def read_bom_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
|
||||
if not records:
|
||||
raise ValueError('BOM 工作表为空')
|
||||
headers = _normal_headers(tuple(cell.value for cell in records[0]))
|
||||
names = tuple(name for name in headers if name)
|
||||
if len(set(names)) != len(names):
|
||||
raise ValueError('BOM 列名重复')
|
||||
required = {'old_part_number', 'new_part_number', 'refdes'}
|
||||
if not required <= set(headers):
|
||||
raise ValueError('BOM 必须包含旧料号、新料号和位号列')
|
||||
positions = {name: index for index, name in enumerate(headers) if name}
|
||||
result = []
|
||||
for cells in records[1:]:
|
||||
values = tuple(cell.value for cell in cells)
|
||||
if not any(value not in (None, '') for value in values):
|
||||
continue
|
||||
if any(cell.data_type == 'f' for cell in cells):
|
||||
raise ValueError('BOM 不接受公式,请填写实际值')
|
||||
old = _text(values, positions, 'old_part_number')
|
||||
new = _text(values, positions, 'new_part_number')
|
||||
refs = _split_refdes(_text(values, positions, 'refdes'))
|
||||
if not old or not new or not refs:
|
||||
raise ValueError('BOM 行的旧料号、新料号和位号不能为空')
|
||||
enabled = _bool(_value(values, positions, 'enabled', True))
|
||||
sync_nc = _bool(_value(values, positions, 'sync_nc', True))
|
||||
custom = _text(values, positions, 'custom_value')
|
||||
schematic = _text(values, positions, 'schematic_name')
|
||||
sheet_number = _text(values, positions, 'sheet_number')
|
||||
uid = _text(values, positions, 'uid')
|
||||
for refdes in refs:
|
||||
candidates = [row for row in by_identity.get((old.casefold(), refdes.casefold()), ())
|
||||
if (not schematic or row.target.schematic_name.casefold() == schematic.casefold())
|
||||
and (not sheet_number or row.target.sheet_number.casefold() == sheet_number.casefold())
|
||||
and (not uid or row.target.uid == uid)]
|
||||
if len(candidates) != 1:
|
||||
raise ValueError(f'位号 {refdes} 无法唯一匹配当前采集清单')
|
||||
target = candidates[0].target
|
||||
if target.key in matched:
|
||||
raise ValueError(f'位号 {refdes} 在 BOM 中重复')
|
||||
matched[target.key] = TargetPlanRow(target, enabled, new, bool(custom), custom, sync_nc)
|
||||
result = tuple(matched.get(key, TargetPlanRow(row.target)) for key, row in by_key.items())
|
||||
compile_target_rules(result)
|
||||
return result
|
||||
record = parse_bom_row(cells, positions)
|
||||
if record is not None:
|
||||
result.append(record)
|
||||
return tuple(result)
|
||||
except (OSError, ValueError, TypeError, KeyError) as error:
|
||||
if isinstance(error, TaskCenterError):
|
||||
raise
|
||||
@@ -114,6 +124,86 @@ def read_bom_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def parse_bom_row(cells, positions):
|
||||
values = tuple(cell.value for cell in cells)
|
||||
if not any(value not in (None, '') for value in values):
|
||||
return None
|
||||
if any(cell.data_type == 'f' for cell in cells):
|
||||
raise ValueError('BOM 不接受公式,请填写实际值')
|
||||
old = _text(values, positions, 'old_part_number')
|
||||
new = _text(values, positions, 'new_part_number')
|
||||
refs = _split_refdes(_text(values, positions, 'refdes'))
|
||||
if not old and not new and not refs and not _text(values, positions, 'custom_value'):
|
||||
return None # An untouched project row is a scaffold, not a rule.
|
||||
if not old or not new or not refs:
|
||||
raise ValueError('BOM 行的旧料号、新料号和位号不能为空')
|
||||
enabled = _bool(_value(values, positions, 'enabled', True))
|
||||
sync_nc = _bool(_value(values, positions, 'sync_nc', True))
|
||||
custom = _text(values, positions, 'custom_value')
|
||||
schematic = _text(values, positions, 'schematic_name')
|
||||
sheet_number = _text(values, positions, 'sheet_number')
|
||||
uid = _text(values, positions, 'uid')
|
||||
project = _text(values, positions, 'project_path')
|
||||
if project and not Path(project).is_absolute():
|
||||
raise ValueError('工程路径必须使用模板中的完整路径')
|
||||
return BomRecord(project, old, new, refs, schematic, sheet_number, uid, enabled, custom, sync_nc)
|
||||
|
||||
|
||||
class BomMatcher:
|
||||
"""Index one immutable inventory once, then match independent Excel rows."""
|
||||
|
||||
def __init__(self, baseline):
|
||||
if not baseline:
|
||||
raise TaskCenterError('target_inventory', '未采集到可匹配的工程位号')
|
||||
self.by_key = {}
|
||||
self.projects = set()
|
||||
self.by_identity = {}
|
||||
self.identities = ProjectIdentityResolver()
|
||||
for row in baseline:
|
||||
target = row.target
|
||||
key = self.identities.target(target)
|
||||
if key in self.by_key:
|
||||
raise TaskCenterError('target_overlap', '采集清单存在重复位号身份')
|
||||
self.by_key[key] = row
|
||||
self.projects.add(key[0])
|
||||
self.by_identity.setdefault((target.old_part_number.casefold(), target.refdes.casefold()), []).append((key, target))
|
||||
|
||||
def match_record(self, record):
|
||||
if record.project_path and self.identities.project(record.project_path) not in self.projects:
|
||||
raise TaskCenterError('bom_import', 'BOM 工程与当前任务不一致')
|
||||
matched = {}
|
||||
for refdes in record.refs:
|
||||
candidates = [(key, target) for key, target in self.by_identity.get((record.old.casefold(), refdes.casefold()), ())
|
||||
if (not record.schematic or target.schematic_name.casefold() == record.schematic.casefold())
|
||||
and (not record.sheet or target.sheet_number.casefold() == record.sheet.casefold())
|
||||
and (not record.uid or target.uid == record.uid)]
|
||||
if len(candidates) != 1:
|
||||
raise TaskCenterError('bom_import', f'位号 {refdes} 无法唯一匹配当前采集清单')
|
||||
key, target = candidates[0]
|
||||
if key in matched:
|
||||
raise TaskCenterError('bom_import', f'位号 {refdes} 在 BOM 中重复')
|
||||
matched[key] = TargetPlanRow(target, record.enabled, record.new,
|
||||
bool(record.custom), record.custom, record.sync_nc)
|
||||
return matched
|
||||
|
||||
|
||||
def match_bom_records(baseline, records) -> tuple[TargetPlanRow, ...]:
|
||||
matcher = BomMatcher(baseline)
|
||||
matched = {}
|
||||
for record in records:
|
||||
incoming = matcher.match_record(record)
|
||||
if matched.keys() & incoming.keys():
|
||||
raise TaskCenterError('bom_import', '位号在 BOM 中重复')
|
||||
matched.update(incoming)
|
||||
result = tuple(matched.get(key, TargetPlanRow(row.target)) for key, row in matcher.by_key.items())
|
||||
compile_target_rules(result)
|
||||
return result
|
||||
|
||||
|
||||
def read_bom_plan(store, task_id: str, path: Path) -> tuple[TargetPlanRow, ...]:
|
||||
return match_bom_records(store.list_target_plan(task_id), read_bom_records(path))
|
||||
|
||||
|
||||
def _normal_headers(values):
|
||||
result = []
|
||||
for value in values:
|
||||
|
||||
@@ -66,3 +66,12 @@ def verify_application(app, binding=None, *, require_view=True):
|
||||
if not handle or window_pid(handle) != binding.pid:
|
||||
raise ValueError('CAD view PID does not match its owned session')
|
||||
return binding
|
||||
|
||||
|
||||
def project_file_path(app):
|
||||
"""COM type libraries expose this getter as either a property or a method."""
|
||||
value = app.GetProjectData().GetProjectFilePath
|
||||
value = value() if callable(value) else value
|
||||
if not isinstance(value, str):
|
||||
raise ValueError('CAD returned an invalid project path')
|
||||
return value
|
||||
@@ -7,7 +7,6 @@ from dataclasses import dataclass
|
||||
import json
|
||||
import math
|
||||
from types import MappingProxyType
|
||||
from typing import Any
|
||||
|
||||
from dx_productivity.part_replace.models import MappingRule
|
||||
|
||||
|
||||
@@ -15,9 +15,10 @@ import stat
|
||||
from threading import RLock
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .operation_control import check_cancelled
|
||||
|
||||
|
||||
def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
|
||||
def project_fingerprint(project: Path, excluded_root: Path, *, stop_event=None) -> tuple | None:
|
||||
try:
|
||||
project = Path(project).absolute()
|
||||
root = project.parent
|
||||
@@ -31,6 +32,7 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
|
||||
def fail(error):
|
||||
raise error
|
||||
for current, dirs, files in os.walk(root, onerror=fail, followlinks=False):
|
||||
check_cancelled(stop_event)
|
||||
current = Path(current)
|
||||
kept = []
|
||||
for name in sorted(dirs):
|
||||
@@ -38,7 +40,8 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
|
||||
relative = tuple(part.casefold() for part in path.relative_to(root).parts)
|
||||
audit_directory = (len(relative) == 3 and relative[:2] == ('database', 'cdbsvr')
|
||||
and relative[2] in {'log', 'plog', 'events'})
|
||||
if path.resolve() == excluded or name.casefold() == '.git' or audit_directory:
|
||||
backup_directory = relative == ('projectbackup', 'backups')
|
||||
if path.resolve() == excluded or name.casefold() == '.git' or audit_directory or backup_directory:
|
||||
continue
|
||||
info = path.lstat()
|
||||
if _unsafe(info):
|
||||
@@ -46,8 +49,10 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
|
||||
kept.append(name)
|
||||
dirs[:] = kept
|
||||
for name in sorted(files):
|
||||
check_cancelled(stop_event)
|
||||
path = current / name
|
||||
if path.suffix.casefold() == '.log':
|
||||
relative = tuple(part.casefold() for part in path.relative_to(root).parts)
|
||||
if path.suffix.casefold() == '.log' or relative == ('log files', 'projectbackuplog.txt'):
|
||||
continue
|
||||
info = path.lstat()
|
||||
if _unsafe(info) or not stat.S_ISREG(info.st_mode):
|
||||
@@ -60,7 +65,14 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
|
||||
# each source's full stamp against itself after hashing.
|
||||
if handle_before[:4] != before[:4]:
|
||||
return None
|
||||
digest = hashlib.file_digest(stream, 'sha256').digest()
|
||||
if stop_event is None:
|
||||
digest = hashlib.file_digest(stream, 'sha256').digest()
|
||||
else:
|
||||
digestor = hashlib.sha256()
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
check_cancelled(stop_event)
|
||||
digestor.update(chunk)
|
||||
digest = digestor.digest()
|
||||
if _file_stamp(os.fstat(stream.fileno())) != handle_before:
|
||||
return None
|
||||
# Check the path as well as the handle: atomic replacement can
|
||||
@@ -85,6 +97,28 @@ def _unsafe(info):
|
||||
getattr(info, 'st_file_attributes', 0) & getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400))
|
||||
|
||||
|
||||
def _without_runtime_database(stamp):
|
||||
if stamp is None or len(stamp) != 2:
|
||||
return None
|
||||
return (stamp[0], tuple(row for row in stamp[1]
|
||||
if row[0].replace('\\', '/').casefold() != 'database/icdb.dat'))
|
||||
|
||||
|
||||
def _only_database_changed(before, after):
|
||||
design = _without_runtime_database(before)
|
||||
return design is not None and before != after and design == _without_runtime_database(after)
|
||||
|
||||
|
||||
def _discovery_identity(discovery):
|
||||
sheets = discovery.sheets
|
||||
components = getattr(discovery, 'components', ())
|
||||
if len(set(sheets)) != len(sheets) or len({row.key for row in components}) != len(components):
|
||||
raise TaskCenterError('target_identity', '原生采集返回重复图页或位号身份,请核对工程')
|
||||
return (tuple(sorted(sheets)),
|
||||
tuple(sorted((sheet, tuple(sorted(parts))) for sheet, parts in discovery.matched_old_parts.items())),
|
||||
tuple(sorted((row.key, row.refdes, row.old_part_number, row.old_value) for row in components)))
|
||||
|
||||
|
||||
class DiscoveryCache:
|
||||
"""One preparer owns one cache; the lock also serializes cache discovery."""
|
||||
def __init__(self, data_root: Path, capacity: int = 32):
|
||||
@@ -97,38 +131,67 @@ class DiscoveryCache:
|
||||
with self.lock:
|
||||
self._entries.pop(_key(project), None)
|
||||
|
||||
def discover(self, project, parts, collect_components, loader):
|
||||
def discover(self, project, parts, collect_components, loader, *, stop_event=None):
|
||||
with self.lock:
|
||||
check_cancelled(stop_event)
|
||||
def fingerprint():
|
||||
check_cancelled(stop_event)
|
||||
return project_fingerprint(project, self.data_root, **({'stop_event': stop_event} if stop_event is not None else {}))
|
||||
key = _key(project)
|
||||
requested = frozenset(part.casefold() for part in parts)
|
||||
before = project_fingerprint(project, self.data_root)
|
||||
before = fingerprint()
|
||||
entry = self._entries.pop(key, None)
|
||||
if entry is not None:
|
||||
stamp, covered, has_components, discovery = entry
|
||||
if (before is not None and before == stamp and requested <= covered
|
||||
and (not collect_components or has_components)):
|
||||
self._entries[key] = entry
|
||||
check_cancelled(stop_event)
|
||||
return deepcopy(discovery)
|
||||
# Fingerprinting is an optimization: an initially unverifiable
|
||||
# project still gets fresh native discovery, with no cache reuse.
|
||||
if before is None:
|
||||
return loader()
|
||||
# Native first-open may normalize an old database. Discard that
|
||||
# discovery and reopen once; only a verified stable pass is usable.
|
||||
for attempt in range(2):
|
||||
if attempt:
|
||||
before = project_fingerprint(project, self.data_root)
|
||||
discovery = loader()
|
||||
after = project_fingerprint(project, self.data_root)
|
||||
check_cancelled(stop_event)
|
||||
_discovery_identity(discovery)
|
||||
return discovery
|
||||
# Native opens may update database session metadata on every read.
|
||||
# Accept that case only after two equal native results while every
|
||||
# other design file stays stable across both passes. The complete
|
||||
# final database hash still invalidates later cache reuse.
|
||||
previous = None
|
||||
previous_design = None
|
||||
attempt, limit = 0, 2
|
||||
while attempt < limit:
|
||||
if attempt:
|
||||
before = fingerprint()
|
||||
check_cancelled(stop_event)
|
||||
discovery = loader()
|
||||
check_cancelled(stop_event)
|
||||
identity = _discovery_identity(discovery)
|
||||
after = fingerprint()
|
||||
if before is not None and before == after:
|
||||
break
|
||||
if _only_database_changed(before, after):
|
||||
design = _without_runtime_database(after)
|
||||
if previous is not None and previous == identity and previous_design == design:
|
||||
break
|
||||
# First-open normalization can precede the two stable
|
||||
# inventory reads. Allow one extra pass only in that case.
|
||||
if attempt == 1 and previous is None:
|
||||
limit = 3
|
||||
previous, previous_design = identity, design
|
||||
else:
|
||||
previous = previous_design = None
|
||||
attempt += 1
|
||||
else:
|
||||
raise TaskCenterError("quick_run_sheet_discovery",
|
||||
"project contents changed or could not be verified during discovery; retry read-only discovery")
|
||||
# Refuse incomplete inventories and bound both projects and row count.
|
||||
sheets = getattr(discovery, 'sheets', ())
|
||||
matches = getattr(discovery, 'matched_old_parts', {})
|
||||
if (before is not None and before == after and sheets
|
||||
check_cancelled(stop_event)
|
||||
if (after is not None and sheets
|
||||
and set(sheets) == set(matches)
|
||||
and (len(getattr(discovery, 'components', ())) + len(sheets)
|
||||
+ sum(len(parts) for parts in matches.values())) <= 100000):
|
||||
|
||||
@@ -41,7 +41,11 @@ def read_component_inventory(path: Path, project_path: Path,
|
||||
|
||||
|
||||
def collect_target_inventory(preparer, project_path: Path,
|
||||
old_part_numbers: tuple[str, ...]) -> tuple[ComponentTarget, ...]:
|
||||
old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None) -> tuple[ComponentTarget, ...]:
|
||||
if not old_part_numbers:
|
||||
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
|
||||
return preparer.collect_inventory(project_path, old_part_numbers)
|
||||
from .operation_control import check_cancelled, control_options
|
||||
check_cancelled(stop_event)
|
||||
rows = preparer.collect_inventory(project_path, old_part_numbers, **control_options(stop_event, on_progress))
|
||||
check_cancelled(stop_event)
|
||||
return rows
|
||||
@@ -8,7 +8,7 @@ import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .cad_identity import CadBinding, current_desktop_name, verify_application
|
||||
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
|
||||
@@ -65,7 +65,7 @@ def _designer_executable():
|
||||
class IsolatedCadSession:
|
||||
"""The supervisor never attaches to COM on the user's input desktop."""
|
||||
def __init__(self, root, *, abort_event=None):
|
||||
self.root = Path(root)
|
||||
self.root = Path(root).resolve()
|
||||
self.token = uuid4().hex
|
||||
self.desktop = PrivateDesktop('dx-' + self.token, enabled=True)
|
||||
self.cad = None
|
||||
@@ -101,7 +101,7 @@ class IsolatedCadSession:
|
||||
probe = self.desktop.start_process(_helper_command('probe', bootstrap, self.cad.pid), env=_child_environment(environment),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
deadline = time.monotonic() + 75
|
||||
deadline = time.monotonic() + 120
|
||||
while probe.poll() is None:
|
||||
self._check_abort()
|
||||
if time.monotonic() >= deadline:
|
||||
@@ -175,11 +175,12 @@ class IsolatedCadSession:
|
||||
self._record(state='uncertain', error=message)
|
||||
|
||||
|
||||
def run_isolated_process(command, timeout, *, abort_event=None):
|
||||
def run_isolated_process(command, timeout, *, abort_event=None, cooperative_abort=False):
|
||||
from .worker_monitor import run_monitored_process
|
||||
try:
|
||||
with IsolatedCadSession(Path(command[3]), abort_event=abort_event) as session:
|
||||
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker)
|
||||
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker,
|
||||
**({'cooperative_abort': True} if cooperative_abort else {}))
|
||||
except PrivateCadStartupError as error:
|
||||
# The existing handoff recognizes exit=2 with unchanged status as a
|
||||
# retryable pre-mutation startup failure, without an uncertainty lock.
|
||||
@@ -188,6 +189,20 @@ def run_isolated_process(command, timeout, *, abort_event=None):
|
||||
|
||||
def native_action(action, evidence, expected_pid):
|
||||
"""Runs in a child created with lpDesktop, never in a Python thread switch."""
|
||||
if action != 'probe':
|
||||
return _native_action(action, evidence, expected_pid)
|
||||
# COM startup can block inside a native call, so keep diagnostics outside
|
||||
# the redirected pipes and retain them when the supervisor ends the child.
|
||||
import faulthandler
|
||||
with Path(str(evidence) + '.fault.txt').open('a', encoding='utf-8') as trace:
|
||||
faulthandler.dump_traceback_later(20, repeat=True, file=trace)
|
||||
try:
|
||||
return _native_action(action, evidence, expected_pid)
|
||||
finally:
|
||||
faulthandler.cancel_dump_traceback_later()
|
||||
|
||||
|
||||
def _native_action(action, evidence, expected_pid):
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
import win32gui
|
||||
@@ -226,7 +241,7 @@ def native_action(action, evidence, expected_pid):
|
||||
# ActiveViewHandle can retain a destroyed/reused HWND after closing
|
||||
# the last project. The private ROT/GUID binds this empty instance.
|
||||
verify_application(app, binding, require_view=False)
|
||||
if app.GetProjectData().GetProjectFilePath():
|
||||
if project_file_path(app):
|
||||
raise ValueError('owned CAD still has a project open; no implicit save or discard')
|
||||
app.Quit()
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Short access paths for legacy WSH without relocating task evidence."""
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import ctypes
|
||||
import csv
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from threading import RLock
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
def _short_path(path: Path) -> str | None:
|
||||
function = ctypes.WinDLL('kernel32', use_last_error=True).GetShortPathNameW
|
||||
function.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint]
|
||||
function.restype = ctypes.c_uint
|
||||
buffer = ctypes.create_unicode_buffer(32768)
|
||||
count = function(str(path), buffer, len(buffer))
|
||||
return buffer.value if count and count < len(buffer) else None
|
||||
|
||||
|
||||
def _fits(root) -> bool:
|
||||
# Leave room for snapshot/job suffixes and monitor handshakes.
|
||||
return len(str(root)) + 100 < 260
|
||||
|
||||
|
||||
class _AliasPool:
|
||||
def __init__(self):
|
||||
self.directory = None
|
||||
self.links = {}
|
||||
self.lock = RLock()
|
||||
|
||||
def alias(self, root: Path) -> Path:
|
||||
import _winapi
|
||||
with self.lock:
|
||||
if self.directory is None:
|
||||
local = Path(os.environ.get('LOCALAPPDATA') or tempfile.gettempdir())
|
||||
parent = local / 'DxProductivity' / 'path-links'
|
||||
parent.mkdir(parents=True, exist_ok=True)
|
||||
self.directory = Path(tempfile.mkdtemp(prefix='dxp-', dir=parent))
|
||||
key = hashlib.sha256(os.path.normcase(str(root)).encode('utf-8')).hexdigest()[:20]
|
||||
link = self.directory / key
|
||||
if not _fits(link):
|
||||
raise OSError('the per-user compatibility directory is also too long')
|
||||
if link not in self.links:
|
||||
# Junction creation needs no symbolic-link privilege. The
|
||||
# junction contains no copies and never changes the target.
|
||||
_winapi.CreateJunction(str(root), str(link))
|
||||
self.links[link] = root
|
||||
if not link.is_junction() or link.resolve(strict=True) != root:
|
||||
raise OSError('compatibility directory no longer points to the confirmed evidence')
|
||||
return link
|
||||
|
||||
def close(self):
|
||||
errors = []
|
||||
with self.lock:
|
||||
for link, target in tuple(self.links.items()):
|
||||
try:
|
||||
if link.is_junction():
|
||||
if link.resolve() != target:
|
||||
raise OSError('refusing to remove a redirected compatibility directory')
|
||||
link.rmdir() # Remove only the link, never the target tree.
|
||||
elif link.exists():
|
||||
raise OSError('refusing to remove a non-junction compatibility directory')
|
||||
del self.links[link]
|
||||
except OSError as error:
|
||||
errors.append(error)
|
||||
if self.directory is not None and not self.links:
|
||||
try:
|
||||
self.directory.rmdir()
|
||||
self.directory = None
|
||||
except OSError as error:
|
||||
errors.append(error)
|
||||
return errors
|
||||
|
||||
|
||||
_aliases = _AliasPool()
|
||||
|
||||
|
||||
def cleanup_worker_aliases():
|
||||
return _aliases.close()
|
||||
|
||||
|
||||
atexit.register(cleanup_worker_aliases)
|
||||
|
||||
|
||||
def worker_paths(script: Path, root: Path) -> tuple[str, str]:
|
||||
if os.name == 'nt':
|
||||
_prepare_project_access(root)
|
||||
if os.name != 'nt' or _fits(root):
|
||||
return str(script), str(root)
|
||||
canonical = root.resolve(strict=True)
|
||||
short = _short_path(canonical)
|
||||
if short and _fits(short):
|
||||
return str(Path(short) / script.name), short
|
||||
try:
|
||||
alias = _aliases.alias(canonical)
|
||||
except OSError as error:
|
||||
raise TaskCenterError('quick_run_path_length',
|
||||
f'无法建立长路径兼容入口:{error};尚未启动 CAD 操作。') from error
|
||||
return str(alias / script.name), str(alias)
|
||||
|
||||
|
||||
def _prepare_project_access(root: Path):
|
||||
"""Keep command identities canonical while giving legacy CAD short entry paths."""
|
||||
command = root / 'command.tsv'
|
||||
if not command.is_file():
|
||||
return
|
||||
rows = []
|
||||
with command.open(encoding='utf-8-sig', newline='') as stream:
|
||||
for row in csv.DictReader(stream, delimiter='\t'):
|
||||
value = row.get('project_path')
|
||||
if not value:
|
||||
continue
|
||||
project = Path(value).resolve(strict=False)
|
||||
if (_fits(project.parent) and len(str(project)) < 260) or not project.is_file():
|
||||
continue
|
||||
short = _short_path(project)
|
||||
if short and _fits(Path(short).parent) and len(short) < 260:
|
||||
access = Path(short)
|
||||
else:
|
||||
access = _aliases.alias(project.parent) / project.name
|
||||
if not _fits(access.parent) or len(str(access)) >= 260 or access.resolve(strict=True) != project:
|
||||
raise TaskCenterError('quick_run_path_length', '工程短路径入口不能与原工程身份对应,未启动 CAD 操作。')
|
||||
pair = (str(project), str(access))
|
||||
if pair not in rows:
|
||||
rows.append(pair)
|
||||
target = root / 'project-access.tsv'
|
||||
if rows or target.exists():
|
||||
temporary = target.with_suffix('.tmp')
|
||||
with temporary.open('w', encoding='utf-8', newline='') as stream:
|
||||
writer = csv.writer(stream, delimiter='\t', lineterminator='\n')
|
||||
writer.writerow(('project_path', 'access_path'))
|
||||
writer.writerows(rows)
|
||||
temporary.replace(target)
|
||||
|
||||
|
||||
def validate_project_access(root: Path):
|
||||
"""Reject disappeared/redirected entry paths before and after a native worker."""
|
||||
target = Path(root) / 'project-access.tsv'
|
||||
if not target.is_file():
|
||||
return
|
||||
with target.open(encoding='utf-8-sig', newline='') as stream:
|
||||
reader = csv.DictReader(stream, delimiter='\t')
|
||||
if reader.fieldnames != ['project_path', 'access_path']:
|
||||
raise TaskCenterError('target_identity', '工程路径入口清单格式已改变')
|
||||
for row in reader:
|
||||
try:
|
||||
same = Path(row['access_path']).resolve(strict=True) == Path(row['project_path']).resolve(strict=True)
|
||||
except (OSError, ValueError, KeyError):
|
||||
same = False
|
||||
if not same:
|
||||
raise TaskCenterError('target_identity', '工程短路径入口已失效或指向其他工程,拒绝使用采集或替换结果')
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
@@ -47,6 +48,7 @@ class LoggingContext:
|
||||
application_log_path: Path
|
||||
logger: logging.Logger
|
||||
_event_lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
|
||||
_event_sequences: OrderedDict = field(default_factory=OrderedDict, repr=False)
|
||||
|
||||
def report_exception(
|
||||
self,
|
||||
@@ -128,7 +130,11 @@ def append_task_event(
|
||||
raise TaskCenterError("event_details", "task event details must be JSON-compatible") from error
|
||||
path = task_directory / "events.jsonl"
|
||||
with context._event_lock:
|
||||
sequence = _next_event_sequence(path)
|
||||
# Reuse only a sequence belonging to this exact, unchanged file. External
|
||||
# appends, rotation, truncation and replacement fall back to the disk tail.
|
||||
cached = context._event_sequences.pop(path, None)
|
||||
stamp = _event_file_stamp(path)
|
||||
sequence = cached[1] if cached is not None and stamp is not None and cached[0] == stamp else _next_event_sequence(path)
|
||||
event = {
|
||||
"sequence": sequence,
|
||||
"timestamp_utc": _utc_now_text(),
|
||||
@@ -153,6 +159,14 @@ def append_task_event(
|
||||
handle.write(encoded)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
written = os.fstat(handle.fileno())
|
||||
final = _event_file_stamp(path)
|
||||
# Windows fstat/Path.stat differ in ctime semantics; retain the full
|
||||
# Path stamp only after handle identity, size and mtime agree.
|
||||
if final is not None and final[:4] == (written.st_dev, written.st_ino, written.st_size, written.st_mtime_ns):
|
||||
context._event_sequences[path] = (final, sequence + 1)
|
||||
while len(context._event_sequences) > 64:
|
||||
context._event_sequences.popitem(last=False)
|
||||
except OSError as error:
|
||||
raise TaskCenterError("event_write_failed", "cannot append task event") from error
|
||||
context.logger.log(
|
||||
@@ -167,6 +181,14 @@ def append_task_event(
|
||||
return event
|
||||
|
||||
|
||||
def _event_file_stamp(path):
|
||||
try:
|
||||
info = path.stat()
|
||||
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def capture_subprocess_output(
|
||||
context: LoggingContext,
|
||||
*,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Native current-sheet replacement adapter for the existing QuickPartReplace runner."""
|
||||
import argparse
|
||||
import faulthandler
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
@@ -205,7 +206,7 @@ def attach():
|
||||
api = win32com.client.gencache.EnsureModule(
|
||||
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
|
||||
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
|
||||
from .cad_identity import verify_application
|
||||
from .cad_identity import verify_application, project_file_path
|
||||
verify_application(app)
|
||||
return app, api
|
||||
|
||||
@@ -228,9 +229,9 @@ def components_on_sheet(app, api):
|
||||
|
||||
|
||||
def check_active_context(app, metadata):
|
||||
from .cad_identity import verify_application
|
||||
from .cad_identity import verify_application, project_file_path
|
||||
verify_application(app)
|
||||
if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])):
|
||||
if Path(project_file_path(app)).resolve() != Path(metadata[1]).resolve():
|
||||
raise ValueError("Active project changed")
|
||||
if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]:
|
||||
raise ValueError("Active sheet changed")
|
||||
@@ -333,14 +334,21 @@ def existing_replacement_uids(components, records, target, binding, require_part
|
||||
return matches
|
||||
|
||||
|
||||
def promote_pin_numbers(app, api, replacement_uids, slot_count=1):
|
||||
def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=None):
|
||||
def progress(phase):
|
||||
if on_progress:
|
||||
on_progress(phase)
|
||||
progress('query_components')
|
||||
components = components_on_sheet(app, api)
|
||||
replacement_uids = set(replacement_uids)
|
||||
try:
|
||||
progress('select_replacements')
|
||||
for component in components:
|
||||
selection(component, str(component.UID) in replacement_uids)
|
||||
for slot in range(1, int(slot_count) + 1):
|
||||
progress(f'promote_slot_{slot}')
|
||||
app.ActiveView.Block.PromoteSymbolNumbers(1, slot)
|
||||
progress('query_promoted_pins')
|
||||
promoted = []
|
||||
for item in app.ActiveView.Query(4096, 0):
|
||||
pin = api.IVdCmpPin(item._oleobj_)
|
||||
@@ -352,8 +360,15 @@ def promote_pin_numbers(app, api, replacement_uids, slot_count=1):
|
||||
raise ValueError("Replacement produced no pins")
|
||||
return promoted
|
||||
finally:
|
||||
progress('deselect_components')
|
||||
for component in components:
|
||||
selection(component, False)
|
||||
progress('promotion_complete')
|
||||
|
||||
|
||||
def _promotion_phase(snapshot, report, phase):
|
||||
report['pin_promotion_phase'] = phase
|
||||
save_report(snapshot, report)
|
||||
|
||||
|
||||
def replacement_matches(components, records, target, require_part_label):
|
||||
@@ -420,7 +435,8 @@ def run_native(snapshot, report):
|
||||
slot_count = int(binding.get("slot_count", report.get("slot_count", 1)))
|
||||
if slot_count < 1:
|
||||
raise ValueError("Recorded replacement has no valid slots")
|
||||
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count)
|
||||
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count,
|
||||
lambda phase: _promotion_phase(snapshot, report, phase))
|
||||
report["already_replaced"] = True
|
||||
report["stage"] = "native_replace_verified"
|
||||
return
|
||||
@@ -617,7 +633,8 @@ def run_native(snapshot, report):
|
||||
save_report(snapshot, report)
|
||||
report["stage"] = "pin_promotion_started"
|
||||
save_report(snapshot, report)
|
||||
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count)
|
||||
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count,
|
||||
lambda phase: _promotion_phase(snapshot, report, phase))
|
||||
report["stage"] = "native_replace_verified"
|
||||
finally:
|
||||
if dialog and win32gui.IsWindow(dialog):
|
||||
@@ -644,13 +661,23 @@ def atomic_text(path, text):
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
os.replace(temporary, path)
|
||||
break
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.02)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def run(snapshot):
|
||||
snapshot = Path(snapshot)
|
||||
fault_stream = Path(str(snapshot) + '.native.fault.txt').open('a', encoding='utf-8')
|
||||
faulthandler.enable(file=fault_stream, all_threads=True)
|
||||
report_path = Path(str(snapshot) + ".native.json")
|
||||
report = {}
|
||||
if report_path.is_file():
|
||||
@@ -681,7 +708,15 @@ def run(snapshot):
|
||||
return 1
|
||||
finally:
|
||||
watchdog.cancel()
|
||||
save_report(snapshot, report)
|
||||
try:
|
||||
save_report(snapshot, report)
|
||||
except Exception:
|
||||
traceback.print_exc(file=fault_stream)
|
||||
fault_stream.flush()
|
||||
raise
|
||||
finally:
|
||||
faulthandler.disable()
|
||||
fault_stream.close()
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Explicit completed-round archival; previous handoffs never become resumable."""
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .models import ProjectStatus, TaskStatus
|
||||
from .target_plan import compile_target_rules
|
||||
|
||||
|
||||
def _write(path, value):
|
||||
temporary = path.with_name(f'.{path.name}.{uuid4().hex}.tmp')
|
||||
try:
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, default=str), encoding='utf-8')
|
||||
with temporary.open('r+b') as stream:
|
||||
os.fsync(stream.fileno())
|
||||
temporary.replace(path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def recover_archives(service):
|
||||
"""Recover a process exit between atomic directory moves and the DB commit."""
|
||||
for journal in (service._logging.root / 'round-transitions').glob('*/journal.json'):
|
||||
if (journal.parent / 'committed').exists() or (journal.parent / 'rolled-back').exists():
|
||||
continue
|
||||
value = json.loads(journal.read_text(encoding='utf-8'))
|
||||
committed = service._store.round_committed(journal.parent.name)
|
||||
if committed:
|
||||
(journal.parent / 'committed').touch()
|
||||
continue
|
||||
# The database transaction is atomic, so an uncommitted journal restores
|
||||
# the original current handoff. Never merge or overwrite newer files.
|
||||
for source, destination in reversed(value['moves']):
|
||||
source, destination = Path(source), Path(destination)
|
||||
if destination.exists():
|
||||
if source.exists():
|
||||
raise TaskCenterError('round_recovery', '新一轮归档恢复发生目录冲突,请保留证据并检查归档日志。')
|
||||
destination.rename(source)
|
||||
(journal.parent / 'rolled-back').touch()
|
||||
|
||||
|
||||
def start_new_round(service, task_id):
|
||||
recover_archives(service)
|
||||
transition = {}
|
||||
try:
|
||||
# Include the actual COMMIT boundary, not only the SQL/reset body.
|
||||
with service._store.transaction():
|
||||
tasks, journal_root = _stage_new_round(service, task_id, transition)
|
||||
except BaseException:
|
||||
if transition:
|
||||
_restore_moves(transition['moves'])
|
||||
(transition['journal_root'] / 'rolled-back').touch()
|
||||
raise
|
||||
(journal_root / 'committed').touch()
|
||||
return tasks
|
||||
|
||||
|
||||
def _restore_moves(moves):
|
||||
for source, destination in reversed(moves):
|
||||
source, destination = Path(source), Path(destination)
|
||||
if destination.exists():
|
||||
if source.exists():
|
||||
raise TaskCenterError('round_recovery', '归档回滚目录冲突,请保留证据并检查日志。')
|
||||
destination.rename(source)
|
||||
|
||||
|
||||
def _stage_new_round(service, task_id, transition):
|
||||
store = service._store
|
||||
with store.transaction():
|
||||
task = store.get_task(task_id)
|
||||
if task.status is not TaskStatus.COMPLETED:
|
||||
raise TaskCenterError('new_round_state', '只有已完成任务可以开始新一轮;当前轮次不会重复重置。')
|
||||
if store.has_active_project():
|
||||
raise TaskCenterError('active_project_exists', '请先完成当前活动工程。')
|
||||
members = (tuple(t for t in store.list_project_group(task.group_id) if t.status is not TaskStatus.DELETED)
|
||||
if task.group_id else (task,))
|
||||
completed = tuple(t for t in members if t.status is TaskStatus.COMPLETED)
|
||||
for member in members:
|
||||
facade = service._project_task_service(member.task_id)
|
||||
root = facade._quick_run_preparer.data_root / 'quick-run'
|
||||
rules = (compile_target_rules(store.list_target_plan(member.task_id))
|
||||
if member.target_plan_mode else store.list_rules(member.task_id))
|
||||
snapshot = facade._quick_run_preparer.read_snapshot(member.task_id,
|
||||
store.list_projects(member.task_id), rules,
|
||||
copy_part_number_to_value=member.copy_part_number_to_value)
|
||||
if snapshot.interrupted or (root / 'uncertain.flag').exists():
|
||||
raise TaskCenterError('new_round_interrupted', '同批任务有中断或不确定结果,请先核验恢复。')
|
||||
if member.status is not TaskStatus.COMPLETED:
|
||||
if member.status not in {TaskStatus.DRAFT, TaskStatus.READY} or snapshot.has_evidence:
|
||||
raise TaskCenterError('new_round_batch_active', '同批任务仍有执行记录,请先完成或核验;未执行的草稿可以保留。')
|
||||
continue
|
||||
selected = tuple(p for p in store.list_projects(member.task_id) if p.selected)
|
||||
if not selected or any(p.status is not ProjectStatus.COMPLETED for p in selected):
|
||||
raise TaskCenterError('new_round_unverified', '工程尚未全部校验完成,不能开始新一轮。')
|
||||
if snapshot.has_evidence and (not snapshot.progress.queue_complete or snapshot.progress.failed_items):
|
||||
raise TaskCenterError('new_round_unverified', '替换队列尚未校验完成,不能开始新一轮。')
|
||||
round_id = uuid4().hex
|
||||
summary = f'new round {round_id}: collect current inventory before execution'
|
||||
journal_root = service._logging.root / 'round-transitions' / round_id
|
||||
journal_root.mkdir(parents=True)
|
||||
moves, archives = [], []
|
||||
for member in completed:
|
||||
root = service._project_task_service(member.task_id)._quick_run_preparer.data_root
|
||||
archive = root / 'rounds' / round_id
|
||||
archive.mkdir(parents=True)
|
||||
archives.append(archive)
|
||||
_write(archive / 'plan.json', dict(task=asdict(member),
|
||||
projects=[asdict(p) for p in store.list_projects(member.task_id)],
|
||||
rules=[asdict(r) for r in store.list_rules(member.task_id)],
|
||||
targets=[asdict(r) for r in store.list_target_plan(member.task_id)]))
|
||||
for name in ('quick-run', 'quick-run-history'):
|
||||
if (root / name).exists():
|
||||
moves.append((str(root / name), str(archive / name)))
|
||||
_write(journal_root / 'journal.json', dict(task_ids=[t.task_id for t in completed],
|
||||
summary=summary, moves=moves, archives=[str(path) for path in archives]))
|
||||
transition.update(moves=moves, journal_root=journal_root)
|
||||
for source, destination in moves:
|
||||
Path(source).rename(destination)
|
||||
for member in completed:
|
||||
store.reset_completed_round(member.task_id, summary)
|
||||
store.record_round_commit(round_id)
|
||||
return tuple(store.get_task(t.task_id) for t in completed), journal_root
|
||||
|
||||
|
||||
def latest_archive(preparer):
|
||||
plans = tuple((preparer.data_root / 'rounds').glob('*/plan.json'))
|
||||
return max(plans, key=lambda path: path.stat().st_mtime_ns).parent if plans else None
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Cooperative read-only operation control, independent of Qt and CAD."""
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
def check_cancelled(stop_event):
|
||||
if stop_event is not None and stop_event.is_set():
|
||||
raise TaskCenterError('operation_cancelled', '已取消采集;当前私有 CAD 会话已安全收尾,未保存部分计划。')
|
||||
|
||||
|
||||
def control_options(stop_event=None, on_progress=None):
|
||||
return {key: value for key, value in (('stop_event', stop_event), ('on_progress', on_progress)) if value is not None}
|
||||
|
||||
|
||||
def report_progress(on_progress, message):
|
||||
if on_progress is not None:
|
||||
on_progress(message)
|
||||
@@ -10,6 +10,7 @@ from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .quick_run_protocol import ProjectDiscovery, _encode_vbs_field
|
||||
from .operation_control import check_cancelled, report_progress
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -33,8 +34,11 @@ def discover_project(
|
||||
script_source: Path,
|
||||
runtime: DiscoveryRuntime,
|
||||
collect_components: bool = False,
|
||||
stop_event=None,
|
||||
on_progress=None,
|
||||
) -> ProjectDiscovery:
|
||||
"""Enumerate sheets and requested source parts while the owned project is open."""
|
||||
check_cancelled(stop_event)
|
||||
project = project_path.resolve(strict=True)
|
||||
token = uuid4().hex
|
||||
job_id = "discover_" + token
|
||||
@@ -74,12 +78,19 @@ def discover_project(
|
||||
job_id,
|
||||
)
|
||||
try:
|
||||
report_progress(on_progress, f'正在启动工程读取会话:{project.name}')
|
||||
check_cancelled(stop_event)
|
||||
completed = runtime.process_runner(command, runtime.timeout)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
_require_released_reader(root)
|
||||
check_cancelled(stop_event)
|
||||
raise TaskCenterError(
|
||||
"quick_run_sheet_discovery",
|
||||
f"枚举工程图页时执行器未能安全结束:{project};{error}",
|
||||
) from error
|
||||
_require_released_reader(root)
|
||||
check_cancelled(stop_event)
|
||||
report_progress(on_progress, f'读取会话已结束,正在核对位号清单:{project.name}')
|
||||
(root / "worker-output.txt").write_text(completed.stdout + "\n" + completed.stderr, encoding="utf-8")
|
||||
if completed.returncode != 0:
|
||||
detail = completed.stderr.strip() or completed.stdout.strip() or "sheet discovery failed"
|
||||
@@ -91,5 +102,11 @@ def discover_project(
|
||||
components = read_component_inventory(root / "components.tsv", project, sheets)
|
||||
else:
|
||||
components = ()
|
||||
check_cancelled(stop_event)
|
||||
return ProjectDiscovery(sheets, matches, components)
|
||||
|
||||
|
||||
def _require_released_reader(root):
|
||||
if (root / 'uncertain.flag').exists():
|
||||
raise TaskCenterError('inventory_cleanup', f'采集会话未能正常收尾,请检查诊断记录后重试:{root}')
|
||||
|
||||
@@ -22,7 +22,7 @@ class ProjectSessionWorker:
|
||||
A separate monitor thread retains the existing idle watchdog and worker job.
|
||||
"""
|
||||
def __init__(self, project: Path, root: Path, *, private_desktop=False):
|
||||
self.project, self.root = Path(project), Path(root)
|
||||
self.project, self.root = Path(project), Path(root).resolve()
|
||||
self.token = uuid4().hex
|
||||
self._done, self._abort = Event(), Event()
|
||||
self._thread = None
|
||||
|
||||
@@ -14,6 +14,7 @@ import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from typing import Protocol
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -489,6 +490,12 @@ class QuickRunPreparer:
|
||||
_write_uncertain_flag(uncertain_path, "worker_exited_before_native_completion")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain worker_exited_before_native_completion")
|
||||
raise TaskCenterError("quick_run_uncertain", "执行器已退出,但未返回替换收尾结果;请核验恢复,不要重复替换。")
|
||||
from .quick_run_snapshot import failed_native_result_uncertain
|
||||
if state == BATCH_FAILED_STATE and failed_native_result_uncertain(
|
||||
handoff.command_path.parent, commands, after):
|
||||
_write_uncertain_flag(uncertain_path, "native_batch_failed_after_mutation")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain native_batch_failed_after_mutation")
|
||||
raise TaskCenterError("quick_run_uncertain", "原生修改后未完成核验,队列已停止;请先核验恢复,不要直接重试。")
|
||||
if state == BATCH_SAVED_UNVERIFIED_STATE:
|
||||
_write_uncertain_flag(uncertain_path, "saved_readback_unverified")
|
||||
if state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE} and (not batch_mode or batch_session is None):
|
||||
@@ -668,22 +675,33 @@ class QuickRunPreparer:
|
||||
self._discovery_cache.invalidate(project_path)
|
||||
|
||||
def discover_project(self, project_path: Path, old_part_numbers: tuple[str, ...], *,
|
||||
collect_components: bool = False) -> ProjectDiscovery:
|
||||
collect_components: bool = False, stop_event=None, on_progress=None) -> ProjectDiscovery:
|
||||
from .operation_control import check_cancelled, control_options, report_progress
|
||||
check_cancelled(stop_event)
|
||||
controls = control_options(stop_event, on_progress)
|
||||
attempt = 0
|
||||
def load():
|
||||
nonlocal attempt
|
||||
attempt += 1
|
||||
check_cancelled(stop_event)
|
||||
report_progress(on_progress, f'正在读取工程 {project_path.name}(第 {attempt} 次核对),请等待当前会话安全收尾…')
|
||||
check_cancelled(stop_event)
|
||||
if collect_components:
|
||||
return self._discover_project_sheets(project_path, old_part_numbers,
|
||||
collect_components=True)
|
||||
return self._discover_project_sheets(project_path, old_part_numbers)
|
||||
collect_components=True, **controls)
|
||||
return self._discover_project_sheets(project_path, old_part_numbers, **controls)
|
||||
return self._discovery_cache.discover(
|
||||
Path(project_path), old_part_numbers, collect_components, load)
|
||||
Path(project_path), old_part_numbers, collect_components, load,
|
||||
**({'stop_event': stop_event} if stop_event is not None else {}))
|
||||
|
||||
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...]) -> tuple:
|
||||
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None) -> tuple:
|
||||
"""Collect validated component targets, retaining reusable sheet evidence."""
|
||||
if not old_part_numbers:
|
||||
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
|
||||
requested = {part.casefold() for part in old_part_numbers}
|
||||
from .operation_control import control_options
|
||||
return tuple(component for component in self.discover_project(
|
||||
project_path, old_part_numbers, collect_components=True).components
|
||||
project_path, old_part_numbers, collect_components=True, **control_options(stop_event, on_progress)).components
|
||||
if component.old_part_number.casefold() in requested)
|
||||
|
||||
def _discover_project_sheets(
|
||||
@@ -692,15 +710,24 @@ class QuickRunPreparer:
|
||||
old_part_numbers: tuple[str, ...],
|
||||
*,
|
||||
collect_components: bool = False,
|
||||
stop_event=None,
|
||||
on_progress=None,
|
||||
) -> _ProjectDiscovery:
|
||||
"""Enumerate sheets and requested source parts while the owned project is open."""
|
||||
from .project_discovery import DiscoveryRuntime, discover_project
|
||||
from .operation_control import control_options
|
||||
|
||||
process_runner = self._process_runner
|
||||
if stop_event is not None and process_runner is _run_process:
|
||||
def process_runner(command, timeout):
|
||||
return _run_process(command, timeout, abort_event=stop_event)
|
||||
|
||||
return discover_project(project_path, old_part_numbers,
|
||||
data_root=self._data_root, script_source=self._required_script_source(),
|
||||
collect_components=collect_components,
|
||||
**control_options(stop_event, on_progress),
|
||||
runtime=DiscoveryRuntime(
|
||||
self._process_runner, self._cscript_resolver, _vbs_worker_paths,
|
||||
process_runner, self._cscript_resolver, _vbs_worker_paths,
|
||||
_native_helper_launch_arguments, _session_failure_message,
|
||||
_read_discovered_sheets, _read_discovery_inventory,
|
||||
IDLE_PROGRESS_TIMEOUT_SECONDS))
|
||||
@@ -914,7 +941,7 @@ def _advance_batch_session(
|
||||
|
||||
|
||||
def _is_saved_result(state: str, code: str) -> bool:
|
||||
return state == "saved_ok" or (state == "restored_ok" and code == "recovery_verified")
|
||||
return state == "saved_ok" or (state == "restored_ok" and code in {"recovery_verified", "recovery_saved_verified"})
|
||||
|
||||
|
||||
def _failure_details(
|
||||
@@ -1070,7 +1097,7 @@ def _queue_has_mutation_evidence(root: Path) -> bool:
|
||||
report = json.loads(report_path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
return True
|
||||
if report.get("ok") is True or report.get("stage") in {"native_replace_started", "native_replace_verified"}:
|
||||
if report.get("ok") is True or report.get("stage") in {"native_replace_started", "native_replace_applied", "pin_promotion_started", "native_replace_verified"}:
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -1433,12 +1460,23 @@ def _read_status_details(path: Path) -> tuple[tuple[str, str, str, str], ...]:
|
||||
return tuple(entries)
|
||||
|
||||
|
||||
def _open_status_for_read(path: Path):
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
return path.open('rb')
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.02)
|
||||
|
||||
|
||||
def _read_appended_status_details(
|
||||
session: QuickRunBatchSession,
|
||||
) -> tuple[tuple[tuple[str, str, str, str], ...], int, tuple[int, int], tuple[int, int, int, int, int]]:
|
||||
path = session.handoff.status_path
|
||||
try:
|
||||
with path.open("rb") as handle:
|
||||
with _open_status_for_read(path) as handle:
|
||||
current = os.fstat(handle.fileno())
|
||||
identity = _file_identity(current)
|
||||
if identity != session.status_identity or current.st_size < session.status_offset:
|
||||
@@ -1585,7 +1623,15 @@ def _write_atomic_queue_text(path: Path, text: str, code: str, message: str) ->
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
os.replace(temporary, path)
|
||||
break
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.02)
|
||||
except OSError as error:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise TaskCenterError(code, message) from error
|
||||
@@ -1659,18 +1705,8 @@ def _next_unfinished_command(
|
||||
|
||||
def _vbs_worker_paths(script: Path, root: Path) -> tuple[str, str]:
|
||||
"""FSO cannot see some paths beyond MAX_PATH, including monitor handshakes."""
|
||||
if os.name != 'nt' or len(str(root)) + 100 < 260:
|
||||
return str(script), str(root)
|
||||
import ctypes
|
||||
get_short_path = ctypes.WinDLL('kernel32', use_last_error=True).GetShortPathNameW
|
||||
get_short_path.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint]
|
||||
get_short_path.restype = ctypes.c_uint
|
||||
buffer = ctypes.create_unicode_buffer(32768)
|
||||
count = get_short_path(str(root.resolve(strict=True)), buffer, len(buffer))
|
||||
if not count or count >= len(buffer) or len(buffer.value) + 100 >= 260:
|
||||
raise TaskCenterError('quick_run_path_length',
|
||||
'执行证据目录过长,且系统未提供可用短路径。请将工具和数据放到较短目录后重试;尚未启动 CAD 操作。')
|
||||
return str(Path(buffer.value) / script.name), buffer.value
|
||||
from .legacy_paths import worker_paths
|
||||
return worker_paths(script, root)
|
||||
|
||||
|
||||
def _resolve_cscript(windows_root: Path | None = None, is_64_bit: bool | None = None) -> Path:
|
||||
@@ -1695,10 +1731,15 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup
|
||||
return (resolved_executable, str(Path(__file__).with_name("application.py")))
|
||||
|
||||
|
||||
def _run_process(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
|
||||
def _run_process(command: tuple[str, ...], timeout: int, *, abort_event=None) -> subprocess.CompletedProcess[str]:
|
||||
from .isolated_cad import run_isolated_process
|
||||
from .legacy_paths import validate_project_access
|
||||
|
||||
return run_isolated_process(command, timeout)
|
||||
validate_project_access(Path(command[3]))
|
||||
result = run_isolated_process(command, timeout,
|
||||
**({'abort_event': abort_event, 'cooperative_abort': True} if abort_event is not None else {}))
|
||||
validate_project_access(Path(command[3]))
|
||||
return result
|
||||
|
||||
|
||||
def _log_text(value: str) -> str:
|
||||
|
||||
@@ -1,11 +1,37 @@
|
||||
"""Read-only execution view reconstructed from one cached set of handoff files."""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass, replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from .errors import TaskCenterError
|
||||
from .quick_run_protocol import QuickRunProgress
|
||||
|
||||
|
||||
def failed_native_result_uncertain(root, commands, statuses, *, files=None):
|
||||
"""Closing an unsaved project is not proof that native mutation rolled back."""
|
||||
from . import quick_run as api
|
||||
latest = {job: state for job, state, _, _ in statuses}
|
||||
awaiting = {job for job, state, _, _ in statuses if state == 'awaiting_native_replace'}
|
||||
for _, job, *_ in commands:
|
||||
if latest.get(job) != api.BATCH_FAILED_STATE:
|
||||
continue
|
||||
if api._rollback_marker_verified(root, job):
|
||||
continue
|
||||
path = root / f'snapshot-{job}.tsv.native.json'
|
||||
try:
|
||||
report = json.loads(files.read(path) if files is not None else path.read_text(encoding='utf-8-sig'))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
if job in awaiting or path.exists():
|
||||
return True
|
||||
continue
|
||||
if not isinstance(report, dict):
|
||||
return True
|
||||
if report.get('ok') is True or report.get('stage') in {
|
||||
'native_replace_started', 'native_replace_applied', 'pin_promotion_started', 'native_replace_verified'}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunSnapshot:
|
||||
progress: QuickRunProgress
|
||||
@@ -150,6 +176,7 @@ def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_
|
||||
if root == current:
|
||||
latest = {job_id: state for job_id, state, _, _ in details}
|
||||
interrupted = interrupted or any(state == api.BATCH_SAVED_UNVERIFIED_STATE for state in latest.values())
|
||||
interrupted = interrupted or failed_native_result_uncertain(root, commands, details, files=files)
|
||||
unfinished = api._next_unfinished_command(commands, details)
|
||||
if unfinished is not None:
|
||||
final = latest.get(unfinished[1])
|
||||
|
||||
@@ -34,10 +34,12 @@ def _is_link_or_reparse(path: Path) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _recovery_command(commands, statuses):
|
||||
def _recovery_command(commands, statuses, *, root=None):
|
||||
from .quick_run_snapshot import failed_native_result_uncertain
|
||||
latest = {entry[0]: entry[1] for entry in statuses}
|
||||
unverified = tuple(command for command in commands
|
||||
if latest.get(command[1]) == 'batch_saved_unverified')
|
||||
if latest.get(command[1]) == 'batch_saved_unverified'
|
||||
or (root is not None and failed_native_result_uncertain(root, (command,), statuses)))
|
||||
if len(unverified) > 1:
|
||||
raise TaskCenterError('quick_run_recovery', '多个保存后未核验步骤需要逐项人工核对,保护状态保持。')
|
||||
if unverified:
|
||||
@@ -99,7 +101,7 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
raise TaskCenterError('quick_run_recovery', '当前工程或规则与中断队列不同,不能恢复其他任务。')
|
||||
if not _value_mode_matches_option(mode, copy_part_number_to_value) or len({command[1] for command in commands}) != len(commands):
|
||||
raise TaskCenterError('quick_run_recovery', 'Value 策略变化或队列编号重复,已停止恢复。')
|
||||
selected = _recovery_command(commands, before)
|
||||
selected = _recovery_command(commands, before, root=root)
|
||||
if selected is None:
|
||||
raise TaskCenterError('quick_run_recovery', '队列记录已完成但仍有保护锁,需要单独核对,未自动解除。')
|
||||
job_id = _safe_run_token(selected[1])
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Reuse the replacement engine's mapping constraints for persisted and batch rules."""
|
||||
import csv
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from dx_productivity.part_replace.inputs import InputError, parse_mapping_bytes
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
def validate_mapping_pairs(pairs):
|
||||
output = io.StringIO(newline='')
|
||||
writer = csv.writer(output, lineterminator='\n')
|
||||
writer.writerow(('old_part_number', 'new_part_number'))
|
||||
writer.writerows(pairs)
|
||||
try:
|
||||
parse_mapping_bytes(output.getvalue().encode('utf-8'), Path('task-center-rules.csv'))
|
||||
except InputError as error:
|
||||
raise TaskCenterError(error.code, error.message) from error
|
||||
@@ -112,17 +112,7 @@ class TrialRunner:
|
||||
recovery_event_id=f"v1-attemptless:{recovery.project_id}:task:after",
|
||||
)
|
||||
self._store.acknowledge_migration_recoveries(tuple(recovery.project_id for recovery in migration_recoveries))
|
||||
interrupted_states = {
|
||||
ProjectStatus.CAPTURING_BEFORE,
|
||||
ProjectStatus.CAPTURING_AFTER,
|
||||
ProjectStatus.VERIFYING,
|
||||
}
|
||||
interrupted = tuple(
|
||||
project
|
||||
for task in self._store.list_tasks()
|
||||
for project in self._store.list_projects(task.task_id)
|
||||
if project.status in interrupted_states
|
||||
)
|
||||
interrupted = self._store.interrupted_projects()
|
||||
running_task_ids = {project.task_id for project in interrupted if self._store.get_task(project.task_id).status is TaskStatus.RUNNING}
|
||||
for project in interrupted:
|
||||
self._event_transition(
|
||||
@@ -147,6 +137,8 @@ class TrialRunner:
|
||||
"before",
|
||||
)
|
||||
recovered_project_ids = self._store.recover_interrupted_work()
|
||||
log_recovery = self._logging.logger.warning if recovered_project_ids else self._logging.logger.info
|
||||
log_recovery('recovered_interrupted_projects=%s', ','.join(recovered_project_ids) or 'none')
|
||||
for project_id in recovered_project_ids:
|
||||
project = self._project(project_id)
|
||||
self._event_transition(
|
||||
|
||||
@@ -21,10 +21,12 @@ from .target_plan import compile_target_rules
|
||||
from .project_tasks import create_project_tasks as _create_project_tasks
|
||||
from .inventory import collect_target_inventory
|
||||
from .spreadsheet_plan import export_target_plan as _export_target_plan, import_target_plan as _import_target_plan
|
||||
from .bom_plan import read_bom_plan as _read_bom_plan, write_bom_template as _write_bom_template
|
||||
from .bom_plan import read_bom_plan as _read_bom_plan
|
||||
from .project_context import ProjectTaskContext
|
||||
from .execution_metrics import measure_phase
|
||||
from .read_control import QueryCancelled
|
||||
from .batch_rules import batch_rule_view, mutate_batch_rules, seed_defaults
|
||||
from .operation_control import check_cancelled, control_options, report_progress
|
||||
|
||||
|
||||
_Result = TypeVar("_Result")
|
||||
@@ -135,22 +137,35 @@ class TaskCenterService:
|
||||
return self._operation("preview_bom_plan", task_id,
|
||||
lambda: _read_bom_plan(self._store, task_id, path))
|
||||
|
||||
def export_bom_template(self, task_id: str, path: Path) -> Path:
|
||||
def export():
|
||||
rows = self._store.list_target_plan(task_id)
|
||||
records = ({
|
||||
'old_part_number': row.target.old_part_number,
|
||||
'new_part_number': row.new_part_number,
|
||||
'refdes': row.target.refdes,
|
||||
'schematic_name': row.target.schematic_name,
|
||||
'sheet_number': row.target.sheet_number,
|
||||
'uid': row.target.uid,
|
||||
'enabled': row.enabled,
|
||||
'custom_value': row.custom_value if row.custom_value_enabled else '',
|
||||
'sync_nc': row.sync_nc,
|
||||
} for row in rows)
|
||||
return _write_bom_template(path, records)
|
||||
return self._operation("export_bom_template", task_id, export)
|
||||
def export_bom_template(self, task_id: str | None, path: Path) -> Path:
|
||||
from .bom_batch import export_template
|
||||
return self._operation("export_bom_template", task_id,
|
||||
lambda: export_template(self._store, task_id, path))
|
||||
|
||||
def preview_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None):
|
||||
from .bom_batch import preview_batch
|
||||
return self._idle_quick_run_operation('preview_bom_batch', task_id,
|
||||
lambda: preview_batch(self, task_id, path, **control_options(stop_event, on_progress)))
|
||||
|
||||
def save_bom_batch(self, preview, rows_by_task):
|
||||
from .bom_batch import save_batch
|
||||
return self._idle_quick_run_operation('save_bom_batch', preview.anchor_task_id,
|
||||
lambda: save_batch(self, preview, rows_by_task))
|
||||
|
||||
def save_plan_drafts(self, batches, standalone):
|
||||
"""Confirm all window drafts atomically, including multiple BOM batches."""
|
||||
from .bom_batch import save_batch, _assert_editable
|
||||
batches = tuple(batches)
|
||||
def save():
|
||||
result = {}
|
||||
with self._store.transaction():
|
||||
for preview, rows in batches:
|
||||
result.update(save_batch(self, preview, rows))
|
||||
for task_id, rows in standalone.items():
|
||||
_assert_editable(self, task_id)
|
||||
result[task_id] = self._store.replace_target_plan(task_id, rows)
|
||||
return result
|
||||
return self._idle_quick_run_operation('save_plan_drafts', None, save)
|
||||
|
||||
def for_project_task(self, task_id: str) -> "TaskCenterService":
|
||||
"""Return a facade whose evidence root is isolated to this task."""
|
||||
@@ -228,7 +243,7 @@ class TaskCenterService:
|
||||
legacy = bound is None
|
||||
if not allow_legacy and (task.primary_project_id is None or bound is None or len(projects) != 1):
|
||||
raise TaskCenterError("project_binding", "bound task must own exactly one project")
|
||||
rules, targets = bundle.rules, bundle.targets
|
||||
rules, targets = (bundle.batch_rules if bundle.batch_rules is not None else bundle.rules), bundle.targets
|
||||
facade = self._facade_for_task_record(task)
|
||||
effective_rules = compile_target_rules(tuple(targets)) if task.target_plan_mode else rules
|
||||
snapshot = facade._quick_run_preparer.read_snapshot(task_id, projects, effective_rules,
|
||||
@@ -271,7 +286,7 @@ class TaskCenterService:
|
||||
return self._idle_quick_run_operation("purge_task", task_id, purge)
|
||||
|
||||
def rules(self, task_id: str) -> tuple[RuleRecord, ...]:
|
||||
return self._operation("list_rules", task_id, lambda: self._store.list_rules(task_id))
|
||||
return self._operation("list_rules", task_id, lambda: batch_rule_view(self._store, task_id))
|
||||
|
||||
def _execution_rules(self, task_id: str):
|
||||
task = self._store.get_task(task_id)
|
||||
@@ -281,7 +296,7 @@ class TaskCenterService:
|
||||
if not rules:
|
||||
raise TaskCenterError("enabled_rule_required", "target plan has no enabled targets")
|
||||
return rules
|
||||
return self._store.list_rules(task_id)
|
||||
return batch_rule_view(self._store, task_id, strict=True)
|
||||
|
||||
def add_rule(
|
||||
self,
|
||||
@@ -297,17 +312,14 @@ class TaskCenterService:
|
||||
return self._idle_quick_run_operation(
|
||||
"add_rule",
|
||||
task_id,
|
||||
lambda: self._editable_rules(
|
||||
task_id,
|
||||
lambda: self._store.add_rule(
|
||||
task_id,
|
||||
old_part_number,
|
||||
new_part_number,
|
||||
lambda: mutate_batch_rules(
|
||||
self, task_id, 'add',
|
||||
old_part_number=old_part_number,
|
||||
new_part_number=new_part_number,
|
||||
enabled=enabled,
|
||||
custom_value_enabled=custom_value_enabled,
|
||||
custom_value=custom_value,
|
||||
sync_nc=sync_nc,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -325,17 +337,14 @@ class TaskCenterService:
|
||||
return self._idle_quick_run_operation(
|
||||
"update_rule",
|
||||
None,
|
||||
lambda: self._editable_rules(
|
||||
self._store.get_rule(rule_id).task_id,
|
||||
lambda: self._store.update_rule(
|
||||
rule_id,
|
||||
lambda: mutate_batch_rules(
|
||||
self, self._store.get_rule(rule_id).task_id, 'update', rule_id=rule_id,
|
||||
old_part_number=old_part_number,
|
||||
new_part_number=new_part_number,
|
||||
enabled=enabled,
|
||||
custom_value_enabled=custom_value_enabled,
|
||||
custom_value=custom_value,
|
||||
sync_nc=sync_nc,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -343,26 +352,32 @@ class TaskCenterService:
|
||||
self._idle_quick_run_operation(
|
||||
"delete_rule",
|
||||
None,
|
||||
lambda: self._editable_rules(self._store.get_rule(rule_id).task_id, lambda: self._store.delete_rule(rule_id)),
|
||||
lambda: mutate_batch_rules(self, self._store.get_rule(rule_id).task_id, 'delete', rule_id=rule_id),
|
||||
)
|
||||
|
||||
def move_rule(self, rule_id: str, offset: int) -> tuple[RuleRecord, ...]:
|
||||
return self._idle_quick_run_operation(
|
||||
"move_rule",
|
||||
None,
|
||||
lambda: self._editable_rules(self._store.get_rule(rule_id).task_id, lambda: self._store.move_rule(rule_id, offset)),
|
||||
lambda: mutate_batch_rules(self, self._store.get_rule(rule_id).task_id, 'move', rule_id=rule_id, offset=offset),
|
||||
)
|
||||
|
||||
def projects(self, task_id: str) -> tuple[ProjectRecord, ...]:
|
||||
return self._operation("list_projects", task_id, lambda: self._store.list_projects(task_id))
|
||||
|
||||
def collect_target_inventory(self, task_id: str, old_part_numbers: tuple[str, ...] | None = None):
|
||||
def collect_target_inventory(self, task_id: str, old_part_numbers: tuple[str, ...] | None = None,
|
||||
*, stop_event=None, on_progress=None):
|
||||
delegated = self._project_task_service(task_id)
|
||||
if delegated is not self:
|
||||
return delegated.collect_target_inventory(task_id, old_part_numbers)
|
||||
return delegated.collect_target_inventory(task_id, old_part_numbers, **control_options(stop_event, on_progress))
|
||||
def collect():
|
||||
rules = self._store.list_rules(task_id)
|
||||
parts = old_part_numbers or tuple(rule.old_part_number for rule in rules if rule.enabled)
|
||||
from .bom_batch import _assert_editable
|
||||
_assert_editable(self, task_id)
|
||||
check_cancelled(stop_event)
|
||||
rules = batch_rule_view(self._store, task_id, strict=True)
|
||||
prior = self._store.list_target_plan(task_id)
|
||||
requested = old_part_numbers or tuple(rule.old_part_number for rule in rules if rule.enabled)
|
||||
parts = tuple(dict.fromkeys((*requested, *(row.target.old_part_number for row in prior))))
|
||||
if not parts:
|
||||
raise TaskCenterError("target_inventory", "add an old Part Number before collecting inventory")
|
||||
project = self._store.list_projects(task_id)
|
||||
@@ -370,25 +385,20 @@ class TaskCenterService:
|
||||
raise TaskCenterError("target_inventory", "target inventory requires one project task")
|
||||
with measure_phase(self._logging, task_id, 'collect_inventory', unit='component',
|
||||
project_path=str(project[0].path)) as metric:
|
||||
rows = collect_target_inventory(self._quick_run_preparer, project[0].path, parts)
|
||||
report_progress(on_progress, f'正在采集工程:{project[0].display_name}')
|
||||
rows = collect_target_inventory(self._quick_run_preparer, project[0].path, parts,
|
||||
**control_options(stop_event, on_progress))
|
||||
check_cancelled(stop_event)
|
||||
metric['completed_units'] = len(rows)
|
||||
prior = self._store.list_target_plan(task_id)
|
||||
current = self._store.record_target_inventory(task_id, rows)
|
||||
if not current:
|
||||
return ()
|
||||
if prior:
|
||||
return current
|
||||
existing = {row.target.key: row for row in current}
|
||||
from .target_plan import TargetPlanRow
|
||||
return self._store.replace_target_plan(task_id, tuple(
|
||||
TargetPlanRow(row, False, next((r.new_part_number for r in rules
|
||||
if r.old_part_number.casefold() == row.old_part_number.casefold()), ""),
|
||||
next((r.custom_value_enabled for r in rules
|
||||
if r.old_part_number.casefold() == row.old_part_number.casefold()), False),
|
||||
next((r.custom_value for r in rules
|
||||
if r.old_part_number.casefold() == row.old_part_number.casefold()), ""),
|
||||
next((r.sync_nc for r in rules
|
||||
if r.old_part_number.casefold() == row.old_part_number.casefold()), True)) for row in rows))
|
||||
with self._store.transaction():
|
||||
if self._store.list_target_plan(task_id) != prior:
|
||||
raise TaskCenterError('target_identity', '位号计划在采集时已改变,请重新采集')
|
||||
current = self._store.record_target_inventory(task_id, rows)
|
||||
known = {row.target.key: row for row in prior}
|
||||
seeded = seed_defaults(current, rules)
|
||||
result = tuple(known.get(row.target.key, row) for row in seeded)
|
||||
check_cancelled(stop_event)
|
||||
return self._store.replace_target_plan(task_id, result)
|
||||
return self._idle_quick_run_operation("collect_target_inventory", task_id, collect)
|
||||
|
||||
def scan_projects(self, task_id: str, root: Path) -> tuple[ProjectRecord, ...]:
|
||||
@@ -681,6 +691,8 @@ class TaskCenterService:
|
||||
return delegated.prepare_failed_quick_run(task_id)
|
||||
def prepare_retry() -> QuickRunProgress:
|
||||
task = self._store.get_task(task_id)
|
||||
if self._quick_run_preparer.has_interrupted(task_id):
|
||||
raise TaskCenterError('quick_run_uncertain', '原生替换结果尚未核验,不能归档或重试。请先核验并恢复。')
|
||||
if task.status is not TaskStatus.RUNNING:
|
||||
raise TaskCenterError("quick_run_task_state", "当前任务没有可重试的失败项")
|
||||
progress = self._quick_run_preparer.progress(
|
||||
@@ -735,6 +747,17 @@ class TaskCenterService:
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation("prepare_failed_quick_run", task_id, prepare_retry)
|
||||
|
||||
def start_new_round(self, task_id: str) -> tuple[TaskRecord, ...]:
|
||||
"""Archive and reopen completed members of the selected task's batch."""
|
||||
from .new_round import start_new_round
|
||||
return self._idle_quick_run_operation('start_new_round', task_id,
|
||||
lambda: start_new_round(self, task_id))
|
||||
|
||||
def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None):
|
||||
from .bom_import_report import inspect_batch
|
||||
return self._idle_quick_run_operation('inspect_bom_batch', task_id,
|
||||
lambda: inspect_batch(self, task_id, path, **control_options(stop_event, on_progress)))
|
||||
|
||||
def _pause_quick_run_queue(self, task_id: str, message: str) -> None:
|
||||
if self._store.get_task(task_id).status is TaskStatus.RUNNING:
|
||||
self._store.set_task_status(task_id, TaskStatus.PAUSED, summary=message)
|
||||
@@ -800,7 +823,9 @@ class TaskCenterService:
|
||||
if task.status is TaskStatus.DELETED:
|
||||
raise TaskCenterError("quick_run_recovery", "请先恢复已删除的任务记录,再核验其中断步骤。")
|
||||
projects = self._store.list_projects(task_id)
|
||||
if any(project.selected and project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED} for project in projects):
|
||||
if any(project.selected and project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED}
|
||||
and not (project.status is ProjectStatus.FAILED
|
||||
and project.summary.startswith('quick_run_result:')) for project in projects):
|
||||
raise TaskCenterError("quick_run_recovery", "工程包含手动执行阶段或失败记录,不能混用自动队列恢复。")
|
||||
result = recover(self._quick_run_preparer, task_id, projects,
|
||||
self._execution_rules(task_id), copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
@@ -909,12 +934,24 @@ class TaskCenterService:
|
||||
self._store.get_task(task_id)
|
||||
path = self._quick_run_preparer.evidence_path(task_id)
|
||||
if path is None:
|
||||
raise TaskCenterError("evidence_missing", "quick-run evidence is unavailable for this task")
|
||||
from .new_round import latest_archive
|
||||
path = latest_archive(self._quick_run_preparer)
|
||||
if path is None:
|
||||
raise TaskCenterError("evidence_missing", "quick-run evidence is unavailable for this task")
|
||||
self._path_opener(path)
|
||||
return path
|
||||
|
||||
return self._operation("open_quick_run_evidence", task_id, open_path)
|
||||
|
||||
def open_round_history(self, task_id: str) -> Path:
|
||||
"""Open all retained rounds, or the current evidence before the first reset."""
|
||||
facade = self._project_task_service(task_id)
|
||||
rounds = facade._quick_run_preparer.data_root / 'rounds'
|
||||
if rounds.is_dir():
|
||||
return self._operation('open_round_history', task_id,
|
||||
lambda: (self._path_opener(rounds), rounds)[1])
|
||||
return facade.open_quick_run_evidence(task_id)
|
||||
|
||||
def _operation(self, name: str, task_id: str | None, action: Callable[[], _Result]) -> _Result:
|
||||
timestamp = self._clock().isoformat()
|
||||
self._logging.logger.info("operation_start=%s task_id=%s at=%s", name, task_id or "", timestamp)
|
||||
|
||||
@@ -6,18 +6,16 @@ from collections.abc import Iterator, Sequence
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
from dx_productivity.part_replace.inputs import InputError, parse_mapping_bytes
|
||||
from .rule_validation import validate_mapping_pairs
|
||||
|
||||
from .store_schema import StoreSchema, _SCHEMA_VERSION
|
||||
from .store_schema import StoreSchema
|
||||
from .store_target_plan import TargetPlanRepository
|
||||
from .store_read_model import TaskBundle, checkpoint, read_lock, read_task_bundle
|
||||
from .errors import TaskCenterError
|
||||
@@ -188,6 +186,34 @@ class TaskStore:
|
||||
def list_target_plan(self, task_id: str) -> tuple:
|
||||
return self._target_plans.list_target_plan(task_id)
|
||||
|
||||
def reset_completed_round(self, task_id: str, summary: str) -> TaskRecord:
|
||||
"""Dedicated reset gate; keep binding, rules and numbered attempt history."""
|
||||
with self.transaction():
|
||||
task = self.get_task(task_id)
|
||||
if task.status is not TaskStatus.COMPLETED:
|
||||
raise TaskCenterError('new_round_state', 'task is not completed')
|
||||
self._connection.execute('DELETE FROM target_plan WHERE task_id = ?', (task_id,))
|
||||
self._connection.execute(
|
||||
"""UPDATE projects SET status = ?, error_id = NULL, summary = '',
|
||||
retry_count = MAX(retry_count, COALESCE((SELECT MAX(attempt_number)
|
||||
FROM attempts WHERE attempts.project_id = projects.project_id), 0)) WHERE task_id = ?""",
|
||||
(ProjectStatus.PENDING.value, task_id))
|
||||
self._connection.execute(
|
||||
"""UPDATE tasks SET status = ?, started_utc = NULL, completed_utc = NULL,
|
||||
error_id = NULL, summary = ?, target_plan_mode = 1, updated_utc = ? WHERE task_id = ?""",
|
||||
(TaskStatus.DRAFT.value, summary, _utc_text(self._next_timestamp(task.updated_utc)), task_id))
|
||||
return self.get_task(task_id)
|
||||
|
||||
def record_round_commit(self, round_id: str) -> None:
|
||||
"""Immutable token committed in the same transaction as round resets."""
|
||||
self._connection.execute('INSERT INTO metadata(key, value) VALUES (?, ?)',
|
||||
(f'round_committed:{round_id}', '1'))
|
||||
|
||||
def round_committed(self, round_id: str) -> bool:
|
||||
with self._lock:
|
||||
return self._connection.execute('SELECT 1 FROM metadata WHERE key = ?',
|
||||
(f'round_committed:{round_id}',)).fetchone() is not None
|
||||
|
||||
def _ensure_rule_columns(self) -> None:
|
||||
return self._schema._ensure_rule_columns()
|
||||
|
||||
@@ -206,18 +232,21 @@ class TaskStore:
|
||||
self._transaction_depth += 1
|
||||
try:
|
||||
yield
|
||||
except BaseException:
|
||||
if outermost:
|
||||
self._connection.execute("ROLLBACK")
|
||||
else:
|
||||
self._connection.execute(f"ROLLBACK TO SAVEPOINT {savepoint}")
|
||||
self._connection.execute(f"RELEASE SAVEPOINT {savepoint}")
|
||||
raise
|
||||
else:
|
||||
if outermost:
|
||||
self._connection.execute("COMMIT")
|
||||
else:
|
||||
self._connection.execute(f"RELEASE SAVEPOINT {savepoint}")
|
||||
except BaseException:
|
||||
try:
|
||||
if outermost:
|
||||
self._connection.execute("ROLLBACK")
|
||||
else:
|
||||
self._connection.execute(f"ROLLBACK TO SAVEPOINT {savepoint}")
|
||||
self._connection.execute(f"RELEASE SAVEPOINT {savepoint}")
|
||||
except BaseException:
|
||||
# Preserve the original body/commit failure for diagnosis.
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
self._transaction_depth -= 1
|
||||
|
||||
@@ -409,10 +438,13 @@ class TaskStore:
|
||||
project = self._project_record(self._project_row(project_id))
|
||||
if project.task_id != task_id:
|
||||
raise TaskCenterError("project_task_mismatch", "project does not belong to the task")
|
||||
if project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED}:
|
||||
raise TaskCenterError("quick_run_project_state", "project state does not allow quick-run completion")
|
||||
summary = (project_summaries or {}).get(project_id, "current-sheet quick-run queue completed")
|
||||
if project.status is ProjectStatus.PENDING or project.summary != summary:
|
||||
recovered_native_failure = (project.status is ProjectStatus.FAILED
|
||||
and project.summary.startswith('quick_run_result:')
|
||||
and summary.startswith('quick_run_result:') and summary.endswith(':saved'))
|
||||
if project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED} and not recovered_native_failure:
|
||||
raise TaskCenterError("quick_run_project_state", "project state does not allow quick-run completion")
|
||||
if project.status is not ProjectStatus.COMPLETED or project.summary != summary:
|
||||
self._connection.execute(
|
||||
"UPDATE projects SET status = ?, error_id = NULL, summary = ? WHERE project_id = ?",
|
||||
(ProjectStatus.COMPLETED.value, summary, project_id),
|
||||
@@ -891,6 +923,16 @@ class TaskStore:
|
||||
with self._lock:
|
||||
return self._project_record(self._project_row(project_id))
|
||||
|
||||
def interrupted_projects(self) -> tuple[ProjectRecord, ...]:
|
||||
"""Read recovery candidates directly, without walking every idle task."""
|
||||
with self._lock:
|
||||
states = tuple(status.value for status in _INTERRUPTED_PROJECT_STATES)
|
||||
rows = self._connection.execute(
|
||||
f"SELECT * FROM projects WHERE status IN ({', '.join('?' for _ in states)}) ORDER BY project_id",
|
||||
states,
|
||||
).fetchall()
|
||||
return tuple(self._project_record(row) for row in rows)
|
||||
|
||||
def recover_interrupted_work(self) -> tuple[str, ...]:
|
||||
"""Mark projects interrupted during capture or verification as retryable failures."""
|
||||
with self.transaction():
|
||||
@@ -973,14 +1015,7 @@ class TaskStore:
|
||||
"SELECT old_part_number, new_part_number FROM rules WHERE task_id = ? AND enabled = 1 ORDER BY position",
|
||||
(task_id,),
|
||||
).fetchall()
|
||||
output = io.StringIO(newline="")
|
||||
writer = csv.writer(output, lineterminator="\n")
|
||||
writer.writerow(("old_part_number", "new_part_number"))
|
||||
writer.writerows((row["old_part_number"], row["new_part_number"]) for row in rows)
|
||||
try:
|
||||
parse_mapping_bytes(output.getvalue().encode("utf-8"), Path("task-center-rules.csv"))
|
||||
except InputError as error:
|
||||
raise TaskCenterError(error.code, error.message) from error
|
||||
validate_mapping_pairs((row['old_part_number'], row['new_part_number']) for row in rows)
|
||||
|
||||
def _rule_row(self, rule_id: str) -> sqlite3.Row:
|
||||
row = self._connection.execute("SELECT * FROM rules WHERE rule_id = ?", (rule_id,)).fetchone()
|
||||
|
||||
@@ -5,7 +5,7 @@ from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .models import TaskRecord, ProjectRecord, RuleRecord
|
||||
from .models import TaskRecord, ProjectRecord, RuleRecord, TaskStatus
|
||||
from .target_plan import ComponentTarget, TargetPlanRow
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ class TaskBundle:
|
||||
projects: tuple[ProjectRecord, ...]
|
||||
rules: tuple[RuleRecord, ...]
|
||||
targets: tuple[TargetPlanRow, ...]
|
||||
batch_rules: tuple[RuleRecord, ...] | None = None
|
||||
|
||||
|
||||
def checkpoint(read_control):
|
||||
@@ -66,6 +67,17 @@ def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
|
||||
rules = records(
|
||||
"SELECT * FROM rules WHERE task_id = ? ORDER BY position", store._rule_record,
|
||||
)
|
||||
batch_rules = None
|
||||
if task.group_id and task.status is not TaskStatus.DELETED:
|
||||
from .batch_rules import merge_rule_view
|
||||
group_rules = []
|
||||
for row in store._connection.execute(
|
||||
"SELECT r.* FROM rules r JOIN tasks t ON t.task_id = r.task_id "
|
||||
"WHERE t.group_id = ? AND t.status <> ? ORDER BY t.group_position, t.created_utc, t.task_id, r.position",
|
||||
(task.group_id, TaskStatus.DELETED.value)):
|
||||
checkpoint()
|
||||
group_rules.append(store._rule_record(row))
|
||||
batch_rules = merge_rule_view(group_rules, {r.old_part_number.casefold(): r for r in rules})
|
||||
def target_record(row):
|
||||
return TargetPlanRow(
|
||||
ComponentTarget(Path(row['project_path']), row['schematic_name'], row['sheet_number'],
|
||||
@@ -81,7 +93,7 @@ def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
|
||||
if started:
|
||||
store._connection.execute("COMMIT")
|
||||
started = False
|
||||
return TaskBundle(task, projects, rules, targets)
|
||||
return TaskBundle(task, projects, rules, targets, batch_rules)
|
||||
except BaseException:
|
||||
if started:
|
||||
store._connection.execute("ROLLBACK")
|
||||
|
||||
@@ -4,9 +4,26 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
from .errors import TaskCenterError
|
||||
from .models import TaskRecord, TaskStatus
|
||||
from .target_plan import ProjectIdentityResolver
|
||||
|
||||
def _target_baseline(target) -> tuple:
|
||||
return (target.key, target.refdes, target.old_part_number, target.old_value)
|
||||
def _target_baseline(target, identities) -> tuple:
|
||||
return (identities.target(target), target.refdes, target.old_part_number, target.old_value)
|
||||
|
||||
|
||||
def merge_target_inventory(existing, targets) -> tuple:
|
||||
"""Validate an additive inventory snapshot and retain every existing edit."""
|
||||
from .target_plan import TargetPlanRow
|
||||
existing, targets = tuple(existing), tuple(targets)
|
||||
identities = ProjectIdentityResolver()
|
||||
incoming = {identities.target(target): target for target in targets}
|
||||
if len(incoming) != len(targets):
|
||||
raise TaskCenterError("target_identity", "component inventory contains duplicate UID")
|
||||
if any(identities.target(row.target) not in incoming or
|
||||
_target_baseline(row.target, identities) != _target_baseline(incoming[identities.target(row.target)], identities)
|
||||
for row in existing):
|
||||
raise TaskCenterError("target_identity", "component inventory identity changed")
|
||||
known = {identities.target(row.target) for row in existing}
|
||||
return existing + tuple(TargetPlanRow(target) for key, target in incoming.items() if key not in known)
|
||||
|
||||
|
||||
class TargetPlanRepository:
|
||||
@@ -53,22 +70,24 @@ class TargetPlanRepository:
|
||||
raise TaskCenterError("target_plan_locked", "task plan is locked")
|
||||
rows = tuple(rows)
|
||||
compile_target_rules(rows)
|
||||
identities = ProjectIdentityResolver()
|
||||
projects = self._store.list_projects(task_id)
|
||||
allowed = {str(project.path.resolve(strict=False)).casefold() for project in projects}
|
||||
if any(str(row.target.project_path.resolve(strict=False)).casefold() not in allowed for row in rows):
|
||||
allowed = {identities.project(project.path) for project in projects}
|
||||
if any(identities.project(row.target.project_path) not in allowed for row in rows):
|
||||
raise TaskCenterError("target_identity", "target project is not in task")
|
||||
inventory = {row.target.key: row.target for row in self._store.list_target_plan(task_id)}
|
||||
inventory = {identities.target(row.target): row.target for row in self._store.list_target_plan(task_id)}
|
||||
if not inventory and not (task.target_plan_mode and not rows):
|
||||
raise TaskCenterError("target_inventory", "collect component inventory before editing the plan")
|
||||
if set(inventory) != {row.target.key for row in rows} or any(
|
||||
_target_baseline(inventory[row.target.key]) != _target_baseline(row.target)
|
||||
keys = {identities.target(row.target) for row in rows}
|
||||
if len(keys) != len(rows) or set(inventory) != keys or any(
|
||||
_target_baseline(inventory[identities.target(row.target)], identities) != _target_baseline(row.target, identities)
|
||||
for row in rows):
|
||||
raise TaskCenterError("target_identity", "target baseline identity changed")
|
||||
self._store._connection.execute("DELETE FROM target_plan WHERE task_id = ?", (task_id,))
|
||||
for row in rows:
|
||||
target = row.target
|
||||
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(task_id, str(target.project_path.resolve(strict=False)).casefold(), target.schematic_name,
|
||||
(task_id, identities.project(target.project_path), target.schematic_name,
|
||||
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value,
|
||||
int(row.enabled), row.new_part_number, int(row.custom_value_enabled), row.custom_value,
|
||||
int(row.sync_nc)))
|
||||
@@ -76,7 +95,6 @@ class TargetPlanRepository:
|
||||
return self._store.list_target_plan(task_id)
|
||||
|
||||
def record_target_inventory(self, task_id: str, targets) -> tuple:
|
||||
from .target_plan import TargetPlanRow
|
||||
with self._store.transaction():
|
||||
task = self._store.get_task(task_id)
|
||||
if task.status not in {TaskStatus.DRAFT, TaskStatus.READY}:
|
||||
@@ -87,25 +105,18 @@ class TargetPlanRepository:
|
||||
raise TaskCenterError("target_identity", "inventory unexpectedly became empty")
|
||||
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
|
||||
return ()
|
||||
if len({target.key for target in targets}) != len(targets):
|
||||
raise TaskCenterError("target_identity", "component inventory contains duplicate UID")
|
||||
existing = self._store.list_target_plan(task_id)
|
||||
if existing:
|
||||
known = {row.target.key: row.target for row in existing}
|
||||
if set(known) != {target.key for target in targets} or any(
|
||||
_target_baseline(known[target.key]) != _target_baseline(target)
|
||||
for target in targets):
|
||||
raise TaskCenterError("target_identity", "component inventory identity changed")
|
||||
return existing
|
||||
rows = tuple(TargetPlanRow(target) for target in targets)
|
||||
merged = merge_target_inventory(existing, targets)
|
||||
rows = merged[len(existing):]
|
||||
identities = ProjectIdentityResolver()
|
||||
projects = self._store.list_projects(task_id)
|
||||
allowed = {str(project.path.resolve(strict=False)).casefold() for project in projects}
|
||||
if any(str(row.target.project_path.resolve(strict=False)).casefold() not in allowed for row in rows):
|
||||
allowed = {identities.project(project.path) for project in projects}
|
||||
if any(identities.project(row.target.project_path) not in allowed for row in rows):
|
||||
raise TaskCenterError("target_identity", "inventory project is not in task")
|
||||
for row in rows:
|
||||
target = row.target
|
||||
self._store._connection.execute("""INSERT INTO target_plan VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, '', 0, '', 1)""",
|
||||
(task_id, str(target.project_path.resolve(strict=False)).casefold(), target.schematic_name,
|
||||
(task_id, identities.project(target.project_path), target.schematic_name,
|
||||
target.sheet_number, target.uid, target.refdes, target.old_part_number, target.old_value))
|
||||
self._store._connection.execute("UPDATE tasks SET target_plan_mode = 1 WHERE task_id = ?", (task_id,))
|
||||
return self._store.list_target_plan(task_id)
|
||||
|
||||
@@ -8,6 +8,21 @@ from pathlib import Path
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
class ProjectIdentityResolver:
|
||||
"""Resolve each project once within one validation pass, never across passes."""
|
||||
def __init__(self):
|
||||
self._projects = {}
|
||||
|
||||
def project(self, path):
|
||||
spelling = str(path)
|
||||
if spelling not in self._projects:
|
||||
self._projects[spelling] = str(Path(path).resolve(strict=False)).casefold()
|
||||
return self._projects[spelling]
|
||||
|
||||
def target(self, target):
|
||||
return (self.project(target.project_path), target.schematic_name, target.sheet_number, target.uid)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ComponentTarget:
|
||||
project_path: Path
|
||||
@@ -27,8 +42,7 @@ class ComponentTarget:
|
||||
|
||||
@property
|
||||
def key(self) -> tuple[str, str, str, str]:
|
||||
return (str(self.project_path.resolve(strict=False)).casefold(),
|
||||
self.schematic_name, self.sheet_number, self.uid)
|
||||
return ProjectIdentityResolver().target(self)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -77,14 +91,16 @@ def compile_target_rules(rows: tuple[TargetPlanRow, ...]) -> tuple[TargetRule, .
|
||||
grouped: dict[tuple[str, str, str, str, str, str, bool, str, bool], list[ComponentTarget]] = {}
|
||||
old_parts: set[str] = set()
|
||||
new_parts: set[str] = set()
|
||||
identities = ProjectIdentityResolver()
|
||||
for row in rows:
|
||||
target = row.target
|
||||
if not all((target.uid, target.refdes, target.schematic_name, target.sheet_number,
|
||||
target.old_part_number)):
|
||||
raise TaskCenterError("target_identity", "component identity is incomplete")
|
||||
if target.key in seen:
|
||||
target_key = identities.target(target)
|
||||
if target_key in seen:
|
||||
raise TaskCenterError("target_overlap", "target UID appears more than once")
|
||||
seen.add(target.key)
|
||||
seen.add(target_key)
|
||||
if not row.enabled:
|
||||
continue
|
||||
new = row.new_part_number.strip()
|
||||
@@ -95,7 +111,7 @@ def compile_target_rules(rows: tuple[TargetPlanRow, ...]) -> tuple[TargetRule, .
|
||||
raise TaskCenterError("value_option", "custom Value is empty")
|
||||
old_parts.add(old.casefold())
|
||||
new_parts.add(new.casefold())
|
||||
key = (str(target.project_path.resolve(strict=False)).casefold(), target.schematic_name,
|
||||
key = (target_key[0], target.schematic_name,
|
||||
target.sheet_number, old, new, row.custom_value_enabled,
|
||||
row.custom_value if row.custom_value_enabled else "", row.sync_nc)
|
||||
grouped.setdefault(key, []).append(target)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Disposable detail views. Plain report/log state lives outside the widgets."""
|
||||
from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt
|
||||
from PySide6.QtGui import QTextCursor
|
||||
from PySide6.QtWidgets import (QAbstractItemView, QDialog, QHBoxLayout, QLabel,
|
||||
QPlainTextEdit, QPushButton, QTableView, QTabWidget, QVBoxLayout, QWidget)
|
||||
|
||||
|
||||
class ResultTableModel(QAbstractTableModel):
|
||||
headers = ('图页', '位号', '旧料号', '回读料号', '核验状态')
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.rows = ()
|
||||
|
||||
def rowCount(self, parent=QModelIndex()):
|
||||
return 0 if parent.isValid() else len(self.rows)
|
||||
|
||||
def columnCount(self, parent=QModelIndex()):
|
||||
return 0 if parent.isValid() else len(self.headers)
|
||||
|
||||
def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
|
||||
if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal:
|
||||
return self.headers[section]
|
||||
return super().headerData(section, orientation, role)
|
||||
|
||||
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
|
||||
if index.isValid() and role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.ToolTipRole):
|
||||
return self.rows[index.row()][index.column()]
|
||||
return None
|
||||
|
||||
def populate(self, rows):
|
||||
rows = tuple(rows[-500:])
|
||||
if rows == self.rows:
|
||||
return
|
||||
if len(rows) > len(self.rows) and rows[:len(self.rows)] == self.rows:
|
||||
self.beginInsertRows(QModelIndex(), len(self.rows), len(rows) - 1)
|
||||
self.rows = rows
|
||||
self.endInsertRows()
|
||||
else:
|
||||
self.beginResetModel()
|
||||
self.rows = rows
|
||||
self.endResetModel()
|
||||
|
||||
|
||||
class TaskLogDialog(QDialog):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
|
||||
self.setWindowTitle('当前任务 · 替换结果与执行日志')
|
||||
self.resize(920, 440)
|
||||
self.log_text, self.result_rows = '', ()
|
||||
self._pending_log_scroll = 'bottom'
|
||||
self.log_view = self.result_view = None
|
||||
self.tabs = QTabWidget()
|
||||
self._pages = (QVBoxLayout(), QVBoxLayout())
|
||||
for title, layout in zip(('位号替换结果', '完整日志'), self._pages):
|
||||
page = QWidget()
|
||||
page.setLayout(layout)
|
||||
self.tabs.addTab(page, title)
|
||||
self.older_log_button = QPushButton('上一页日志', objectName='olderTaskLog')
|
||||
self.latest_log_button = QPushButton('最新日志', objectName='latestTaskLog')
|
||||
self.log_page_status = QLabel()
|
||||
actions = QHBoxLayout()
|
||||
for widget in (self.older_log_button, self.latest_log_button, self.log_page_status):
|
||||
actions.addWidget(widget)
|
||||
actions.addStretch()
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(self.tabs, 1)
|
||||
layout.addLayout(actions)
|
||||
self.tabs.currentChanged.connect(self._render)
|
||||
self._render()
|
||||
|
||||
def set_content(self, text, rows, *, scroll_to=None):
|
||||
self.log_text, self.result_rows = text, rows
|
||||
if scroll_to is not None:
|
||||
self._pending_log_scroll = scroll_to
|
||||
self._render()
|
||||
|
||||
def _render(self, *_):
|
||||
if self.tabs.currentIndex() == 0:
|
||||
if self.result_view is None:
|
||||
self.result_summary = QLabel()
|
||||
self.result_summary.setWordWrap(True)
|
||||
self.result_view = QTableView(objectName='executionResults')
|
||||
self.result_view.setModel(ResultTableModel(self.result_view))
|
||||
self.result_view.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.result_view.setAlternatingRowColors(True)
|
||||
for column, width in enumerate((140, 75, 195, 195, 165)):
|
||||
self.result_view.setColumnWidth(column, width)
|
||||
self._pages[0].addWidget(self.result_summary)
|
||||
self._pages[0].addWidget(self.result_view, 1)
|
||||
self.result_view.model().populate(self.result_rows)
|
||||
self.result_summary.setText(
|
||||
f'当前日志页含 {len(self.result_rows)} 条位号回读记录,显示最近 {min(500, len(self.result_rows))} 条。'
|
||||
'可翻页查看其他记录;失败和未命中见完整日志。')
|
||||
else:
|
||||
if self.log_view is None:
|
||||
self.log_view = QPlainTextEdit(objectName='logView')
|
||||
self.log_view.setReadOnly(True)
|
||||
self._pages[1].addWidget(self.log_view)
|
||||
previous = self.log_view.toPlainText()
|
||||
if previous == self.log_text:
|
||||
scroll = self.log_view.verticalScrollBar()
|
||||
if self._pending_log_scroll is not None:
|
||||
scroll.setValue(scroll.maximum() if self._pending_log_scroll == 'bottom' else 0)
|
||||
self._pending_log_scroll = None
|
||||
return
|
||||
scroll = self.log_view.verticalScrollBar()
|
||||
follow = (self._pending_log_scroll == 'bottom' or
|
||||
(self._pending_log_scroll is None and scroll.value() >= scroll.maximum() - 2))
|
||||
old = scroll.value()
|
||||
if previous and self.log_text.startswith(previous + '\n'):
|
||||
cursor = QTextCursor(self.log_view.document())
|
||||
cursor.movePosition(QTextCursor.MoveOperation.End)
|
||||
cursor.insertText(self.log_text[len(previous):])
|
||||
else:
|
||||
self.log_view.setPlainText(self.log_text)
|
||||
scroll.setValue(0 if self._pending_log_scroll == 'top' else scroll.maximum() if follow else old)
|
||||
self._pending_log_scroll = None
|
||||
|
||||
|
||||
class BomReportDialog(QDialog):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
|
||||
self.setWindowTitle('本批 BOM 导入校验详情')
|
||||
self.resize(820, 420)
|
||||
self.view = QPlainTextEdit(objectName='bomImportReport')
|
||||
self.view.setReadOnly(True)
|
||||
QVBoxLayout(self).addWidget(self.view)
|
||||
|
||||
def set_text(self, text):
|
||||
if self.view.toPlainText() != text:
|
||||
self.view.setPlainText(text)
|
||||
@@ -11,6 +11,7 @@ class ExecutionState:
|
||||
recover: bool = False
|
||||
execute_text: str = '执行当前任务'
|
||||
message: str = '点击新建,在弹窗中选择工程。'
|
||||
new_round: bool = False
|
||||
|
||||
|
||||
def execution_state(context, *, busy=False, dirty=False):
|
||||
@@ -31,9 +32,10 @@ def execution_state(context, *, busy=False, dirty=False):
|
||||
message = ('结果待核验,请先恢复中断步骤。' if context.interrupted else
|
||||
'位号计划有未保存编辑,请先保存。' if dirty else
|
||||
'正在处理当前步骤,暂停会等待安全收尾。' if busy else
|
||||
'任务已完成。' if context.progress.queue_complete and not retry else
|
||||
'任务已完成。可查看原计划和日志;点击“开始新一轮”归档本批已完成任务,再采集当前料号。' if task.status is TaskStatus.COMPLETED else
|
||||
'有失败项,可核对原因后重试。' if retry else
|
||||
'工程不可用,请检查路径。' if not project.available else
|
||||
'先填写旧、新料号,再采集并勾选位号。' if not pending else
|
||||
'配置就绪,可执行当前任务或按顺序执行本批任务。')
|
||||
return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message)
|
||||
return ExecutionState(editable, execute, retry, context.interrupted and not busy and not dirty, text, message,
|
||||
task.status is TaskStatus.COMPLETED and not context.interrupted and not busy and not dirty)
|
||||
@@ -4,7 +4,7 @@ from threading import Event
|
||||
import time
|
||||
from PySide6.QtCore import QElapsedTimer, QSettings, QSignalBlocker, QThreadPool, QTimer, Qt
|
||||
from PySide6.QtWidgets import (QApplication, QDialog, QHBoxLayout, QMainWindow, QMessageBox,
|
||||
QPushButton, QSplitter, QTabWidget, QVBoxLayout, QWidget)
|
||||
QPushButton, QLabel, QSplitter, QTabWidget, QVBoxLayout, QWidget)
|
||||
from ..errors import TaskCenterError
|
||||
from ..models import TaskStatus
|
||||
from ..version import VERSION
|
||||
@@ -23,13 +23,17 @@ from .task_log import TaskLogPresenter
|
||||
from .execution_feedback import format_feedback
|
||||
|
||||
class TrialTaskCenterWindow(QMainWindow):
|
||||
def __init__(self, service, directory_picker=None, quick_run_confirmer=None):
|
||||
def __init__(self, service, directory_picker=None, quick_run_confirmer=None, close_plan_confirmer=None):
|
||||
super().__init__()
|
||||
self.service = service
|
||||
self._close_plan_confirmer = close_plan_confirmer or self._confirm_close_plans
|
||||
self._close_pending = False
|
||||
self._close_saving = False
|
||||
self._quick_run_confirmer = quick_run_confirmer or self._confirm_quick_run
|
||||
self._task_id = None
|
||||
self._context = None
|
||||
self._tasks = ()
|
||||
self._known_task_groups = {}
|
||||
self._workers = set()
|
||||
self._closed = False
|
||||
self._batch_stop = None
|
||||
@@ -52,6 +56,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.setStyleSheet(APP_STYLESHEET)
|
||||
self.task_list = TaskList(self.open_task)
|
||||
self.task_list.filter.currentTextChanged.connect(self._refresh_task_list)
|
||||
self.task_list.recycle_button.toggled.connect(self._refresh_task_list)
|
||||
self.task_list.new_button.clicked.connect(self._new_task)
|
||||
self.task_list.edit_button.clicked.connect(self._edit_task)
|
||||
self.task_list.delete_button.clicked.connect(self._delete_task)
|
||||
@@ -62,7 +67,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.project_summary = ProjectSummary()
|
||||
self.project_summary.refresh_button.clicked.connect(self._refresh_bound_project)
|
||||
self.mapping_table = MappingTable(self._rule_enabled_changed)
|
||||
self.mapping_table.itemSelectionChanged.connect(self._update_gates)
|
||||
self.mapping_table.selectionModel().selectionChanged.connect(self._update_gates)
|
||||
self.add_mapping_button = QPushButton('添加料号规则', objectName='addMappingButton')
|
||||
self.edit_mapping_button = QPushButton('编辑规则', objectName='editMappingButton')
|
||||
self.delete_mapping_button = QPushButton('删除规则', objectName='deleteMappingButton')
|
||||
@@ -80,11 +85,17 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.run_panel.stop_queue_button.clicked.connect(self._pause_queue)
|
||||
self.run_panel.retry_button.clicked.connect(self._retry_failed)
|
||||
self.run_panel.recover_button.clicked.connect(self._recover_quick_run)
|
||||
self.run_panel.new_round_button.clicked.connect(self._start_new_round)
|
||||
self.run_panel.history_button.clicked.connect(self._open_round_history)
|
||||
self.run_panel.copy_value_check.toggled.connect(self._value_option_changed)
|
||||
self.run_panel.reset_layout_button.clicked.connect(self._reset_layout)
|
||||
self.run_panel.toggle_log_button.toggled.connect(lambda on: self._refresh_live_task_log() if on else None)
|
||||
self.run_panel.toggle_log_button.toggled.connect(self._log_visibility_changed)
|
||||
self._build_layout()
|
||||
self._layout_settings = QSettings(str(service.layout_settings_path), QSettings.Format.IniFormat)
|
||||
sort_index = self.task_list.sort.findData(self._layout_settings.value('tasks/sort', 'execution'))
|
||||
if sort_index >= 0:
|
||||
self.task_list.sort.setCurrentIndex(sort_index)
|
||||
self.task_list.view_changed.connect(self._update_gates)
|
||||
for name, widget in self._layout_widgets().items():
|
||||
saved = self._layout_settings.value(f'single_project/{name}')
|
||||
if saved is not None:
|
||||
@@ -96,6 +107,10 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
rule_page = QWidget()
|
||||
rules_layout = QVBoxLayout(rule_page)
|
||||
rules_layout.setContentsMargins(0, 0, 0, 0)
|
||||
rules_help = QLabel('规则提供采集条件和位号默认值;位号计划模式实际执行已保存的每行计划。'
|
||||
'修改默认值仅更新仍等于旧默认值的字段,保留手动覆盖和替换勾选。')
|
||||
rules_help.setWordWrap(True)
|
||||
rules_layout.addWidget(rules_help)
|
||||
rules_layout.addWidget(self.mapping_table, 1)
|
||||
commands = QHBoxLayout()
|
||||
for button in (self.add_mapping_button, self.edit_mapping_button, self.delete_mapping_button,
|
||||
@@ -108,13 +123,19 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.mapping_tabs.addTab(self.plan_panel, '本批位号计划')
|
||||
self.detail_splitter = QSplitter(Qt.Orientation.Vertical)
|
||||
self.detail_splitter.setChildrenCollapsible(False)
|
||||
self.detail_splitter.addWidget(self.run_panel)
|
||||
self.detail_splitter.setStretchFactor(0, 1)
|
||||
self.detail_splitter.addWidget(self.mapping_tabs)
|
||||
execution_area = QWidget()
|
||||
execution_layout = QVBoxLayout(execution_area)
|
||||
execution_layout.setContentsMargins(0, 0, 0, 0)
|
||||
execution_layout.addWidget(self.project_summary)
|
||||
execution_layout.addWidget(self.run_panel)
|
||||
self.detail_splitter.addWidget(execution_area)
|
||||
self.detail_splitter.setStretchFactor(0, 5)
|
||||
self.detail_splitter.setStretchFactor(1, 1)
|
||||
details = QWidget()
|
||||
details_layout = QVBoxLayout(details)
|
||||
details_layout.setContentsMargins(0, 0, 0, 0)
|
||||
details_layout.addWidget(self.mapping_tabs, 5)
|
||||
details_layout.addWidget(self.project_summary)
|
||||
details_layout.addWidget(self.run_panel.copy_value_check)
|
||||
details_layout.addWidget(self.detail_splitter, 1)
|
||||
self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal)
|
||||
self.workspace_splitter.setChildrenCollapsible(False)
|
||||
@@ -134,17 +155,52 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
|
||||
def _reset_layout(self):
|
||||
self.workspace_splitter.setSizes((240, 1040))
|
||||
self.detail_splitter.setSizes((190,))
|
||||
self.detail_splitter.setSizes((590, 170))
|
||||
self.run_panel.toggle_log_button.setChecked(False)
|
||||
|
||||
def _confirm_close_plans(self):
|
||||
box = QMessageBox(self)
|
||||
box.setWindowTitle('未保存位号计划')
|
||||
box.setText('当前或其他任务仍有未保存的位号计划 / BOM 预览。')
|
||||
save = box.addButton('保存全部', QMessageBox.ButtonRole.AcceptRole)
|
||||
discard = box.addButton('放弃', QMessageBox.ButtonRole.DestructiveRole)
|
||||
cancel = box.addButton('取消', QMessageBox.ButtonRole.RejectRole)
|
||||
box.setDefaultButton(cancel)
|
||||
box.exec()
|
||||
return 'save' if box.clickedButton() is save else 'discard' if box.clickedButton() is discard else 'cancel'
|
||||
|
||||
def closeEvent(self, event):
|
||||
if self._close_saving:
|
||||
event.ignore()
|
||||
return
|
||||
if self._workers:
|
||||
self._close_pending = True
|
||||
self.plan_panel.cancel_operation()
|
||||
self._pause_queue()
|
||||
self._set_operator_message('操作尚未结束,请等当前步骤安全收尾后关闭。', 'warning')
|
||||
event.ignore()
|
||||
return
|
||||
self._close_pending = False
|
||||
if self.plan_panel.has_unsaved_plans():
|
||||
choice = self._close_plan_confirmer()
|
||||
if choice == 'cancel':
|
||||
event.ignore()
|
||||
return
|
||||
if choice == 'save':
|
||||
event.ignore()
|
||||
self._close_saving = True
|
||||
def saved(_):
|
||||
self.plan_panel.discard_all()
|
||||
self._close_pending = True
|
||||
self._run_async(self.plan_panel.prepare_save_all(), saved)
|
||||
return
|
||||
if choice != 'discard':
|
||||
event.ignore()
|
||||
return
|
||||
self.plan_panel.discard_all()
|
||||
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._closed = True
|
||||
self._context_query.close()
|
||||
self._task_query.close()
|
||||
@@ -154,14 +210,14 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
super().closeEvent(event)
|
||||
|
||||
def _refresh_task_list(self):
|
||||
deleted = self.task_list.recycle_button.isChecked()
|
||||
def received(tasks):
|
||||
self._known_task_groups.update((task.task_id, task.group_id) for task in tasks)
|
||||
self._tasks = tasks
|
||||
order = {TaskStatus.DELETED: 3, TaskStatus.COMPLETED: 2}
|
||||
tasks = tuple(sorted(tasks, key=lambda task: (order.get(task.status, 1),
|
||||
-task.updated_utc.timestamp(), task.name.casefold())))
|
||||
self.task_list.populate(tasks, selected_task_id=self._task_id)
|
||||
self._update_gates()
|
||||
self._task_query.request(lambda control: self.service.tasks(read_control=control), received, self._show_error, cancellable=True)
|
||||
self._task_query.request(lambda control: self.service.tasks(status=TaskStatus.DELETED, read_control=control)
|
||||
if deleted else self.service.tasks(read_control=control), received, self._show_error, cancellable=True)
|
||||
|
||||
def open_task(self, task_id):
|
||||
if not task_id or (self._workers and self._batch_stop is None):
|
||||
@@ -171,6 +227,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.project_summary.populate(None)
|
||||
self.mapping_table.populate(())
|
||||
self._task_id = task_id
|
||||
self.task_list.select_task(task_id)
|
||||
self._message = ''
|
||||
self._log_presenter.bind(task_id)
|
||||
self._load_task_data()
|
||||
@@ -195,6 +252,8 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
try:
|
||||
self._loading = False
|
||||
self._context = context
|
||||
if context:
|
||||
self._known_task_groups[context.task.task_id] = context.task.group_id
|
||||
self.project_summary.populate(context)
|
||||
self.plan_panel.bind_task(self._task_id, context.targets if context else ())
|
||||
self.mapping_table.populate(context.rules if context else ())
|
||||
@@ -209,8 +268,6 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
else:
|
||||
self.run_panel.queue_summary.setText('未选择任务')
|
||||
self._refresh_live_task_log()
|
||||
if context and (context.progress.saved_items or context.phase in {'complete', 'retry'}):
|
||||
self._show_task_log()
|
||||
self._update_gates()
|
||||
except Exception as error:
|
||||
self._context = None
|
||||
@@ -219,6 +276,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
def _update_gates(self):
|
||||
busy = bool(self._workers) or self._loading
|
||||
state = execution_state(self._context, busy=busy, dirty=self.plan_panel.table.dirty)
|
||||
group_unsaved = self._group_has_unsaved_plans() if state.editable or state.new_round else False
|
||||
context = self._context
|
||||
self.run_panel.quick_run_button.setText(state.execute_text)
|
||||
self.run_panel.quick_run_button.setEnabled(state.execute)
|
||||
@@ -226,19 +284,28 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.run_panel.retry_button.setEnabled(state.retry)
|
||||
self.run_panel.recover_button.setVisible(bool(context and context.interrupted))
|
||||
self.run_panel.recover_button.setEnabled(state.recover)
|
||||
self.run_panel.new_round_button.setVisible(bool(context and context.task.status is TaskStatus.COMPLETED))
|
||||
self.run_panel.new_round_button.setEnabled(state.new_round and not group_unsaved)
|
||||
self.run_panel.history_button.setVisible(bool(context and
|
||||
(context.has_evidence or context.task.status is TaskStatus.COMPLETED or context.task.summary.startswith('new round '))))
|
||||
self.run_panel.history_button.setEnabled(bool(context and not busy))
|
||||
self.run_panel.stop_queue_button.setVisible(self._batch_stop is not None)
|
||||
self.run_panel.stop_queue_button.setEnabled(bool(self._batch_stop and not self._batch_stop.is_set()))
|
||||
self.run_panel.copy_value_check.setEnabled(state.editable)
|
||||
self.mapping_table.set_rules_editable(state.editable)
|
||||
self.plan_panel.set_plan_editable(state.editable)
|
||||
self.add_mapping_button.setEnabled(state.editable)
|
||||
rule_editable = state.editable and not group_unsaved
|
||||
self.mapping_table.set_rules_editable(rule_editable)
|
||||
self.plan_panel.set_plan_editable(state.editable, busy=busy)
|
||||
self.add_mapping_button.setEnabled(rule_editable)
|
||||
selected = self.mapping_table.current_rule_id() is not None
|
||||
for button in (self.edit_mapping_button, self.delete_mapping_button,
|
||||
self.move_mapping_up_button, self.move_mapping_down_button):
|
||||
button.setEnabled(state.editable and selected)
|
||||
button.setEnabled(rule_editable and selected)
|
||||
self.project_summary.refresh_button.setEnabled(bool(context and not context.legacy and not busy))
|
||||
self.task_list.list.setEnabled(not self._workers or self._batch_stop is not None)
|
||||
self.task_list.filter.setEnabled(not self._workers or self._batch_stop is not None)
|
||||
self.task_list.search.setEnabled(not self._workers or self._batch_stop is not None)
|
||||
self.task_list.recycle_button.setEnabled(not busy)
|
||||
self.task_list.sort.setEnabled(not self._workers or self._batch_stop is not None)
|
||||
self.task_list.new_button.setEnabled(not busy)
|
||||
exists = bool(context)
|
||||
deleted = bool(context and context.task.status is TaskStatus.DELETED)
|
||||
@@ -247,13 +314,16 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self.task_list.delete_button.setText('彻底删除' if deleted else '删除')
|
||||
self.task_list.restore_button.setEnabled(deleted and not busy)
|
||||
grouped = bool(context and not context.legacy and context.task.group_id and not deleted)
|
||||
group_ids = tuple(t.task_id for t in self._tasks if context and t.group_id == context.task.group_id
|
||||
and t.status is not TaskStatus.DELETED)
|
||||
group_ids = {t.task_id for t in self._tasks if context and t.group_id == context.task.group_id
|
||||
and t.status is not TaskStatus.DELETED}
|
||||
group_dirty = self.plan_panel.has_unsaved_plan(group_ids)
|
||||
group_active = any(t.status in {TaskStatus.RUNNING, TaskStatus.PAUSED} for t in self._tasks if t.task_id in group_ids)
|
||||
self.task_list.queue_button.setEnabled(grouped and not busy and not group_dirty and not bool(context.interrupted))
|
||||
for button in (self.task_list.up_button, self.task_list.down_button):
|
||||
button.setEnabled(grouped and not busy and not group_active)
|
||||
button.setEnabled(grouped and not busy and not group_active
|
||||
and self.task_list.sort.currentData() == 'execution'
|
||||
and not self.task_list.search.text().strip())
|
||||
button.setToolTip('清空搜索并切换到执行顺序后,可调整本批任务的执行位置。')
|
||||
if not self._message:
|
||||
self.run_panel.operator_band.setText(state.message)
|
||||
if self._loading and not self._message:
|
||||
@@ -261,6 +331,26 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
if not busy:
|
||||
self.run_panel.execution_status.setText('结果待核验' if context and context.interrupted else '空闲')
|
||||
|
||||
def _group_has_unsaved_plans(self):
|
||||
if not self._context:
|
||||
return False
|
||||
task = self._context.task
|
||||
ids = {task.task_id}
|
||||
if task.group_id:
|
||||
ids.update(task_id for task_id, group in self._known_task_groups.items() if group == task.group_id)
|
||||
# Preview scope may also contain members no longer in the normal task list.
|
||||
for batch in self.plan_panel._bom_batches.values():
|
||||
if ids.intersection(task_id for task_id, _ in batch.scope):
|
||||
return True
|
||||
return self.plan_panel.has_unsaved_plan(ids)
|
||||
|
||||
def _rules_change_allowed(self):
|
||||
if self._group_has_unsaved_plans():
|
||||
self._set_operator_message('本批存在未保存计划,请先保存或放弃草稿后修改规则。', 'warning')
|
||||
self._load_task_data()
|
||||
return False
|
||||
return True
|
||||
|
||||
def _new_task(self):
|
||||
dialog = DirectoryTaskDialog(self.service, self)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
@@ -269,7 +359,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._project_tasks_created, self.task_list.new_button)
|
||||
|
||||
def _project_tasks_created(self, tasks):
|
||||
self.task_list.filter.setCurrentText('进行中')
|
||||
self.task_list.recycle_button.setChecked(False)
|
||||
self._refresh_task_list()
|
||||
if tasks:
|
||||
self._task_id = tasks[0].task_id
|
||||
@@ -310,7 +400,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
operation = (lambda: self.service.purge_task(task.task_id, confirmed=True)) if permanent else (lambda: self.service.delete_task(task.task_id))
|
||||
def done(_):
|
||||
if permanent:
|
||||
self.plan_panel._drafts.pop(task.task_id, None)
|
||||
self.plan_panel.forget_task(task.task_id)
|
||||
self._task_id = None
|
||||
self._metadata_changed(None)
|
||||
self._run_async(operation, done, self.task_list.delete_button)
|
||||
@@ -337,6 +427,8 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._mapping_dialog(rule)
|
||||
|
||||
def _mapping_dialog(self, rule):
|
||||
if not self._rules_change_allowed():
|
||||
return
|
||||
dialog = _MappingDialog(self, *(() if rule is None else (rule.old_part_number, rule.new_part_number,
|
||||
rule.enabled, rule.custom_value_enabled, rule.custom_value, rule.sync_nc)))
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
@@ -349,16 +441,22 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._run_async(operation, lambda _: self._load_task_data(), expected_task_id=task_id)
|
||||
|
||||
def _delete_mapping(self):
|
||||
if not self._rules_change_allowed():
|
||||
return
|
||||
rule_id = self.mapping_table.current_rule_id()
|
||||
if rule_id:
|
||||
self._run_async(lambda: self.service.delete_rule(rule_id), lambda _: self._load_task_data())
|
||||
|
||||
def _move_mapping(self, offset):
|
||||
if not self._rules_change_allowed():
|
||||
return
|
||||
rule_id = self.mapping_table.current_rule_id()
|
||||
if rule_id:
|
||||
self._run_async(lambda: self.service.move_rule(rule_id, offset), lambda _: self._load_task_data())
|
||||
|
||||
def _rule_enabled_changed(self, rule_id, enabled):
|
||||
if not self._rules_change_allowed():
|
||||
return
|
||||
rule = next((r for r in self._context.rules if r.rule_id == rule_id), None) if self._context else None
|
||||
if rule:
|
||||
self._run_async(lambda: self.service.update_rule(rule_id, old_part_number=rule.old_part_number,
|
||||
@@ -459,11 +557,43 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._run_async(lambda: self.service.prepare_failed_quick_run(task_id),
|
||||
lambda _: self._load_task_data(), self.run_panel.retry_button, expected_task_id=task_id)
|
||||
|
||||
def _start_new_round(self):
|
||||
if not self.run_panel.new_round_button.isEnabled():
|
||||
return
|
||||
task_id = self._task_id
|
||||
group_id = self._context.task.group_id
|
||||
members = tuple(t for t in self._tasks if t.status is TaskStatus.COMPLETED
|
||||
and (t.group_id == group_id if group_id else t.task_id == task_id))
|
||||
names = '\n'.join(t.name for t in members)
|
||||
if QMessageBox.question(self, '开始新一轮',
|
||||
f'将为以下 {len(members)} 个已完成任务开始新一轮:\n{names}\n\n'
|
||||
'旧计划、命令、快照和日志会保留为轮次证据;当前位号基线将清空。'
|
||||
'请按工程当前料号重新填写规则或导入 BOM,再采集位号、保存并执行。'
|
||||
'本批尚未执行的草稿保留原配置。',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
def done(tasks):
|
||||
self._project_queues.pop(group_id, None)
|
||||
self._context_query.invalidate()
|
||||
for task in tasks:
|
||||
self.plan_panel.forget_task(task.task_id)
|
||||
self._metadata_changed(None)
|
||||
self._set_operator_message('新一轮已创建。请按当前料号导入 BOM 或修改规则,并重新采集位号;旧轮次可通过“查看轮次证据”打开。')
|
||||
self._run_async(lambda: self.service.start_new_round(task_id), done,
|
||||
self.run_panel.new_round_button, expected_task_id=task_id)
|
||||
|
||||
def _open_round_history(self):
|
||||
if self.run_panel.history_button.isEnabled() and self._task_id:
|
||||
task_id = self._task_id
|
||||
self._run_async(lambda: self.service.open_round_history(task_id), lambda _: None,
|
||||
self.run_panel.history_button, expected_task_id=task_id)
|
||||
|
||||
def _recover_quick_run(self):
|
||||
if not self.run_panel.recover_button.isEnabled():
|
||||
return
|
||||
if QMessageBox.question(self, '核验并恢复',
|
||||
'先备份工程和证据,再打开工程核验;不会重复调用原生替换,也不会自动保存。请先保存并关闭已有 CAD 工程。',
|
||||
'先备份工程和证据,再打开工程核验;如需补齐属性,会保存并重开回读,不会重复调用原生替换。请确保待处理工程未在其他 CAD 会话中打开。',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
@@ -483,7 +613,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
if t.group_id == context.task.group_id and t.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED})
|
||||
text = (f'执行范围:{names}\n\n' + (f'勾选目标/规则:{enabled_rules}\n' if scope == 'current' else f'按顺序处理 {selected_projects} 个工程任务。\n')
|
||||
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
|
||||
+ '\n请先保存并关闭已有 DxDesigner 工程。当前默认执行仍使用原生窗口;独立桌面后端处于研究阶段。'
|
||||
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
|
||||
+ '\n确认后连续执行,暂停等待当前步骤收尾;状态不确定时停止。')
|
||||
return QMessageBox.question(self, '确认执行当前任务' if scope == 'current' else '确认顺序执行本批任务', text,
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
@@ -509,15 +639,23 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._log_presenter.bind(self._task_id)
|
||||
self._log_presenter.refresh()
|
||||
|
||||
def _log_visibility_changed(self, visible):
|
||||
if visible:
|
||||
self._refresh_live_task_log()
|
||||
else:
|
||||
self._log_presenter.pause()
|
||||
|
||||
def _show_task_log(self, *, force=False):
|
||||
self.run_panel.toggle_log_button.setChecked(True)
|
||||
if force:
|
||||
if not self.run_panel.toggle_log_button.isChecked():
|
||||
# The visibility handler performs the first read exactly once.
|
||||
self.run_panel.toggle_log_button.setChecked(True)
|
||||
elif force:
|
||||
self._log_presenter.latest(force=True)
|
||||
else:
|
||||
self._refresh_live_task_log()
|
||||
|
||||
def _append_log(self, line):
|
||||
self.run_panel.log_view.appendPlainText(_format_live_log_line(line))
|
||||
self._log_presenter.append_line(_format_live_log_line(line))
|
||||
|
||||
def _set_operator_message(self, text, state='info'):
|
||||
self._message = text
|
||||
@@ -544,12 +682,21 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
except Exception as error:
|
||||
self._show_error(error)
|
||||
def failed(error):
|
||||
if self._close_saving or not (isinstance(error, TaskCenterError) and error.code == 'operation_cancelled'):
|
||||
self._close_pending = False
|
||||
self._finish_run()
|
||||
if isinstance(error, TaskCenterError) and error.code == 'operation_cancelled':
|
||||
self._set_operator_message('已取消采集 / 导入,自有会话已安全释放。')
|
||||
return
|
||||
if valid():
|
||||
self._load_task_data()
|
||||
self._show_error(error, owner_task_id=owner)
|
||||
def finished():
|
||||
self._workers.discard(worker)
|
||||
self.plan_panel.finish_operation()
|
||||
self._close_saving = False
|
||||
if self._close_pending and not self._closed:
|
||||
QTimer.singleShot(0, self.close)
|
||||
if not self._closed:
|
||||
self._update_gates()
|
||||
worker.signals.succeeded.connect(succeeded)
|
||||
|
||||
@@ -1,62 +1,108 @@
|
||||
"""Ordered Part Number mapping table."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
"""Ordered rules rendered on demand, without a widget per row."""
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QHBoxLayout, QHeaderView, QTableWidget, QTableWidgetItem, QWidget
|
||||
from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Signal
|
||||
from PySide6.QtWidgets import QAbstractItemView, QHeaderView, QTableView
|
||||
|
||||
|
||||
class MappingTable(QTableWidget):
|
||||
def __init__(self, on_enabled_changed: Callable[[str, bool], None] | None = None) -> None:
|
||||
super().__init__(0, 6)
|
||||
self.setObjectName("mappingTable")
|
||||
class RuleTableModel(QAbstractTableModel):
|
||||
enabled_requested = Signal(str, bool)
|
||||
headers = ('旧物料编码', '新物料编码', '自定义 Value', '同步 NC', '启用', '顺序')
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.rules = ()
|
||||
self.editable = True
|
||||
|
||||
def rowCount(self, parent=QModelIndex()):
|
||||
return 0 if parent.isValid() else len(self.rules)
|
||||
|
||||
def columnCount(self, parent=QModelIndex()):
|
||||
return 0 if parent.isValid() else len(self.headers)
|
||||
|
||||
def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
|
||||
if role == Qt.ItemDataRole.DisplayRole and orientation == Qt.Orientation.Horizontal:
|
||||
return self.headers[section]
|
||||
return super().headerData(section, orientation, role)
|
||||
|
||||
def data(self, index, role=Qt.ItemDataRole.DisplayRole):
|
||||
if not index.isValid() or not 0 <= index.row() < len(self.rules):
|
||||
return None
|
||||
rule, column = self.rules[index.row()], index.column()
|
||||
if role == Qt.ItemDataRole.UserRole:
|
||||
return rule.rule_id
|
||||
if role == Qt.ItemDataRole.CheckStateRole and column == 4:
|
||||
return Qt.CheckState.Checked if rule.enabled else Qt.CheckState.Unchecked
|
||||
if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.ToolTipRole):
|
||||
if column == 4:
|
||||
return '启用或停用此替换规则' if role == Qt.ItemDataRole.ToolTipRole else None
|
||||
if column == 2:
|
||||
return rule.custom_value if getattr(rule, 'custom_value_enabled', False) else '不写入'
|
||||
if column == 3:
|
||||
return '是' if getattr(rule, 'sync_nc', True) else '否'
|
||||
if column == 5:
|
||||
return rule.position + 1
|
||||
return rule.old_part_number if column == 0 else rule.new_part_number
|
||||
return None
|
||||
|
||||
def flags(self, index):
|
||||
flags = super().flags(index)
|
||||
if index.isValid() and index.column() == 4 and self.editable:
|
||||
flags |= Qt.ItemFlag.ItemIsUserCheckable
|
||||
return flags
|
||||
|
||||
def setData(self, index, value, role=Qt.ItemDataRole.EditRole):
|
||||
if (not self.editable or not index.isValid() or index.column() != 4
|
||||
or not 0 <= index.row() < len(self.rules) or role != Qt.ItemDataRole.CheckStateRole):
|
||||
return False
|
||||
enabled = value in (Qt.CheckState.Checked, Qt.CheckState.Checked.value)
|
||||
# A fresh persisted context confirms the write; failures do not leave a false check.
|
||||
self.enabled_requested.emit(self.rules[index.row()].rule_id, enabled)
|
||||
return True
|
||||
|
||||
def populate(self, rules):
|
||||
rules = tuple(rules)
|
||||
if rules == self.rules:
|
||||
return
|
||||
if tuple(r.rule_id for r in rules) == tuple(r.rule_id for r in self.rules):
|
||||
self.rules = rules
|
||||
if rules:
|
||||
self.dataChanged.emit(self.index(0, 0), self.index(len(rules) - 1, 5))
|
||||
else:
|
||||
self.beginResetModel()
|
||||
self.rules = rules
|
||||
self.endResetModel()
|
||||
|
||||
|
||||
class MappingTable(QTableView):
|
||||
def __init__(self, on_enabled_changed: Callable[[str, bool], None] | None = None):
|
||||
super().__init__()
|
||||
self.setObjectName('mappingTable')
|
||||
self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.setHorizontalHeaderLabels(("旧物料编码", "新物料编码", "自定义 Value", "同步 NC", "启用", "顺序"))
|
||||
self.setAlternatingRowColors(True)
|
||||
self._model = RuleTableModel(self)
|
||||
self.setModel(self._model)
|
||||
if on_enabled_changed is not None:
|
||||
self._model.enabled_requested.connect(on_enabled_changed)
|
||||
header = self.horizontalHeader()
|
||||
for section, width in ((0, 220), (1, 220), (2, 180), (3, 80), (4, 70), (5, 65)):
|
||||
header.setSectionResizeMode(section, QHeaderView.ResizeMode.Interactive)
|
||||
header.resizeSection(section, width)
|
||||
header.setStretchLastSection(True)
|
||||
self._on_enabled_changed = on_enabled_changed
|
||||
self._rules_editable = True
|
||||
|
||||
def set_rules_editable(self, editable: bool) -> None:
|
||||
self._rules_editable = editable
|
||||
for row in range(self.rowCount()):
|
||||
cell = self.cellWidget(row, 4)
|
||||
if cell is not None:
|
||||
for check in cell.findChildren(QCheckBox):
|
||||
check.setEnabled(editable)
|
||||
def set_rules_editable(self, editable: bool):
|
||||
if self._model.editable != editable:
|
||||
self._model.editable = editable
|
||||
if self._model.rules:
|
||||
self._model.dataChanged.emit(self._model.index(0, 4), self._model.index(len(self._model.rules) - 1, 4))
|
||||
|
||||
def populate(self, rules: Iterable[object]) -> None:
|
||||
self.setRowCount(0)
|
||||
for row, rule in enumerate(rules):
|
||||
self.insertRow(row)
|
||||
first = QTableWidgetItem(str(getattr(rule, "old_part_number")))
|
||||
first.setData(32, str(getattr(rule, "rule_id")))
|
||||
self.setItem(row, 0, first)
|
||||
self.setItem(row, 1, QTableWidgetItem(str(getattr(rule, "new_part_number"))))
|
||||
custom_value = str(getattr(rule, "custom_value", "")) if bool(getattr(rule, "custom_value_enabled", False)) else "不写入"
|
||||
self.setItem(row, 2, QTableWidgetItem(custom_value))
|
||||
self.setItem(row, 3, QTableWidgetItem("是" if bool(getattr(rule, "sync_nc", True)) else "否"))
|
||||
enabled = QCheckBox()
|
||||
enabled.setChecked(bool(getattr(rule, "enabled")))
|
||||
enabled.setEnabled(self._rules_editable)
|
||||
enabled.setToolTip("启用或停用此替换规则")
|
||||
if self._on_enabled_changed is not None:
|
||||
rule_id = str(getattr(rule, "rule_id"))
|
||||
enabled.toggled.connect(lambda checked, item_id=rule_id: self._on_enabled_changed(item_id, checked))
|
||||
enabled_cell = QWidget()
|
||||
enabled_layout = QHBoxLayout(enabled_cell)
|
||||
enabled_layout.setContentsMargins(0, 0, 0, 0)
|
||||
enabled_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
enabled_layout.addWidget(enabled)
|
||||
self.setCellWidget(row, 4, enabled_cell)
|
||||
self.setItem(row, 5, QTableWidgetItem(str(getattr(rule, "position") + 1)))
|
||||
self.resizeRowsToContents()
|
||||
def populate(self, rules: Iterable[object]):
|
||||
selected = self.current_rule_id()
|
||||
self._model.populate(rules)
|
||||
if selected and self.current_rule_id() != selected:
|
||||
row = next((i for i, rule in enumerate(self._model.rules) if rule.rule_id == selected), None)
|
||||
if row is not None:
|
||||
self.setCurrentIndex(self._model.index(row, 0))
|
||||
|
||||
def current_rule_id(self) -> str | None:
|
||||
item = self.item(self.currentRow(), 0)
|
||||
return str(item.data(32)) if item is not None else None
|
||||
def current_rule_id(self):
|
||||
return self.currentIndex().data(Qt.ItemDataRole.UserRole)
|
||||
@@ -26,7 +26,7 @@ ERROR_TEXT = {
|
||||
"quick_run_session": "本次执行在启动或工程检查阶段停止,尚未开始本项替换。请按具体原因处理后重试。",
|
||||
"quick_run_complete": "当前任务中的替换规则已经全部完成。",
|
||||
"quick_run_cscript": "未找到 Windows 脚本运行组件,无法连接 DxDesigner。",
|
||||
"quick_run_path_length": "执行目录过长,请使用较短的工具及数据目录。",
|
||||
"quick_run_path_length": "无法建立长路径兼容入口,请查看详细错误及当前用户目录的写入权限。",
|
||||
"quick_run_command": "替换命令文件无效,请查看日志。",
|
||||
"quick_run_uncertain": "无法确认本次替换结果,请使用“核验并恢复中断任务”,不要直接清锁重跑。",
|
||||
"quick_run_recovery": "中断任务恢复未通过,原保护状态仍保留。",
|
||||
@@ -71,8 +71,8 @@ def _nc_sync_log_lines(message: str) -> tuple[str, ...]:
|
||||
)
|
||||
|
||||
|
||||
def _replacement_log_lines(message: str, state: str) -> tuple[str, ...]:
|
||||
"""Render native readback results; never turn a plan or failed step into success."""
|
||||
def _replacement_parts(message: str, state: str) -> tuple[tuple[str, str, str], ...]:
|
||||
"""Parse only native readback messages; plans and failures are excluded."""
|
||||
if state not in {'saved_ok', 'restored_ok'}:
|
||||
return ()
|
||||
_, marker, summary = message.partition('Replacements:')
|
||||
@@ -80,15 +80,39 @@ def _replacement_log_lines(message: str, state: str) -> tuple[str, ...]:
|
||||
return ()
|
||||
for suffix in (' Display verified:', ' NC synced:', ' Saved, reopened'):
|
||||
summary = summary.partition(suffix)[0]
|
||||
status = '已保存并核验' if state == 'saved_ok' else '已替换并回读,尚未确认保存'
|
||||
lines = []
|
||||
parts = []
|
||||
for entry in summary.strip().split('; '):
|
||||
match = re.fullmatch(r'(\S+) (.+?) -> (.+)', entry.strip())
|
||||
if not match:
|
||||
return () # Preserve unfamiliar native output verbatim for diagnosis.
|
||||
refdes, old, new = match.groups()
|
||||
lines.append(f'{status} · 位号 {refdes}:{old} → {new}')
|
||||
return tuple(lines)
|
||||
parts.append(match.groups())
|
||||
return tuple(parts)
|
||||
|
||||
|
||||
def _replacement_log_lines(message: str, state: str) -> tuple[str, ...]:
|
||||
status = '已保存并核验' if state == 'saved_ok' else '已替换并回读,尚未确认保存'
|
||||
return tuple(f'{status} · 位号 {refdes}:{old} → {new}'
|
||||
for refdes, old, new in _replacement_parts(message, state))
|
||||
|
||||
|
||||
def replacement_result_rows(lines):
|
||||
rows = []
|
||||
for line in lines:
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if not isinstance(event, dict) or event.get('operation') != 'quick_run_executed':
|
||||
continue
|
||||
details = event.get('details')
|
||||
if not isinstance(details, dict):
|
||||
continue
|
||||
state = details.get('state')
|
||||
location = ':'.join(str(details.get(key) or '') for key in ('schematic_name', 'sheet_number'))
|
||||
verification = '已保存并核验' if state == 'saved_ok' else '已回读,保存待确认'
|
||||
rows.extend((location, refdes, old, new, verification)
|
||||
for refdes, old, new in _replacement_parts(str(event.get('message') or ''), state))
|
||||
return tuple(rows)
|
||||
|
||||
|
||||
def _format_task_log_lines(lines: tuple[str, ...]) -> tuple[str, ...]:
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
"""Directory task creation and optional spreadsheet/direct plan editing."""
|
||||
|
||||
from pathlib import Path
|
||||
from dataclasses import replace
|
||||
from threading import Event
|
||||
from time import monotonic
|
||||
|
||||
from PySide6.QtCore import Qt, QThreadPool, QObject, Signal, QSignalBlocker
|
||||
from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QFileDialog, QHBoxLayout, QLabel,
|
||||
QLineEdit, QListWidget, QListWidgetItem, QMessageBox, QPushButton,
|
||||
QVBoxLayout, QWidget)
|
||||
QVBoxLayout, QWidget, QToolButton, QMenu)
|
||||
|
||||
from ..errors import TaskCenterError
|
||||
from .detail_windows import BomReportDialog
|
||||
from .target_table import TargetTable
|
||||
from .workers import ServiceWorker
|
||||
|
||||
|
||||
class _OperationProgress(QObject):
|
||||
changed = Signal(str)
|
||||
|
||||
|
||||
class _ScanProgress(QObject):
|
||||
changed = Signal(object, int, int)
|
||||
|
||||
@@ -164,7 +169,14 @@ class ProjectPlanPanel(QWidget):
|
||||
self.window = window
|
||||
self.task_id = None
|
||||
self._drafts = {}
|
||||
self._bom_batches = {}
|
||||
self._orphaned_bom_batches = {}
|
||||
self._bom_reports = {}
|
||||
self._editable = False
|
||||
self._operation_stop = None
|
||||
self.stop_button = QPushButton("取消采集 / 导入", objectName="cancelInventoryOperation")
|
||||
self.stop_button.hide()
|
||||
self.stop_button.clicked.connect(self.cancel_operation)
|
||||
self.table = TargetTable(self)
|
||||
self.collect_button = QPushButton('采集所有匹配位号', objectName='collectTargetInventory')
|
||||
self.save_button = QPushButton('保存位号计划', objectName='saveTargetPlan')
|
||||
@@ -172,8 +184,9 @@ class ProjectPlanPanel(QWidget):
|
||||
self.export_button = QPushButton('导出位号计划', objectName='exportTargetPlan')
|
||||
self.import_bom_button = QPushButton('导入 BOM', objectName='importBomPlan')
|
||||
self.export_bom_button = QPushButton('BOM 模板', objectName='exportBomTemplate')
|
||||
self.select_all = QPushButton('全部替换')
|
||||
self.select_none = QPushButton('全部保留')
|
||||
self.export_bom_button.setToolTip('按本批已导入工程生成空白 BOM,无需先采集位号')
|
||||
self.select_all = QPushButton('替换当前工程')
|
||||
self.select_none = QPushButton('保留当前工程')
|
||||
self.bulk_part = QLineEdit(objectName='bulkTargetPart')
|
||||
self.bulk_part.setPlaceholderText('对选中行批量填写新料号')
|
||||
self.bulk_apply = QPushButton('填入选中行')
|
||||
@@ -185,10 +198,28 @@ class ProjectPlanPanel(QWidget):
|
||||
self.find_result = QLabel()
|
||||
self.summary = QLabel('先添加旧、新料号规则,再采集位号;可直接在这里编辑,也可选用 Excel。')
|
||||
self.summary.setWordWrap(True)
|
||||
self.report_text = ''
|
||||
self.report_dialog = None
|
||||
self.report_toggle = QToolButton(objectName='toggleBomReport')
|
||||
self.report_toggle.setCheckable(True)
|
||||
self.report_toggle.hide()
|
||||
self.report_toggle.toggled.connect(self._toggle_report)
|
||||
self.last_bom_report = None
|
||||
actions = QHBoxLayout()
|
||||
for button in (self.collect_button, self.save_button, self.import_button, self.export_button,
|
||||
self.import_bom_button, self.export_bom_button):
|
||||
for button in (self.collect_button, self.save_button, self.import_bom_button, self.export_bom_button):
|
||||
actions.addWidget(button)
|
||||
excel_menu = QMenu(self)
|
||||
for button in (self.import_button, self.export_button):
|
||||
button.setParent(self)
|
||||
button.hide()
|
||||
action = excel_menu.addAction(button.text(), button.click)
|
||||
excel_menu.aboutToShow.connect(lambda a=action, b=button: a.setEnabled(b.isEnabled()))
|
||||
self.excel_button = QToolButton()
|
||||
self.excel_button.setText('位号 Excel')
|
||||
self.excel_button.setMenu(excel_menu)
|
||||
self.excel_button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
|
||||
actions.addWidget(self.excel_button)
|
||||
actions.addWidget(self.stop_button)
|
||||
actions.addStretch()
|
||||
selection = QHBoxLayout()
|
||||
selection.addWidget(self.select_all)
|
||||
@@ -199,6 +230,7 @@ class ProjectPlanPanel(QWidget):
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addLayout(actions)
|
||||
layout.addWidget(self.summary)
|
||||
layout.addWidget(self.report_toggle)
|
||||
search = QHBoxLayout()
|
||||
for widget in (self.find_text, self.find_button, self.find_next_button,
|
||||
self.clear_find_button, self.find_result):
|
||||
@@ -222,6 +254,7 @@ class ProjectPlanPanel(QWidget):
|
||||
self.clear_find_button.clicked.connect(self.clear_find)
|
||||
|
||||
def bind_task(self, task_id, rows=None):
|
||||
self._restore_bom_report(self._report_scope(task_id))
|
||||
if self.task_id == task_id and self.table.dirty:
|
||||
return
|
||||
if self.task_id and self.table.dirty:
|
||||
@@ -241,44 +274,138 @@ class ProjectPlanPanel(QWidget):
|
||||
def find(self):
|
||||
count = self.table.set_find_text(self.find_text.text())
|
||||
self.find_result.setText(f'{count} 条匹配')
|
||||
self.select_all.setText('替换可见行' if self.find_text.text().strip() else '全部替换')
|
||||
self.select_none.setText('保留可见行' if self.find_text.text().strip() else '全部保留')
|
||||
self.select_all.setText('替换可见行' if self.find_text.text().strip() else '替换当前工程')
|
||||
self.select_none.setText('保留可见行' if self.find_text.text().strip() else '保留当前工程')
|
||||
self.table.find_next()
|
||||
|
||||
def clear_find(self):
|
||||
self.find_text.clear()
|
||||
self.table.set_find_text('')
|
||||
self.find_result.clear()
|
||||
self.select_all.setText('全部替换')
|
||||
self.select_none.setText('全部保留')
|
||||
self.select_all.setText('替换当前工程')
|
||||
self.select_none.setText('保留当前工程')
|
||||
|
||||
def has_unsaved_plan(self, task_ids):
|
||||
return any(task_id in self._drafts or
|
||||
(task_id == self.task_id and self.table.dirty) for task_id in task_ids)
|
||||
|
||||
def has_unsaved_plans(self):
|
||||
return bool(self._drafts or self._bom_batches or self._orphaned_bom_batches or self.table.dirty)
|
||||
|
||||
def prepare_save_all(self):
|
||||
# Snapshot widgets only on the GUI thread; the returned operation uses plain data.
|
||||
drafts = dict(self._drafts)
|
||||
if self.task_id and self.table.dirty:
|
||||
drafts[self.task_id] = self.table.rows()
|
||||
batches = tuple(self._bom_batches.values()) + tuple(self._orphaned_bom_batches.values())
|
||||
return lambda: self._save_all_snapshot(drafts, batches)
|
||||
|
||||
def save_all(self):
|
||||
return self.prepare_save_all()()
|
||||
|
||||
def _save_all_snapshot(self, drafts, batches):
|
||||
# Keep every draft until all writes succeed, including on a partial failure.
|
||||
pending_batches = tuple((batch, {p.task_id: drafts.get(p.task_id, p.rows)
|
||||
for p in batch.projects}) for batch in batches)
|
||||
covered = {task_id for _, rows in pending_batches for task_id in rows}
|
||||
standalone = {task_id: rows for task_id, rows in drafts.items() if task_id not in covered}
|
||||
return self.window.service.save_plan_drafts(pending_batches, standalone)
|
||||
|
||||
def forget_task(self, task_id):
|
||||
"""A confirmed permanent deletion is the only removal that discards its draft."""
|
||||
self._drafts.pop(task_id, None)
|
||||
self._bom_reports.pop(self._report_scope(task_id), None)
|
||||
self._restore_bom_report(self._report_scope(self.task_id))
|
||||
self._orphaned_bom_batches.pop(task_id, None)
|
||||
for owner, batch in tuple(self._orphaned_bom_batches.items()):
|
||||
self._orphaned_bom_batches[owner] = replace(
|
||||
batch, scope=tuple(item for item in batch.scope if item[0] != task_id))
|
||||
batches = {}
|
||||
for batch in self._bom_batches.values():
|
||||
scope = tuple(item for item in batch.scope if item[0] != task_id)
|
||||
projects = tuple(p for p in batch.projects if p.task_id != task_id)
|
||||
if projects:
|
||||
anchor = batch.anchor_task_id if batch.anchor_task_id != task_id else projects[0].task_id
|
||||
batches[tuple(x for x, _ in scope)] = replace(batch, anchor_task_id=anchor,
|
||||
scope=scope, projects=projects)
|
||||
self._bom_batches = batches
|
||||
if self.task_id == task_id:
|
||||
self.task_id = None
|
||||
self.table.populate(())
|
||||
|
||||
def discard_all(self):
|
||||
self._drafts.clear()
|
||||
self._bom_batches.clear()
|
||||
self._orphaned_bom_batches.clear()
|
||||
self.table.dirty = False
|
||||
self._release_bom_previews()
|
||||
|
||||
def _release_bom_previews(self, saved=None):
|
||||
for scope, (report, text, title) in tuple(self._bom_reports.items()):
|
||||
preview = report.preview
|
||||
if preview is not None and (saved is None or all(p.task_id in saved for p in preview.projects)):
|
||||
text = '\n'.join(text.splitlines()[:-1]) + ('\n校验通过,位号计划已保存。' if saved is not None
|
||||
else '\n本次导入预览已放弃,校验报告保留。')
|
||||
self._bom_reports[scope] = (replace(report, preview=None), text, title)
|
||||
self._restore_bom_report(self._report_scope(self.task_id))
|
||||
|
||||
def cancel_operation(self):
|
||||
if self._operation_stop is not None:
|
||||
self._operation_stop.set()
|
||||
self.stop_button.setEnabled(False)
|
||||
self.summary.setText('正在取消;等待自有 CAD 会话安全释放…')
|
||||
|
||||
def finish_operation(self):
|
||||
self._operation_stop = None
|
||||
self.stop_button.hide()
|
||||
|
||||
def _dispatch_cancellable(self, operation, callback, button):
|
||||
if self.window._workers:
|
||||
return
|
||||
stop = Event()
|
||||
self._operation_stop = stop
|
||||
progress = _OperationProgress(self)
|
||||
self._operation_progress = progress
|
||||
progress.changed.connect(self._operation_message)
|
||||
self.stop_button.show()
|
||||
self.stop_button.setEnabled(True)
|
||||
self._dispatch(lambda: operation(stop, progress.changed.emit),
|
||||
lambda result: callback(result) if not stop.is_set() else None, button)
|
||||
|
||||
def _operation_message(self, message):
|
||||
if self._operation_stop is not None and not self._operation_stop.is_set():
|
||||
self.summary.setText(message)
|
||||
|
||||
def _summary(self):
|
||||
rows = self.table.rows()
|
||||
if not rows:
|
||||
count = self.table.plan_model.rowCount()
|
||||
batch = self._active_bom_batch()
|
||||
self.save_button.setText('保存本批位号计划' if batch else '保存位号计划')
|
||||
if batch:
|
||||
self.summary.setText(f'本批 BOM 已匹配 {len(batch.projects)} 个工程;表格显示当前工程,切换任务可编辑,'
|
||||
'确认后一次保存本批位号计划。')
|
||||
return
|
||||
if not count:
|
||||
self.summary.setText('先添加旧、新料号规则,再采集位号;可直接编辑,Excel 导入导出为可选操作。')
|
||||
if rows:
|
||||
selected = sum(row.enabled for row in rows)
|
||||
if count:
|
||||
selected = self.table.plan_model.enabled_count
|
||||
suffix = ';有未保存编辑,请先保存' if self.table.dirty else ''
|
||||
self.summary.setText(f'共 {len(rows)} 个位号,替换 {selected} 个、保留 {len(rows)-selected} 个{suffix}。同步 NC 可按行勾选。')
|
||||
self.summary.setText(f'当前工程:{count} 个位号,替换 {selected} 个、保留 {count-selected} 个{suffix}。同步 NC 按行设置。')
|
||||
|
||||
def _changed(self):
|
||||
self._summary()
|
||||
self.window._update_gates()
|
||||
|
||||
def set_plan_editable(self, editable):
|
||||
def set_plan_editable(self, editable, *, busy=False):
|
||||
self._editable = bool(editable)
|
||||
self.table.set_plan_editable(self._editable)
|
||||
for widget in (self.collect_button, self.save_button, self.import_button, self.import_bom_button,
|
||||
self.select_all, self.select_none, self.bulk_part, self.bulk_apply):
|
||||
widget.setEnabled(self._editable and bool(self.task_id))
|
||||
if self._active_bom_batch():
|
||||
self.collect_button.setEnabled(False)
|
||||
self.export_button.setEnabled(self._editable and bool(self.task_id)
|
||||
and bool(self.table.rows()) and not self.table.dirty)
|
||||
self.export_bom_button.setEnabled(self._editable and bool(self.task_id)
|
||||
and bool(self.table.rows()) and not self.table.dirty)
|
||||
and bool(self.table.plan_model.rowCount()) and not self.table.dirty)
|
||||
self.export_bom_button.setEnabled(not busy)
|
||||
|
||||
def _dispatch(self, operation, callback, button):
|
||||
self.window._run_async(operation, callback, button, expected_task_id=self.task_id)
|
||||
@@ -293,7 +420,8 @@ class ProjectPlanPanel(QWidget):
|
||||
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
task_id = self.task_id
|
||||
self._dispatch(lambda: self.window.service.collect_target_inventory(task_id),
|
||||
self._dispatch_cancellable(lambda stop, progress: self.window.service.collect_target_inventory(
|
||||
task_id, stop_event=stop, on_progress=progress),
|
||||
self._saved, self.collect_button)
|
||||
|
||||
def _saved(self, rows):
|
||||
@@ -305,6 +433,13 @@ class ProjectPlanPanel(QWidget):
|
||||
def save(self):
|
||||
if not self.task_id:
|
||||
return
|
||||
batch = self._active_bom_batch()
|
||||
if batch:
|
||||
rows = {project.task_id: self.table.rows() if project.task_id == self.task_id
|
||||
else self._drafts.get(project.task_id, project.rows) for project in batch.projects}
|
||||
self._dispatch(lambda: self.window.service.save_bom_batch(batch, rows),
|
||||
self._saved_bom_batch, self.save_button)
|
||||
return
|
||||
task_id = self.task_id
|
||||
rows = self.table.rows()
|
||||
self._dispatch(lambda: self.window.service.replace_target_plan(task_id, rows),
|
||||
@@ -339,18 +474,126 @@ class ProjectPlanPanel(QWidget):
|
||||
path, _ = QFileDialog.getOpenFileName(self, '导入 BOM 模板', '', 'BOM Excel (*.xlsx)')
|
||||
if path:
|
||||
task_id = self.task_id
|
||||
self._dispatch(lambda: self.window.service.preview_bom_plan(task_id, Path(path)),
|
||||
self._preview_bom, self.import_bom_button)
|
||||
scope = self._report_scope(task_id)
|
||||
self._dispatch_cancellable(lambda stop, progress: self.window.service.inspect_bom_batch(
|
||||
task_id, Path(path), stop_event=stop, on_progress=progress),
|
||||
lambda report: self._received_bom_report(report, scope=scope), self.import_bom_button)
|
||||
|
||||
def _preview_bom(self, rows):
|
||||
self.table.populate(rows)
|
||||
self.table.dirty = True
|
||||
self.summary.setText(f'BOM 已匹配 {sum(row.enabled for row in rows)} 个位号;请检查预览后点击保存位号计划。')
|
||||
def _report_scope(self, task_id):
|
||||
if not task_id:
|
||||
return None
|
||||
groups = getattr(self.window, '_known_task_groups', {})
|
||||
return ('batch', groups[task_id]) if groups.get(task_id) else ('task', task_id)
|
||||
|
||||
def _toggle_report(self, visible):
|
||||
if visible:
|
||||
if self.report_dialog is None:
|
||||
dialog = BomReportDialog(self)
|
||||
self.report_dialog = dialog
|
||||
dialog.finished.connect(lambda _: self._report_finished(dialog))
|
||||
self.report_dialog.set_text(self.report_text)
|
||||
self.report_dialog.show()
|
||||
elif self.report_dialog is not None:
|
||||
dialog, self.report_dialog = self.report_dialog, None
|
||||
dialog.close()
|
||||
|
||||
def _report_finished(self, dialog):
|
||||
if self.report_dialog is dialog:
|
||||
self.report_dialog = None
|
||||
self.report_toggle.setChecked(False)
|
||||
|
||||
def _restore_bom_report(self, scope):
|
||||
cached = self._bom_reports.get(scope)
|
||||
self.last_bom_report = cached[0] if cached else None
|
||||
self.report_text = cached[1] if cached else ''
|
||||
self.report_toggle.setText(cached[2] if cached else '')
|
||||
self.report_toggle.setVisible(bool(cached))
|
||||
if not cached:
|
||||
self.report_toggle.setChecked(False)
|
||||
if self.report_dialog is not None:
|
||||
self.report_dialog.set_text(self.report_text)
|
||||
|
||||
def _received_bom_report(self, report, *, scope=None):
|
||||
scope = scope or self._report_scope(self.task_id)
|
||||
summary = (f'BOM 校验:共 {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]
|
||||
details.extend(f'Excel 第 {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)
|
||||
if report.preview is None:
|
||||
details.append('本次未暂存或保存任何计划;请修正后重新导入。')
|
||||
else:
|
||||
details.append('校验通过,已暂存预览;请确认后保存本批位号计划。')
|
||||
outcome = '校验未通过' if report.preview is None else '校验通过'
|
||||
title = f'本批 BOM {outcome} · 通过 {report.passed_rows} / 失败 {report.failed_rows} / 未检查 {report.unchecked_rows} 行 · 详情'
|
||||
self._bom_reports[scope] = (report, '\n'.join(details), title)
|
||||
if scope != self._report_scope(self.task_id):
|
||||
return
|
||||
self._restore_bom_report(scope)
|
||||
if report.preview is not None:
|
||||
self._preview_bom(report.preview)
|
||||
else:
|
||||
self._summary()
|
||||
|
||||
def _active_bom_batch(self):
|
||||
return next((batch for batch in (*self._bom_batches.values(), *self._orphaned_bom_batches.values())
|
||||
if any(project.task_id == self.task_id for project in batch.projects)), None)
|
||||
|
||||
def _preview_bom(self, batch):
|
||||
if self.task_id and self.table.dirty:
|
||||
self._drafts[self.task_id] = self.table.rows()
|
||||
key = tuple(task_id for task_id, _ in batch.scope)
|
||||
incoming = {project.task_id for project in batch.projects}
|
||||
# A membership change invalidates every overlapping scope. Carry forward only
|
||||
# still-present projects with the same binding, and preserve their local drafts.
|
||||
identities = dict(batch.scope)
|
||||
projects = {}
|
||||
for old_key, existing in tuple(self._bom_batches.items()):
|
||||
if set(old_key).intersection(key):
|
||||
old_identities = dict(existing.scope)
|
||||
projects.update({p.task_id: p for p in existing.projects
|
||||
if p.task_id in identities and
|
||||
old_identities.get(p.task_id) == identities[p.task_id]})
|
||||
for project in existing.projects:
|
||||
if project.task_id not in projects:
|
||||
# Draft rows alone cannot reconstruct a never-persisted inventory.
|
||||
# Keep its original scope so restore can validate the old binding.
|
||||
self._orphaned_bom_batches[project.task_id] = replace(
|
||||
existing, anchor_task_id=project.task_id, projects=(project,))
|
||||
del self._bom_batches[old_key]
|
||||
for task_id, detached in tuple(self._orphaned_bom_batches.items()):
|
||||
if task_id in identities and dict(detached.scope).get(task_id) == identities[task_id]:
|
||||
projects.setdefault(task_id, detached.projects[0])
|
||||
del self._orphaned_bom_batches[task_id]
|
||||
projects.update({project.task_id: project for project in batch.projects})
|
||||
batch = replace(batch, projects=tuple(projects[task_id] for task_id in key if task_id in projects))
|
||||
self._bom_batches[key] = batch
|
||||
for project in batch.projects:
|
||||
# A repeated import overwrites only the projects present in it.
|
||||
if project.task_id in incoming:
|
||||
self._drafts[project.task_id] = project.rows
|
||||
if self.task_id in self._drafts:
|
||||
self.table.populate(self._drafts[self.task_id])
|
||||
self.table.dirty = True
|
||||
self._changed()
|
||||
|
||||
def _saved_bom_batch(self, saved):
|
||||
self._release_bom_previews(saved)
|
||||
for task_id in saved:
|
||||
self._drafts.pop(task_id, None)
|
||||
self._orphaned_bom_batches.pop(task_id, None)
|
||||
self._bom_batches = {key: batch for key, batch in self._bom_batches.items()
|
||||
if not all(project.task_id in saved for project in batch.projects)}
|
||||
if self.task_id in saved:
|
||||
self.table.populate(saved[self.task_id])
|
||||
self.window._load_task_data()
|
||||
self._summary()
|
||||
|
||||
def export_bom(self):
|
||||
if not self.task_id or self.table.dirty:
|
||||
return
|
||||
path, _ = QFileDialog.getSaveFileName(self, '导出 BOM 模板', '替换BOM模板.xlsx', 'Excel (*.xlsx)')
|
||||
if path:
|
||||
task_id = self.task_id
|
||||
|
||||
@@ -1,15 +1,43 @@
|
||||
"""Read-only identity and result of the task's single bound project."""
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget
|
||||
from PySide6.QtWidgets import QApplication, QHBoxLayout, QLabel, QPushButton, QToolButton, QVBoxLayout, QWidget, QSizePolicy
|
||||
|
||||
|
||||
class ProjectPathLabel(QLabel):
|
||||
"""One line of context; the full path remains selectable and copyable."""
|
||||
def __init__(self):
|
||||
super().__init__(objectName='boundProjectPath')
|
||||
self.full_path = ''
|
||||
self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Fixed)
|
||||
self.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
|
||||
def setText(self, text):
|
||||
self.full_path = text
|
||||
self.setToolTip(text)
|
||||
self._elide()
|
||||
|
||||
def clear(self):
|
||||
self.setText('')
|
||||
|
||||
def text(self):
|
||||
return self.full_path
|
||||
|
||||
def resizeEvent(self, event):
|
||||
super().resizeEvent(event)
|
||||
self._elide()
|
||||
|
||||
def _elide(self):
|
||||
super().setText(self.fontMetrics().elidedText(self.full_path, Qt.TextElideMode.ElideMiddle, max(0, self.width())))
|
||||
|
||||
|
||||
class ProjectSummary(QWidget):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.name = QLabel('未选择任务')
|
||||
self.path = QLabel(objectName='boundProjectPath')
|
||||
self.path.setWordWrap(True)
|
||||
self.path.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
self.path = ProjectPathLabel()
|
||||
self.copy_path = QToolButton()
|
||||
self.copy_path.setText('复制路径')
|
||||
self.copy_path.clicked.connect(lambda: QApplication.clipboard().setText(self.path.full_path))
|
||||
self.state = QLabel()
|
||||
self.state.setWordWrap(True)
|
||||
self.refresh_button = QPushButton('重新读取工程', objectName='refreshBoundProject')
|
||||
@@ -19,7 +47,10 @@ class ProjectSummary(QWidget):
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addLayout(heading)
|
||||
layout.addWidget(self.path)
|
||||
path_row = QHBoxLayout()
|
||||
path_row.addWidget(self.path, 1)
|
||||
path_row.addWidget(self.copy_path)
|
||||
layout.addLayout(path_row)
|
||||
layout.addWidget(self.state)
|
||||
|
||||
def populate(self, context):
|
||||
@@ -38,5 +69,7 @@ class ProjectSummary(QWidget):
|
||||
else:
|
||||
labels = {'draft': '待配置', 'ready': '待执行', 'running': '执行中', 'paused': '已暂停',
|
||||
'completed': '已完成', 'failed': '失败', 'deleted': '已删除'}
|
||||
self.state.setText(f'工程已绑定 · {labels.get(context.task.status.value, context.task.status.value)}'
|
||||
+ (f' · {project.summary}' if project.summary else ''))
|
||||
progress = context.progress
|
||||
result = (f' · 已保存 {progress.saved_items} / 失败 {progress.failed_items} / 未命中 {progress.no_match_items}'
|
||||
if progress.completed_items else '')
|
||||
self.state.setText(f'当前工程 · {labels.get(context.task.status.value, context.task.status.value)}{result}')
|
||||
@@ -1,122 +0,0 @@
|
||||
"""Project selection table used by the task workspace."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtGui import QColor
|
||||
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QHeaderView, QTableWidget, QTableWidgetItem
|
||||
|
||||
|
||||
PROJECT_STATUS_TEXT = {
|
||||
"pending": "待处理",
|
||||
"capturing_before": "采集替换前",
|
||||
"awaiting_operator": "等待人工替换",
|
||||
"capturing_after": "采集替换后",
|
||||
"verifying": "正在核验",
|
||||
"completed": "已完成",
|
||||
"failed": "失败",
|
||||
"skipped": "已跳过",
|
||||
}
|
||||
|
||||
PROJECT_RESULT_TEXT = {
|
||||
"project selected for capture": "工程已进入替换前采集",
|
||||
"before profile captured": "替换前数据已采集",
|
||||
"capturing after profile": "正在采集替换后数据",
|
||||
"verifying captured profiles": "正在核验替换前后数据",
|
||||
"comparison passed": "替换核验通过",
|
||||
"project selected after resume": "继续处理此工程",
|
||||
"project selected for retry": "工程已进入重试",
|
||||
"project queued for retry": "工程已加入重试队列",
|
||||
"project skipped by operator": "工程已由操作员跳过",
|
||||
"operator stopped project before verification": "工程在核验前被操作员停止",
|
||||
"current-sheet quick-run queue completed": "图页替换队列已校验,尚未保存",
|
||||
}
|
||||
|
||||
PROJECT_STATUS_COLORS = {
|
||||
"completed": "#245b35",
|
||||
"failed": "#84251e",
|
||||
"skipped": "#5a4600",
|
||||
}
|
||||
|
||||
|
||||
class ProjectTable(QTableWidget):
|
||||
def __init__(self, on_selection_changed: Callable[[str, bool], None]) -> None:
|
||||
super().__init__(0, 5)
|
||||
self.setObjectName("projectTable")
|
||||
self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.setHorizontalHeaderLabels(("选择", "工程", "路径", "状态", "结果"))
|
||||
header = self.horizontalHeader()
|
||||
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
|
||||
header.resizeSection(0, 58)
|
||||
for section, width in ((1, 150), (2, 360), (3, 90), (4, 210)):
|
||||
header.setSectionResizeMode(section, QHeaderView.ResizeMode.Interactive)
|
||||
header.resizeSection(section, width)
|
||||
header.setStretchLastSection(True)
|
||||
self._on_selection_changed = on_selection_changed
|
||||
self._selection_enabled = True
|
||||
|
||||
def set_selection_enabled(self, enabled: bool) -> None:
|
||||
self._selection_enabled = enabled
|
||||
for row in range(self.rowCount()):
|
||||
check = self.cellWidget(row, 0)
|
||||
if check is not None:
|
||||
check.setEnabled(enabled and bool(check.property('projectAvailable')))
|
||||
|
||||
def populate(self, projects: Iterable[object]) -> None:
|
||||
vertical_position = self.verticalScrollBar().value()
|
||||
horizontal_position = self.horizontalScrollBar().value()
|
||||
current_project_id = self.current_project_id()
|
||||
self.setRowCount(0)
|
||||
current_row = -1
|
||||
for row, project in enumerate(projects):
|
||||
self.insertRow(row)
|
||||
check = QCheckBox()
|
||||
check.setChecked(bool(getattr(project, "selected")))
|
||||
check.setProperty('projectAvailable', bool(getattr(project, 'available')))
|
||||
check.setEnabled(self._selection_enabled and bool(check.property('projectAvailable')))
|
||||
project_id = str(getattr(project, "project_id"))
|
||||
check.toggled.connect(lambda checked, item_id=project_id: self._on_selection_changed(item_id, checked))
|
||||
self.setCellWidget(row, 0, check)
|
||||
name = QTableWidgetItem(str(getattr(project, "display_name")))
|
||||
name.setData(Qt.ItemDataRole.UserRole, project_id)
|
||||
self.setItem(row, 1, name)
|
||||
if project_id == current_project_id:
|
||||
current_row = row
|
||||
self.setItem(row, 2, QTableWidgetItem(str(getattr(project, "path"))))
|
||||
status = str(getattr(project, "status").value)
|
||||
status_item = QTableWidgetItem(PROJECT_STATUS_TEXT.get(status, status))
|
||||
self.setItem(row, 3, status_item)
|
||||
raw_detail = str(getattr(project, "summary"))
|
||||
detail = PROJECT_RESULT_TEXT.get(raw_detail, raw_detail)
|
||||
if raw_detail.startswith("quick_run_result:"):
|
||||
try:
|
||||
_, replaced, missed, result_detail = raw_detail.split(":", 3)
|
||||
saved, _, failure_detail = result_detail.partition("|")
|
||||
if saved == "failed":
|
||||
status = "failed"
|
||||
status_item.setText("失败")
|
||||
detail = failure_detail or "工程失败,失败原因请查看任务日志"
|
||||
elif int(replaced) == 0:
|
||||
status = "skipped"
|
||||
status_item.setText("未命中跳过")
|
||||
detail = f"未命中 {int(missed)} 项,未作替换"
|
||||
else:
|
||||
detail = f"替换校验 {int(replaced)} 项,未命中 {int(missed)} 项;" + ("已保存" if saved == "saved" else "尚未确认保存")
|
||||
except ValueError:
|
||||
detail = "结果记录格式异常,请查看证据"
|
||||
error_id = getattr(project, "error_id")
|
||||
color = PROJECT_STATUS_COLORS.get(status)
|
||||
if color is not None:
|
||||
status_item.setForeground(QColor(color))
|
||||
self.setItem(row, 4, QTableWidgetItem(f"{error_id or ''} {detail}".strip()))
|
||||
self.resizeRowsToContents()
|
||||
if current_row >= 0:
|
||||
self.setCurrentCell(current_row, 1)
|
||||
self.verticalScrollBar().setValue(vertical_position)
|
||||
self.horizontalScrollBar().setValue(horizontal_position)
|
||||
|
||||
def current_project_id(self) -> str | None:
|
||||
item = self.item(self.currentRow(), 1)
|
||||
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
|
||||
@@ -1,9 +1,14 @@
|
||||
"""Explicit single-task execution, recovery and safe pause controls."""
|
||||
from PySide6.QtCore import Signal
|
||||
from PySide6.QtWidgets import (QCheckBox, QHBoxLayout, QLabel, QProgressBar,
|
||||
QPushButton, QPlainTextEdit, QToolButton, QVBoxLayout, QWidget)
|
||||
QPushButton, QToolButton, QVBoxLayout, QWidget)
|
||||
|
||||
from .detail_windows import TaskLogDialog
|
||||
|
||||
|
||||
class RunPanel(QWidget):
|
||||
log_created = Signal(object)
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.queue_summary = QLabel('未选择任务', objectName='queueSummary')
|
||||
@@ -20,32 +25,20 @@ class RunPanel(QWidget):
|
||||
self.stop_queue_button = QPushButton('完成当前项后暂停', objectName='stopQueueButton')
|
||||
self.retry_button = QPushButton('重试失败项', objectName='retryTaskItems')
|
||||
self.recover_button = QPushButton('核验并恢复', objectName='recoverQuickRunButton')
|
||||
self.copy_value_check = QCheckBox('替换后将 Part Label 写入 Value', objectName='copyPartNumberToValue')
|
||||
self.new_round_button = QPushButton('开始新一轮', objectName='startNewRoundButton')
|
||||
self.history_button = QPushButton('查看轮次证据', objectName='roundHistoryButton')
|
||||
self.copy_value_check = QCheckBox('Value 策略:替换后将 Part Label 写入 Value(逐行自定义优先)', objectName='copyPartNumberToValue')
|
||||
self.copy_value_check.setToolTip('每行自定义 Value 优先;同步 NC 由每行开关控制。开始执行后选项冻结。')
|
||||
self.toggle_log_button = QToolButton(objectName='toggleLogButton')
|
||||
self.toggle_log_button.setText('显示日志')
|
||||
self.toggle_log_button.setText('替换结果 / 日志')
|
||||
self.toggle_log_button.setCheckable(True)
|
||||
self.reset_layout_button = QToolButton(objectName='resetLayoutButton')
|
||||
self.reset_layout_button.setText('重置布局')
|
||||
self.log_view = QPlainTextEdit(objectName='logView')
|
||||
self.log_view.setReadOnly(True)
|
||||
self.log_view.setMinimumHeight(60)
|
||||
self.log_view.hide()
|
||||
self.older_log_button = QPushButton('上一页日志', objectName='olderTaskLog')
|
||||
self.latest_log_button = QPushButton('最新日志', objectName='latestTaskLog')
|
||||
self.log_page_status = QLabel()
|
||||
self.log_navigation = QWidget()
|
||||
log_actions = QHBoxLayout(self.log_navigation)
|
||||
log_actions.setContentsMargins(0, 0, 0, 0)
|
||||
for widget in (self.older_log_button, self.latest_log_button, self.log_page_status):
|
||||
log_actions.addWidget(widget)
|
||||
log_actions.addStretch()
|
||||
self.log_navigation.hide()
|
||||
self.toggle_log_button.toggled.connect(self.log_view.setVisible)
|
||||
self.toggle_log_button.toggled.connect(self.log_navigation.setVisible)
|
||||
self.toggle_log_button.toggled.connect(lambda on: self.toggle_log_button.setText('收起日志' if on else '显示日志'))
|
||||
self.log_dialog = None
|
||||
self.toggle_log_button.toggled.connect(self._toggle_log)
|
||||
buttons = QHBoxLayout()
|
||||
for button in (self.quick_run_button, self.retry_button, self.recover_button, self.stop_queue_button):
|
||||
for button in (self.quick_run_button, self.retry_button, self.recover_button,
|
||||
self.new_round_button, self.history_button, self.stop_queue_button):
|
||||
buttons.addWidget(button)
|
||||
buttons.addStretch()
|
||||
buttons.addWidget(self.toggle_log_button)
|
||||
@@ -53,8 +46,24 @@ class RunPanel(QWidget):
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
for widget in (self.queue_summary, self.execution_status, self.busy_indicator,
|
||||
self.operator_band, self.copy_value_check):
|
||||
self.operator_band):
|
||||
layout.addWidget(widget)
|
||||
layout.addLayout(buttons)
|
||||
layout.addWidget(self.log_view, 1)
|
||||
layout.addWidget(self.log_navigation)
|
||||
|
||||
def _toggle_log(self, visible):
|
||||
self.toggle_log_button.setText('收起结果' if visible else '替换结果 / 日志')
|
||||
if visible:
|
||||
if self.log_dialog is None:
|
||||
dialog = TaskLogDialog(self)
|
||||
self.log_dialog = dialog
|
||||
dialog.finished.connect(lambda _: self._log_finished(dialog))
|
||||
self.log_created.emit(dialog)
|
||||
self.log_dialog.show()
|
||||
elif self.log_dialog is not None:
|
||||
dialog, self.log_dialog = self.log_dialog, None
|
||||
dialog.close()
|
||||
|
||||
def _log_finished(self, dialog):
|
||||
if self.log_dialog is dialog:
|
||||
self.log_dialog = None
|
||||
self.toggle_log_button.setChecked(False)
|
||||
@@ -4,7 +4,7 @@ APP_STYLESHEET = """
|
||||
QWidget { background: #f4f6f8; color: #17212b; font-size: 13px; }
|
||||
QLabel#taskSectionTitle { color: #5d6873; font-size: 12px; font-weight: 600; padding: 2px 4px; }
|
||||
QWidget#taskNavigation, QWidget#workspace, QTextEdit { background: #ffffff; border: 1px solid #cbd5df; }
|
||||
QPushButton, QComboBox, QLineEdit, QTableWidget { border: 1px solid #aebdca; border-radius: 4px; background: #ffffff; }
|
||||
QPushButton, QComboBox, QLineEdit, QTableView { border: 1px solid #aebdca; border-radius: 6px; background: #ffffff; }
|
||||
QPushButton { min-height: 30px; padding: 2px 9px; }
|
||||
QPushButton:hover { background: #edf4fa; }
|
||||
QPushButton:disabled { color: #81909c; background: #e8edf1; }
|
||||
@@ -15,11 +15,12 @@ QPushButton#deleteTaskButton, QPushButton#deleteMappingButton { color: #9f2018;
|
||||
QPushButton#deleteTaskButton:hover, QPushButton#deleteMappingButton:hover { background: #fff0ee; }
|
||||
QPushButton#deleteTaskButton:disabled, QPushButton#deleteMappingButton:disabled { color: #81909c; border-color: #cbd5df; background: #e8edf1; }
|
||||
QLineEdit, QComboBox { min-height: 28px; padding: 0 6px; }
|
||||
QTableWidget { gridline-color: #d8e0e7; selection-background-color: #dbeeff; selection-color: #17212b; }
|
||||
QTableView { gridline-color: #e4e9ee; selection-background-color: #e0edfa; selection-color: #17212b; alternate-background-color: #f8fafc; }
|
||||
QHeaderView::section { background: #e8edf1; border: 0; border-bottom: 1px solid #cbd5df; padding: 5px; font-weight: 600; }
|
||||
QListWidget { background: #ffffff; border: 1px solid #cbd5df; }
|
||||
QListWidget::item { padding: 8px 10px; border-radius: 6px; margin: 2px 0; }
|
||||
QListWidget::item:selected { background: #dbeeff; color: #17212b; }
|
||||
QListWidget::item:selected { background: #e0edfa; color: #17212b; border: 1px solid #b4cce6; }
|
||||
QListWidget::item:hover:!selected { background: #f1f5f9; }
|
||||
QLabel#operatorBand { background: #fff8d9; border: 1px solid #dfbf4b; padding: 7px; color: #5a4600; }
|
||||
QLabel#operatorBand[state="success"] { background: #edf8f1; border-color: #71a982; color: #245b35; }
|
||||
QLabel#operatorBand[state="error"] { background: #fff0ee; border-color: #d58b84; color: #84251e; }
|
||||
|
||||
@@ -3,7 +3,7 @@ from dataclasses import replace
|
||||
from PySide6.QtCore import QAbstractTableModel, QModelIndex, QSortFilterProxyModel, Qt, Signal
|
||||
from PySide6.QtWidgets import QAbstractItemView, QHeaderView, QTableView
|
||||
|
||||
HEADERS = ('替换', '原理图', '图页', '位号', '旧料号', '原 Value', '新料号', '自定义 Value', '新 Value', '同步 NC')
|
||||
HEADERS = ('替换', '原理图', '图页', '位号', '旧料号', '原 Value', '新料号', '自定义 Value', '自定义内容', '同步 NC')
|
||||
CHECK_FIELDS = {0: 'enabled', 7: 'custom_value_enabled', 9: 'sync_nc'}
|
||||
TEXT_FIELDS = {6: 'new_part_number', 8: 'custom_value'}
|
||||
|
||||
@@ -12,6 +12,7 @@ class TargetPlanModel(QAbstractTableModel):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.rows = []
|
||||
self.enabled_count = 0
|
||||
self.search_text = []
|
||||
self.editable = True
|
||||
@staticmethod
|
||||
@@ -22,6 +23,7 @@ class TargetPlanModel(QAbstractTableModel):
|
||||
def populate(self, rows):
|
||||
self.beginResetModel()
|
||||
self.rows = list(rows)
|
||||
self.enabled_count = sum(row.enabled for row in self.rows)
|
||||
self.search_text = [self.searchable(row) for row in self.rows]
|
||||
self.endResetModel()
|
||||
def rowCount(self, parent=QModelIndex()):
|
||||
@@ -68,6 +70,7 @@ class TargetPlanModel(QAbstractTableModel):
|
||||
updated = replace(self.rows[number], **change)
|
||||
if updated == self.rows[number]:
|
||||
return False
|
||||
self.enabled_count += int(updated.enabled) - int(self.rows[number].enabled)
|
||||
self.rows[number] = updated
|
||||
self.search_text[number] = self.searchable(updated)
|
||||
self.dataChanged.emit(index, index, [role, Qt.ItemDataRole.DisplayRole])
|
||||
@@ -83,6 +86,7 @@ class TargetPlanModel(QAbstractTableModel):
|
||||
for number in numbers:
|
||||
updated = replace(self.rows[number], **{field: value})
|
||||
if updated != self.rows[number]:
|
||||
self.enabled_count += int(updated.enabled) - int(self.rows[number].enabled)
|
||||
self.rows[number] = updated
|
||||
self.search_text[number] = self.searchable(updated)
|
||||
changed.append(number)
|
||||
@@ -108,11 +112,15 @@ class TargetTable(QTableView):
|
||||
self.proxy = TargetFilter(self)
|
||||
self.proxy.setSourceModel(self.plan_model)
|
||||
self.setModel(self.proxy)
|
||||
self.setSortingEnabled(True)
|
||||
self.sortByColumn(-1, Qt.SortOrder.AscendingOrder)
|
||||
self.setAlternatingRowColors(True)
|
||||
self.setMinimumHeight(160)
|
||||
self.setEditTriggers(QAbstractItemView.EditTrigger.DoubleClicked | QAbstractItemView.EditTrigger.EditKeyPressed)
|
||||
self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
|
||||
self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||
for col, width in enumerate((55, 90, 50, 70, 160, 130, 160, 90, 130, 75)):
|
||||
for col, width in enumerate((55, 90, 50, 70, 145, 115, 145, 90, 125, 75)):
|
||||
self.setColumnWidth(col, width)
|
||||
self.dirty = False
|
||||
self._next_match = -1
|
||||
@@ -129,12 +137,6 @@ class TargetTable(QTableView):
|
||||
def rowCount(self):
|
||||
return self.proxy.rowCount()
|
||||
|
||||
def item(self, row, column):
|
||||
"""Compatibility cell adapter for the original QTableWidget tests/UI hooks."""
|
||||
index = self.proxy.index(row, column)
|
||||
if not index.isValid():
|
||||
return None
|
||||
return _CellAdapter(self, index)
|
||||
def set_plan_editable(self, editable):
|
||||
if self.plan_model.editable != bool(editable):
|
||||
self.plan_model.editable = bool(editable)
|
||||
@@ -163,23 +165,3 @@ class TargetTable(QTableView):
|
||||
def apply_to_selected(self, new_part_number):
|
||||
source_rows = [self.proxy.mapToSource(index).row() for index in self.selectionModel().selectedRows()]
|
||||
self.plan_model.apply_changes(source_rows, 6, str(new_part_number).strip(), Qt.ItemDataRole.EditRole)
|
||||
|
||||
|
||||
class _CellAdapter:
|
||||
def __init__(self, table, index):
|
||||
self.table, self.index = table, index
|
||||
|
||||
def setCheckState(self, state):
|
||||
return self.table.model().setData(self.index, state, Qt.ItemDataRole.CheckStateRole)
|
||||
|
||||
def checkState(self):
|
||||
return self.table.model().data(self.index, Qt.ItemDataRole.CheckStateRole)
|
||||
|
||||
def setText(self, value):
|
||||
return self.table.model().setData(self.index, value, Qt.ItemDataRole.EditRole)
|
||||
|
||||
def text(self):
|
||||
return str(self.table.model().data(self.index, Qt.ItemDataRole.DisplayRole) or '')
|
||||
|
||||
def flags(self):
|
||||
return self.table.model().flags(self.index)
|
||||
@@ -1,28 +1,47 @@
|
||||
"""Task navigation widget with Active, Completed, and Deleted filters."""
|
||||
"""Cached task navigation; search and display sorting never reorder execution."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
import re
|
||||
from typing import Iterable
|
||||
|
||||
from PySide6.QtCore import Qt, QSignalBlocker
|
||||
from PySide6.QtWidgets import QComboBox, QGridLayout, QLabel, QListWidget, QListWidgetItem, QPushButton, QVBoxLayout, QWidget
|
||||
from PySide6.QtCore import Qt, QSignalBlocker, Signal
|
||||
from PySide6.QtWidgets import QComboBox, QGridLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem, QPushButton, QVBoxLayout, QWidget
|
||||
|
||||
|
||||
class TaskList(QWidget):
|
||||
view_changed = Signal()
|
||||
|
||||
def __init__(self, on_open: Callable[[str], None]) -> None:
|
||||
super().__init__()
|
||||
self.setObjectName("taskNavigation")
|
||||
self._tasks = ()
|
||||
self._selected_task_id = None
|
||||
self.search = QLineEdit(objectName='taskSearch')
|
||||
self.search.setPlaceholderText('搜索任务名称、目录、备注')
|
||||
self.search.setClearButtonEnabled(True)
|
||||
self.sort = QComboBox(objectName='taskSort')
|
||||
for label, key in (('执行顺序', 'execution'), ('名称 ↑', 'name_asc'), ('名称 ↓', 'name_desc'),
|
||||
('创建时间:新到旧', 'created_desc'), ('创建时间:旧到新', 'created_asc'),
|
||||
('最近更新', 'updated_desc')):
|
||||
self.sort.addItem(label, key)
|
||||
self.recycle_button = QPushButton('回收站', objectName='taskRecycleBin')
|
||||
self.recycle_button.setCheckable(True)
|
||||
self.count = QLabel(objectName='taskCount')
|
||||
self.filter = QComboBox(objectName="taskFilter")
|
||||
self.filter.addItems(("进行中", "已完成", "已删除"))
|
||||
self.filter.setVisible(False)
|
||||
self.filter.setMaximumHeight(0)
|
||||
self.list = QListWidget(objectName="taskList")
|
||||
self.list.setTextElideMode(Qt.TextElideMode.ElideRight)
|
||||
self.list.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.new_button = QPushButton("新建", objectName="newTaskButton")
|
||||
self.edit_button = QPushButton("编辑", objectName="editTaskButton")
|
||||
self.delete_button = QPushButton("删除", objectName="deleteTaskButton")
|
||||
self.restore_button = QPushButton("恢复", objectName="restoreTaskButton")
|
||||
self.queue_button = QPushButton("顺序执行本批任务", objectName="executeProjectTasks")
|
||||
self.queue_button.setToolTip('按保存的执行顺序执行本批全部任务,不受搜索和显示排序影响。')
|
||||
self.up_button = QPushButton("上移任务", objectName="moveTaskUp")
|
||||
self.down_button = QPushButton("下移任务", objectName="moveTaskDown")
|
||||
actions = QGridLayout()
|
||||
@@ -36,16 +55,52 @@ class TaskList(QWidget):
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(8, 8, 8, 8)
|
||||
layout.addWidget(QLabel('任务', objectName='taskSectionTitle'))
|
||||
layout.addWidget(self.search)
|
||||
layout.addWidget(self.sort)
|
||||
layout.addWidget(self.recycle_button)
|
||||
layout.addWidget(self.count)
|
||||
layout.addWidget(self.list, 1)
|
||||
layout.addLayout(actions)
|
||||
self.list.itemSelectionChanged.connect(lambda: on_open(self.current_task_id() or ""))
|
||||
def selected():
|
||||
self._selected_task_id = self.current_task_id()
|
||||
on_open(self._selected_task_id or '')
|
||||
self.list.itemSelectionChanged.connect(selected)
|
||||
self.search.textChanged.connect(self._render)
|
||||
self.sort.currentIndexChanged.connect(self._render)
|
||||
|
||||
def current_task_id(self) -> str | None:
|
||||
item = self.list.currentItem()
|
||||
return str(item.data(Qt.ItemDataRole.UserRole)) if item is not None else None
|
||||
|
||||
def populate(self, tasks: Iterable[object], *, selected_task_id: str | None = None) -> None:
|
||||
selected = selected_task_id or self.current_task_id()
|
||||
self._selected_task_id = selected_task_id or self.current_task_id() or self._selected_task_id
|
||||
self._tasks = tuple(tasks)
|
||||
self._render()
|
||||
|
||||
def select_task(self, task_id: str) -> None:
|
||||
if task_id != self._selected_task_id:
|
||||
self._selected_task_id = task_id
|
||||
self._render()
|
||||
|
||||
def _render(self):
|
||||
selected = self._selected_task_id
|
||||
query = self.search.text().strip().casefold().replace('\\', '/')
|
||||
tasks = [task for task in self._tasks if query in ' '.join(str(getattr(task, name, '') or '')
|
||||
for name in ('name', 'discovery_root', 'note')).casefold().replace('\\', '/')]
|
||||
mode = self.sort.currentData()
|
||||
if mode.startswith('name_'):
|
||||
tasks.sort(key=lambda task: tuple(int(part) if part.isdigit() else part
|
||||
for part in re.split(r'(\d+)', task.name.casefold())), reverse=mode == 'name_desc')
|
||||
elif mode == 'execution':
|
||||
batches = {}
|
||||
for task in self._tasks:
|
||||
key = task.group_id or task.task_id
|
||||
batches[key] = min(batches.get(key, task.created_utc), task.created_utc)
|
||||
tasks.sort(key=lambda task: (-batches[task.group_id or task.task_id].timestamp(),
|
||||
task.group_id or task.task_id, task.group_position, task.task_id))
|
||||
else:
|
||||
field = 'updated_utc' if mode == 'updated_desc' else 'created_utc'
|
||||
tasks.sort(key=lambda task: (getattr(task, field), task.task_id), reverse=mode.endswith('desc'))
|
||||
with QSignalBlocker(self.list):
|
||||
self.list.clear()
|
||||
for task in tasks:
|
||||
@@ -56,6 +111,10 @@ class TaskList(QWidget):
|
||||
'completed': '已完成', 'failed': '失败', 'deleted': '已删除'}
|
||||
item = QListWidgetItem(prefix + str(getattr(task, "name")) + f"\n{labels.get(status, status)}")
|
||||
item.setData(Qt.ItemDataRole.UserRole, str(getattr(task, "task_id")))
|
||||
item.setToolTip(f'{task.name}\n{task.discovery_root or ""}\n{task.note}'.strip())
|
||||
self.list.addItem(item)
|
||||
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 ''))
|
||||
self.view_changed.emit()
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Asynchronous paged history and incremental live logs for the selected task."""
|
||||
from PySide6.QtCore import QObject
|
||||
from PySide6.QtGui import QTextCursor
|
||||
"""Asynchronous log data, independent of disposable detail widgets."""
|
||||
from collections import deque
|
||||
|
||||
from .messages import _format_task_log_lines
|
||||
from PySide6.QtCore import QObject
|
||||
|
||||
from .messages import _format_task_log_lines, replacement_result_rows
|
||||
from .queries import LatestQuery
|
||||
|
||||
|
||||
@@ -15,12 +16,22 @@ class TaskLogPresenter(QObject):
|
||||
self.task_id = None
|
||||
self._requested_task = None
|
||||
self.cursor = self.older_cursor = None
|
||||
self.history = False
|
||||
self.initialized = False
|
||||
self.has_older = False
|
||||
self.history = self.initialized = self.has_older = False
|
||||
self._displayed_events = 0
|
||||
panel.older_log_button.clicked.connect(self.older)
|
||||
panel.latest_log_button.clicked.connect(self.latest)
|
||||
self._result_rows = ()
|
||||
self._text = ''
|
||||
self._local_lines = deque(maxlen=100)
|
||||
panel.log_created.connect(self._connect_dialog)
|
||||
|
||||
@property
|
||||
def log_text(self):
|
||||
return '\n'.join(part for part in (self._text, '\n'.join(self._local_lines)) if part)
|
||||
|
||||
def _connect_dialog(self, dialog):
|
||||
dialog.older_log_button.clicked.connect(self.older)
|
||||
dialog.latest_log_button.clicked.connect(self.latest)
|
||||
dialog.set_content(self.log_text, self._result_rows)
|
||||
self._buttons()
|
||||
|
||||
def bind(self, task_id):
|
||||
if task_id == self.task_id:
|
||||
@@ -30,26 +41,46 @@ class TaskLogPresenter(QObject):
|
||||
self.cursor = self.older_cursor = None
|
||||
self.history = self.initialized = self.has_older = False
|
||||
self._displayed_events = 0
|
||||
self.panel.log_view.clear()
|
||||
self._text, self._result_rows = '', ()
|
||||
self._local_lines.clear()
|
||||
self._render(scroll_to='bottom')
|
||||
self._buttons()
|
||||
|
||||
def pause(self):
|
||||
self.query.invalidate()
|
||||
# Reopening starts at latest; no cursor can outlive the disposed view.
|
||||
self.cursor = self.older_cursor = None
|
||||
self.history = self.initialized = self.has_older = False
|
||||
self._displayed_events = 0
|
||||
|
||||
def append_line(self, line):
|
||||
self._local_lines.append(line)
|
||||
self._render()
|
||||
|
||||
def _render(self, *, scroll_to=None):
|
||||
if self.panel.log_dialog is not None:
|
||||
self.panel.log_dialog.set_content(self.log_text, self._result_rows, scroll_to=scroll_to)
|
||||
|
||||
def _buttons(self):
|
||||
self.panel.older_log_button.setEnabled(self.has_older and not self.query.current_busy)
|
||||
self.panel.latest_log_button.setEnabled(bool(self.task_id) and not self.query.current_busy)
|
||||
dialog = self.panel.log_dialog
|
||||
if dialog is not None:
|
||||
dialog.older_log_button.setEnabled(self.has_older and not self.query.current_busy)
|
||||
dialog.latest_log_button.setEnabled(bool(self.task_id) and not self.query.current_busy)
|
||||
|
||||
def refresh(self):
|
||||
if not self.task_id or (self.query.current_busy and self._requested_task == self.task_id) or self.history:
|
||||
if (self.panel.log_dialog is None or not self.task_id
|
||||
or (self.query.current_busy and self._requested_task == self.task_id) or self.history):
|
||||
return
|
||||
# Keep live rendering bounded; older events remain available via paging.
|
||||
# Older events remain available via paging; live state stays bounded.
|
||||
self._request('poll' if self.initialized and self._displayed_events < 400 else 'latest')
|
||||
|
||||
def latest(self, *, force=False):
|
||||
if self.task_id and (force or not self.query.current_busy):
|
||||
if self.panel.log_dialog is not None and self.task_id and (force or not self.query.current_busy):
|
||||
self.history = False
|
||||
self._request('latest')
|
||||
|
||||
def older(self):
|
||||
if self.task_id and self.has_older and not self.query.current_busy:
|
||||
if self.panel.log_dialog is not None and self.task_id and self.has_older and not self.query.current_busy:
|
||||
self.history = True
|
||||
self._request('older')
|
||||
|
||||
@@ -60,35 +91,35 @@ class TaskLogPresenter(QObject):
|
||||
def read(control):
|
||||
page = self.service.read_task_log(task_id, mode=mode, cursor=cursor, limit=200, read_control=control)
|
||||
control.checkpoint()
|
||||
return page, '\n'.join(_format_task_log_lines(page.lines))
|
||||
return page, '\n'.join(_format_task_log_lines(page.lines)), replacement_result_rows(page.lines)
|
||||
def received(result):
|
||||
page, text = result
|
||||
view = self.panel.log_view
|
||||
dialog = self.panel.log_dialog
|
||||
if dialog is None:
|
||||
return
|
||||
page, text, result_rows = result
|
||||
if mode == 'poll' and not page.reset:
|
||||
if text:
|
||||
scroll = view.verticalScrollBar()
|
||||
follow = scroll.value() >= scroll.maximum() - 2
|
||||
old = scroll.value()
|
||||
position = QTextCursor(view.document())
|
||||
position.movePosition(QTextCursor.MoveOperation.End)
|
||||
position.insertText(('\n' if not view.document().isEmpty() else '') + text)
|
||||
scroll.setValue(scroll.maximum() if follow else old)
|
||||
self._text = '\n'.join(part for part in (self._text, text) if part)
|
||||
self._displayed_events += len(page.lines)
|
||||
self._result_rows = (self._result_rows + result_rows)[-500:]
|
||||
else:
|
||||
view.setPlainText(text)
|
||||
self._text = text
|
||||
self.older_cursor = page.older_cursor
|
||||
self.has_older = page.has_older
|
||||
self._displayed_events = len(page.lines)
|
||||
if mode != 'older':
|
||||
view.verticalScrollBar().setValue(view.verticalScrollBar().maximum())
|
||||
self._result_rows = result_rows
|
||||
if mode != 'older':
|
||||
self.cursor = page.cursor
|
||||
self.initialized = True
|
||||
self._render(scroll_to=('top' if mode == 'older' else
|
||||
'bottom' if mode != 'poll' or page.reset else None))
|
||||
if page.reset:
|
||||
self.panel.log_page_status.setText('日志已轮转或重建,已加载最近记录')
|
||||
dialog.log_page_status.setText('日志已轮转或重建,已加载最近记录')
|
||||
else:
|
||||
self.panel.log_page_status.setText('历史记录 · 每页 200 条' if self.history else '最近记录 · 实时追加')
|
||||
dialog.log_page_status.setText('历史记录 · 每页 200 条' if self.history else '最近记录 · 实时追加')
|
||||
def failed(error):
|
||||
self.panel.log_page_status.setText(f'日志读取失败,可点击最新日志重试:{getattr(error, "message", str(error))}')
|
||||
if self.panel.log_dialog is not None:
|
||||
self.panel.log_dialog.log_page_status.setText(
|
||||
f'日志读取失败,可点击最新日志重试:{getattr(error, "message", str(error))}')
|
||||
self.query.request(read, received, failed, cancellable=True)
|
||||
self._buttons()
|
||||
@@ -1 +1 @@
|
||||
VERSION = "1.1.1"
|
||||
VERSION = "1.1.2"
|
||||
@@ -158,8 +158,8 @@ class _OwnedWorkers:
|
||||
|
||||
|
||||
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None,
|
||||
process_factory=None) -> subprocess.CompletedProcess[str]:
|
||||
root = Path(command[3])
|
||||
process_factory=None, cooperative_abort=False) -> subprocess.CompletedProcess[str]:
|
||||
root = Path(command[3]).resolve()
|
||||
job_id = command[-1]
|
||||
token = uuid4().hex
|
||||
ready = root / f'monitor-{token}.ready'
|
||||
@@ -212,7 +212,15 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
_atomic_text(ready, token)
|
||||
while process.poll() is None:
|
||||
if abort_event is not None and abort_event.is_set():
|
||||
raise WorkerMonitorError('project session supervisor requested worker cleanup')
|
||||
if not cooperative_abort:
|
||||
raise WorkerMonitorError('project session supervisor requested worker cleanup')
|
||||
if not watch.stop_requested:
|
||||
# Read-only callers request the VBS safe boundary first.
|
||||
# The existing idle watchdog still bounds a stalled COM call.
|
||||
watch.stop_requested = True
|
||||
watch.last_progress = time.monotonic()
|
||||
_atomic_text(stop, token)
|
||||
_publish_progress(progress_path, watch.snapshot())
|
||||
try:
|
||||
receive(*messages.get(timeout=min(0.1, idle_timeout / 10)))
|
||||
for pending in range(128):
|
||||
|
||||
@@ -38,7 +38,7 @@ def test_explicit_data_root_still_overrides_frozen_portable_default(tmp_path: Pa
|
||||
assert application.resolve_data_root(override) == override.resolve()
|
||||
|
||||
|
||||
def test_main_configures_logging_before_qapplication_and_logs_recovery(tmp_path: Path, monkeypatch) -> None:
|
||||
def test_main_configures_logging_before_qapplication(tmp_path: Path, monkeypatch) -> None:
|
||||
"""Moving logging after Qt creation would lose startup and recovery diagnostics."""
|
||||
from dx_productivity.trial_task_center import application
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
@@ -53,9 +53,6 @@ def test_main_configures_logging_before_qapplication_and_logs_recovery(tmp_path:
|
||||
assert events == ["logging"]
|
||||
self.path = path
|
||||
|
||||
def recover_interrupted_work(self) -> tuple[str, ...]:
|
||||
return ("project-1",)
|
||||
|
||||
def close(self) -> None:
|
||||
events.append("closed")
|
||||
|
||||
@@ -85,7 +82,6 @@ def test_main_configures_logging_before_qapplication_and_logs_recovery(tmp_path:
|
||||
|
||||
assert application.main(["--data-root", str(tmp_path)]) == 0
|
||||
assert events == ["logging", "window", "shown", "closed"]
|
||||
assert "recovered_interrupted_projects=project-1" in context.application_log_path.read_text(encoding="utf-8")
|
||||
assert f"version={application.VERSION}" in context.application_log_path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
|
||||
@@ -60,6 +60,25 @@ def run_queue(service, task, stop=None):
|
||||
return service.execute_quick_run_queue(task.task_id, expected_item=expected, stop_event=stop or Event())
|
||||
|
||||
|
||||
def test_native_mutation_failure_stops_before_next_batch_step(tmp_path):
|
||||
service, task, calls = setup_queue(tmp_path, ('batch_failed', 'saved_ok'))
|
||||
original_worker = service._quick_run_preparer._process_runner
|
||||
def failed_after_mutation(command, timeout):
|
||||
root = Path(command[3])
|
||||
job = command[-1]
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\tawaiting_native_replace\t\tsnapshot captured\n')
|
||||
(root / f'snapshot-{job}.tsv.native.json').write_text(
|
||||
json.dumps({'ok': False, 'stage': 'pin_promotion_started'}), encoding='utf-8')
|
||||
return original_worker(command, timeout)
|
||||
service._quick_run_preparer._process_runner = failed_after_mutation
|
||||
with pytest.raises(TaskCenterError) as raised:
|
||||
run_queue(service, task)
|
||||
assert raised.value.code == 'quick_run_uncertain'
|
||||
assert len(calls) == 1
|
||||
assert (tmp_path / 'data/quick-run/uncertain.flag').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('states', [('no_match',) * 20, ('no_match', 'saved_ok', 'no_match', 'saved_ok')])
|
||||
def test_queue_continues_after_misses_and_successes(tmp_path, states):
|
||||
service, task, calls = setup_queue(tmp_path, states)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import pytest
|
||||
|
||||
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.models import TaskStatus
|
||||
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, TargetPlanRow
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def batch(tmp_path):
|
||||
root = tmp_path / 'projects'
|
||||
for name in ('a', 'b'):
|
||||
folder = root / name
|
||||
folder.mkdir(parents=True)
|
||||
(folder / 'board.prj').write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
app = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
tasks = app.create_project_tasks(root)
|
||||
yield app, store, tasks
|
||||
store.close()
|
||||
|
||||
|
||||
def values(rules):
|
||||
return [(r.old_part_number, r.new_part_number, r.enabled, r.sync_nc) for r in rules]
|
||||
|
||||
|
||||
def test_rule_crud_and_order_are_shared_across_projects(batch):
|
||||
app, store, tasks = batch
|
||||
a, b = (t.task_id for t in tasks)
|
||||
first = app.add_rule(a, 'OLD', 'NEW')
|
||||
assert values(app.rules(a)) == values(app.rules(b)) == [('OLD', 'NEW', True, True)]
|
||||
second = app.add_rule(b, 'OTHER', 'OTHER-NEW', sync_nc=False)
|
||||
app.move_rule(second.rule_id, -1)
|
||||
assert values(app.rules(a)) == values(app.rules(b))
|
||||
assert app.rules(a)[0].old_part_number == 'OTHER'
|
||||
app.update_rule(first.rule_id, old_part_number='OLD', new_part_number='NEW2', enabled=False)
|
||||
assert values(app.rules(a)) == values(app.rules(b))
|
||||
app.delete_rule(first.rule_id)
|
||||
assert values(app.rules(a)) == values(app.rules(b)) == [('OTHER', 'OTHER-NEW', True, False)]
|
||||
|
||||
|
||||
def test_rule_change_updates_execution_defaults_but_keeps_manual_fields_and_selection(batch):
|
||||
app, store, tasks = batch
|
||||
rule = app.add_rule(tasks[0].task_id, 'OLD', 'NEW1')
|
||||
for task in tasks:
|
||||
path = store.list_projects(task.task_id)[0].path
|
||||
targets = tuple(ComponentTarget(path, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', 'V0') for i in (1, 2, 3))
|
||||
store.record_target_inventory(task.task_id, targets)
|
||||
store.replace_target_plan(task.task_id, (
|
||||
TargetPlanRow(targets[0], True, 'NEW1'),
|
||||
TargetPlanRow(targets[1], True, 'MANUAL', True, 'custom', False),
|
||||
TargetPlanRow(targets[2], False, 'NEW1'),
|
||||
))
|
||||
app.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW2', enabled=True,
|
||||
custom_value_enabled=True, custom_value='rule value', sync_nc=False)
|
||||
for task in tasks:
|
||||
rows = app.target_plan(task.task_id)
|
||||
assert [(r.enabled, r.new_part_number) for r in rows] == [(True, 'NEW2'), (True, 'MANUAL'), (False, 'NEW2')]
|
||||
assert rows[0].custom_value == 'rule value' and not rows[0].sync_nc
|
||||
assert rows[1].custom_value == 'custom' and not rows[1].sync_nc
|
||||
effective = app._execution_rules(task.task_id)
|
||||
assert {r.new_part_number for r in effective} == {'NEW2', 'MANUAL'}
|
||||
assert app.task_context(task.task_id).targets == rows
|
||||
|
||||
|
||||
def test_frozen_sibling_rejects_entire_rule_mutation(batch):
|
||||
app, store, tasks = batch
|
||||
rule = app.add_rule(tasks[0].task_id, 'OLD', 'NEW1')
|
||||
store.set_task_status(tasks[1].task_id, TaskStatus.READY)
|
||||
store.set_task_status(tasks[1].task_id, TaskStatus.RUNNING)
|
||||
before = {t.task_id: app.rules(t.task_id) for t in tasks}
|
||||
with pytest.raises(TaskCenterError):
|
||||
app.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW2', enabled=True)
|
||||
assert before == {t.task_id: app.rules(t.task_id) for t in tasks}
|
||||
|
||||
|
||||
def test_failure_on_sibling_rolls_back_rules_and_target_defaults(batch, monkeypatch):
|
||||
app, store, tasks = batch
|
||||
rule = app.add_rule(tasks[0].task_id, 'OLD', 'NEW1')
|
||||
path = store.list_projects(tasks[0].task_id)[0].path
|
||||
target = ComponentTarget(path, 'MAIN', '1', 'u', 'R1', 'OLD', '')
|
||||
store.record_target_inventory(tasks[0].task_id, (target,))
|
||||
store.replace_target_plan(tasks[0].task_id, (TargetPlanRow(target, True, 'NEW1'),))
|
||||
original = store.update_rule
|
||||
def fail(rule_id, **kwargs):
|
||||
if store.get_rule(rule_id).task_id == tasks[1].task_id:
|
||||
raise TaskCenterError('injected', 'sibling write failed')
|
||||
return original(rule_id, **kwargs)
|
||||
monkeypatch.setattr(store, 'update_rule', fail)
|
||||
with pytest.raises(TaskCenterError, match='sibling write failed'):
|
||||
app.update_rule(rule.rule_id, old_part_number='OLD', new_part_number='NEW2', enabled=True)
|
||||
assert all(app.rules(t.task_id)[0].new_part_number == 'NEW1' for t in tasks)
|
||||
assert app.target_plan(tasks[0].task_id)[0].new_part_number == 'NEW1'
|
||||
|
||||
|
||||
def test_legacy_group_disagreement_is_reported_instead_of_silent_partial_edit(batch):
|
||||
app, store, tasks = batch
|
||||
first = store.add_rule(tasks[0].task_id, 'OLD', 'A')
|
||||
store.add_rule(tasks[1].task_id, 'OLD', 'B')
|
||||
with pytest.raises(TaskCenterError, match='不一致'):
|
||||
app.add_rule(tasks[0].task_id, 'OTHER', 'NEW')
|
||||
# Editing the conflicting mapping explicitly resolves that old-number rule.
|
||||
app.update_rule(first.rule_id, old_part_number='OLD', new_part_number='C', enabled=True)
|
||||
assert all(app.rules(t.task_id)[0].new_part_number == 'C' for t in tasks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('last_target, code', [('NEW', 'mapping_chain'), ('OLD', 'mapping_cycle')])
|
||||
def test_legacy_rule_union_is_validated_before_execution_and_collection(batch, last_target, code):
|
||||
app, store, tasks = batch
|
||||
store.add_rule(tasks[0].task_id, 'OLD', 'MID')
|
||||
store.add_rule(tasks[1].task_id, 'MID', last_target)
|
||||
# Display remains available so a historical conflict can be corrected.
|
||||
assert len(app.rules(tasks[0].task_id)) == 2
|
||||
for task in tasks:
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
app._execution_rules(task.task_id)
|
||||
assert error.value.code == code
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
app.collect_target_inventory(task.task_id)
|
||||
assert error.value.code == code
|
||||
|
||||
|
||||
@pytest.mark.parametrize('action', ['disable', 'delete'])
|
||||
def test_historical_chain_can_be_resolved_through_normal_rule_edit(batch, action):
|
||||
app, store, tasks = batch
|
||||
store.add_rule(tasks[0].task_id, 'OLD', 'MID')
|
||||
selected = store.add_rule(tasks[1].task_id, 'MID', 'NEW')
|
||||
if action == 'disable':
|
||||
updated = app.update_rule(selected.rule_id, old_part_number='MID', new_part_number='NEW', enabled=False)
|
||||
assert updated.rule_id == selected.rule_id
|
||||
else:
|
||||
app.delete_rule(selected.rule_id)
|
||||
assert values(app.rules(tasks[0].task_id)) == values(app.rules(tasks[1].task_id))
|
||||
assert all([r.old_part_number for r in app._execution_rules(t.task_id) if r.enabled] == ['OLD'] for t in tasks)
|
||||
@@ -0,0 +1,218 @@
|
||||
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()
|
||||
@@ -0,0 +1,157 @@
|
||||
from dataclasses import replace
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
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.bom_import_report import inspect_batch
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
def test_reports_independent_excel_errors_without_collecting_or_partial_preview(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
records = list(records_for(tasks, targets))
|
||||
records.extend([dict(records[0], new_part_number='', refdes='R2'),
|
||||
dict(records[1], new_part_number='=1+1')])
|
||||
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'bad.xlsx', records))
|
||||
assert (report.total_rows, report.passed_rows, report.failed_rows, report.unchecked_rows) == (4, 0, 2, 2)
|
||||
assert [row.excel_row for row in report.rows if row.status == 'failed'] == [4, 5]
|
||||
assert report.preview is None and not calls
|
||||
assert all(not store.list_target_plan(task.task_id) for task in tasks)
|
||||
|
||||
|
||||
def test_reports_all_matching_errors_and_success_is_read_only(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
records = list(records_for(tasks, targets))
|
||||
records[0]['refdes'] = 'R9'
|
||||
records[1]['refdes'] = 'R8'
|
||||
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'bad.xlsx', records))
|
||||
assert report.failed_rows == 2 and report.failed_projects == 2 and report.preview is None
|
||||
assert all(row.project_path and row.reason for row in report.rows)
|
||||
report = inspect_batch(service, tasks[0].task_id,
|
||||
write_bom_template(tmp_path / 'good.xlsx', records_for(tasks, targets)))
|
||||
assert report.passed_rows == 2 and report.passed_projects == 2 and report.preview
|
||||
assert all(not store.list_target_plan(task.task_id) for task in tasks)
|
||||
|
||||
|
||||
def test_duplicate_marks_both_rows_and_cross_row_chain_rejected(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
record = records_for(tasks, targets)[0]
|
||||
report = inspect_batch(service, tasks[0].task_id,
|
||||
write_bom_template(tmp_path / 'dup.xlsx', [record, record]))
|
||||
assert report.failed_rows == 2 and report.preview is None
|
||||
target = targets[tasks[0].task_id][1]
|
||||
targets[tasks[0].task_id] = (targets[tasks[0].task_id][0], replace(target, old_part_number='NEW-0'))
|
||||
report = inspect_batch(service, tasks[0].task_id, write_bom_template(tmp_path / 'chain.xlsx',
|
||||
[record, dict(record, old_part_number='NEW-0', new_part_number='NEXT', refdes='R2')]))
|
||||
assert report.failed_rows == 2 and report.preview is None
|
||||
|
||||
|
||||
def test_cancel_and_native_cleanup_errors_propagate_without_next_project(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets))
|
||||
stop = Event()
|
||||
stop.set()
|
||||
with pytest.raises(TaskCenterError, match='取消'):
|
||||
inspect_batch(service, tasks[0].task_id, path, stop_event=stop)
|
||||
assert not calls
|
||||
def unsafe(*args, **kwargs):
|
||||
raise TaskCenterError('native_cleanup', 'cleanup failed')
|
||||
service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = unsafe
|
||||
with pytest.raises(TaskCenterError, match='cleanup failed'):
|
||||
inspect_batch(service, tasks[0].task_id, path)
|
||||
assert not calls
|
||||
|
||||
|
||||
|
||||
def test_cancellation_after_reader_prevents_opening_next_project(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
stop = Event()
|
||||
path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets))
|
||||
def cancel_after_read(*args, **kwargs):
|
||||
calls.append(tasks[0].task_id)
|
||||
stop.set()
|
||||
return targets[tasks[0].task_id]
|
||||
service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = cancel_after_read
|
||||
with pytest.raises(TaskCenterError, match='取消'):
|
||||
inspect_batch(service, tasks[0].task_id, path, stop_event=stop)
|
||||
assert calls == [tasks[0].task_id]
|
||||
assert all(not store.list_target_plan(task.task_id) for task in tasks)
|
||||
|
||||
|
||||
def test_scaffolds_skipped_but_header_and_bool_errors_report_excel_rows(batch, tmp_path):
|
||||
from openpyxl import load_workbook
|
||||
service, store, tasks, targets, calls = batch
|
||||
path = service.export_bom_template(tasks[0].task_id, tmp_path / 'scaffold.xlsx')
|
||||
report = inspect_batch(service, tasks[0].task_id, path)
|
||||
assert report.total_rows == 0 and report.preview is None and report.errors and not calls
|
||||
path = write_bom_template(tmp_path / 'bool.xlsx', [dict(records_for(tasks, targets)[0], enabled='maybe')])
|
||||
report = inspect_batch(service, tasks[0].task_id, path)
|
||||
assert report.rows[0].excel_row == 2 and report.failed_rows == 1 and 'TRUE/FALSE' in report.rows[0].reason
|
||||
workbook = load_workbook(path)
|
||||
workbook.active['C1'] = 'wrong header'
|
||||
workbook.save(path)
|
||||
workbook.close()
|
||||
report = inspect_batch(service, tasks[0].task_id, path)
|
||||
assert report.failed_rows == 1 and '第 1 行' in report.errors[0] and not calls
|
||||
|
||||
|
||||
def test_strict_preview_rejects_corrupt_workbook_with_domain_error(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
path = tmp_path / 'corrupt.xlsx'
|
||||
path.write_bytes(b'not an Excel zip')
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
service.preview_bom_batch(tasks[0].task_id, path)
|
||||
assert caught.value.code == 'bom_import'
|
||||
assert not calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize('strict', [False, True])
|
||||
def test_cancellation_during_excel_parsing_keeps_operation_cancelled(batch, tmp_path, monkeypatch, strict):
|
||||
from dx_productivity.trial_task_center import bom_import_report
|
||||
service, store, tasks, targets, calls = batch
|
||||
stop = Event()
|
||||
path = write_bom_template(tmp_path / 'cancel-while-reading.xlsx', records_for(tasks, targets))
|
||||
parse = bom_import_report.parse_bom_row
|
||||
def cancel_after_first_row(*args):
|
||||
record = parse(*args)
|
||||
stop.set()
|
||||
return record
|
||||
monkeypatch.setattr(bom_import_report, 'parse_bom_row', cancel_after_first_row)
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
if strict:
|
||||
service.preview_bom_batch(tasks[0].task_id, path, stop_event=stop)
|
||||
else:
|
||||
service.inspect_bom_batch(tasks[0].task_id, path, stop_event=stop)
|
||||
assert caught.value.code == 'operation_cancelled'
|
||||
assert not calls
|
||||
assert all(not store.list_target_plan(task.task_id) for task in tasks)
|
||||
|
||||
|
||||
def test_ui_report_is_persistent_and_failure_does_not_stage(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
|
||||
# Exercise the real async import callback without any blocking message box.
|
||||
monkeypatch.setattr(service, 'inspect_bom_batch', lambda *args, **kwargs: inspect_batch(
|
||||
service, *args, **kwargs), raising=False)
|
||||
records = list(records_for(tasks, targets))
|
||||
records[1]['new_part_number'] = ''
|
||||
path = write_bom_template(tmp_path / 'bad-ui.xlsx', records)
|
||||
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)
|
||||
panel = window.plan_panel
|
||||
assert panel.last_bom_report.failed_rows == 1
|
||||
assert 'Excel 第 3 行' in panel.report_text
|
||||
assert '未检查 1 行' in panel.report_text
|
||||
assert not panel._bom_batches and not panel._drafts and not calls
|
||||
panel._summary()
|
||||
assert '失败 1 行' in panel.report_text
|
||||
assert all(not store.list_target_plan(task.task_id) for task in tasks)
|
||||
window.close()
|
||||
@@ -0,0 +1,49 @@
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
from dx_productivity.trial_task_center.bom_plan import BOM_HEADERS, read_bom_records
|
||||
from tools.convert_cbb_bom import convert
|
||||
|
||||
|
||||
def test_cbb_conversion_preserves_completed_rows_and_isolates_conflicts(tmp_path):
|
||||
source = tmp_path / 'source.xlsx'
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = '结果'
|
||||
headers = ['文件名', 'QTY', 'REFDES', 'VALUE'] + [f'column{i}' for i in range(5, 27)]
|
||||
for index, name in {10: '旧料号', 13: '更换为新料号', 22: '更换物料料号', 24: '是否更换完毕'}.items():
|
||||
headers[index - 1] = name
|
||||
sheet.append(headers)
|
||||
for name, proposal, history, completed in (
|
||||
('Board', '4300-NEW-A100', '4300-NEW-A100', 'Y'),
|
||||
('Board', '431R-NEW-A100', '4300-OTHER-A100', ''),
|
||||
('Missing', '4300-NEW-A100', '', ''),
|
||||
('Board', '不可更换', '4300-NEW-A100', ''),
|
||||
):
|
||||
row = [''] * 26
|
||||
for index, value in {0: name, 1: 1, 2: f'R{sheet.max_row}', 3: '100nF/NC',
|
||||
9: '4300-OLD-A100', 12: proposal, 21: history, 23: completed}.items():
|
||||
row[index] = value
|
||||
sheet.append(row)
|
||||
workbook.save(source)
|
||||
project = tmp_path / 'Board.prj'
|
||||
report = convert(source, (project,), tmp_path / 'converted')
|
||||
full = read_bom_records(Path(report['full_file']))
|
||||
ready = read_bom_records(Path(report['mapped_file']))
|
||||
assert len(full) == 3 and len(ready) == 2
|
||||
assert ready[0].enabled # Completion markers are preserved, not used to remove rules.
|
||||
assert not ready[1].enabled
|
||||
assert ready[1].new == '431R-NEW-A100'
|
||||
assert all(not r.custom and r.sync_nc for r in full)
|
||||
assert report['source_rows'] == 4 and report['conflict_rows'] == 1
|
||||
workbook = load_workbook(report['mapped_file'])
|
||||
assert tuple(cell.value for cell in workbook.active[1]) == BOM_HEADERS
|
||||
assert 'Y' in workbook.active['D2'].comment.text
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_cbb_conversion_does_not_guess_a_path_for_duplicate_project_names(tmp_path):
|
||||
from tools.convert_cbb_bom import project_index
|
||||
index = project_index((tmp_path / 'left' / 'Board.prj', tmp_path / 'right' / 'Board.prj'))
|
||||
assert len(index['board']) == 2
|
||||
@@ -0,0 +1,20 @@
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import isolated_cad
|
||||
|
||||
|
||||
@pytest.mark.parametrize('as_property', [True, False])
|
||||
def test_private_quit_accepts_property_or_method_project_path(monkeypatch, tmp_path, as_property):
|
||||
import win32com.client
|
||||
data = SimpleNamespace(GetProjectFilePath='' if as_property else lambda: '')
|
||||
quit_calls = []
|
||||
app = SimpleNamespace(GetProjectData=lambda: data, Quit=lambda: quit_calls.append(1))
|
||||
monkeypatch.setattr(win32com.client, 'GetActiveObject', lambda _: app)
|
||||
monkeypatch.setattr(isolated_cad, 'current_desktop_name', lambda: 'dx-' + 'a' * 32)
|
||||
monkeypatch.setattr(isolated_cad, 'verify_application', lambda *args, **kwargs: None)
|
||||
for name, value in {'DXPART_DESKTOP': 'dx-' + 'a' * 32, 'DXPART_SESSION_TOKEN': 'a' * 32,
|
||||
'DXPART_CAD_PID': '123', 'DXPART_CAD_GUID': 'guid'}.items():
|
||||
monkeypatch.setenv(name, value)
|
||||
assert isolated_cad.native_action('quit', tmp_path / 'unused.json', 123) == 0
|
||||
assert quit_calls == [1]
|
||||
@@ -320,6 +320,75 @@ def test_initially_unverifiable_project_uses_fresh_discovery_without_cache(tmp_p
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_projectbackup_audit_updates_do_not_rediscover(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
original = preparer._discover_project_sheets
|
||||
def discover(*args, **kwargs):
|
||||
log = project.parent / 'Log Files' / 'ProjectBackupLog.txt'
|
||||
log.parent.mkdir(exist_ok=True)
|
||||
log.write_text('automatic backup audit')
|
||||
backup = project.parent / 'ProjectBackup' / 'backups' / 'auto.zip'
|
||||
backup.parent.mkdir(parents=True, exist_ok=True)
|
||||
backup.write_bytes(b'generated backup')
|
||||
return original(*args, **kwargs)
|
||||
preparer._discover_project_sheets = discover
|
||||
preparer.discover_project(project, ('old',))
|
||||
preparer.discover_project(project, ('old',))
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_native_database_runtime_updates_require_repeated_equal_inventory(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
database = project.parent / 'database' / 'icdb.dat'
|
||||
database.parent.mkdir()
|
||||
database.write_text('initial database')
|
||||
original = preparer._discover_project_sheets
|
||||
def discover(*args, **kwargs):
|
||||
result = original(*args, **kwargs)
|
||||
database.write_text('native session metadata ' + str(len(calls)))
|
||||
return result
|
||||
preparer._discover_project_sheets = discover
|
||||
assert preparer.collect_inventory(project, ('old',))[0].refdes == 'R1'
|
||||
assert len(calls) == 2
|
||||
preparer.collect_inventory(project, ('old',))
|
||||
assert len(calls) == 2
|
||||
database.write_text('external database edit')
|
||||
preparer.collect_inventory(project, ('old',))
|
||||
assert len(calls) == 4 # Database content remains part of cache invalidation.
|
||||
|
||||
|
||||
def test_native_database_runtime_updates_reject_different_inventories(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
database = project.parent / 'database' / 'icdb.dat'
|
||||
database.parent.mkdir()
|
||||
database.write_text('initial database')
|
||||
def discover(path, parts, *, collect_components=False):
|
||||
calls.append(parts)
|
||||
database.write_text('native session metadata ' + str(len(calls)))
|
||||
row = ComponentTarget(path, 'MAIN', '1', 'uid', 'R1', 'old', str(len(calls)))
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})}, (row,))
|
||||
preparer._discover_project_sheets = discover
|
||||
with pytest.raises(TaskCenterError, match='changed'):
|
||||
preparer.collect_inventory(project, ('old',))
|
||||
|
||||
|
||||
def test_first_open_normalization_then_runtime_updates_need_two_equal_reads(tmp_path):
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
database = project.parent / 'database' / 'icdb.dat'
|
||||
database.parent.mkdir()
|
||||
database.write_text('initial database')
|
||||
original = preparer._discover_project_sheets
|
||||
def discover(*args, **kwargs):
|
||||
result = original(*args, **kwargs)
|
||||
if len(calls) == 1:
|
||||
project.write_text('normalized project')
|
||||
database.write_text('native session metadata ' + str(len(calls)))
|
||||
return result
|
||||
preparer._discover_project_sheets = discover
|
||||
assert preparer.collect_inventory(project, ('old',))[0].refdes == 'R1'
|
||||
assert len(calls) == 3
|
||||
|
||||
|
||||
def test_unverifiable_retry_after_known_churn_still_fails_closed(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import discovery_cache as module
|
||||
project, preparer, calls = prepared(tmp_path)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import json
|
||||
|
||||
from dx_productivity.trial_task_center import logging_setup as logs
|
||||
|
||||
|
||||
def test_unchanged_event_log_does_not_reread_tail_each_append(tmp_path, monkeypatch):
|
||||
context = logs.configure_logging(tmp_path)
|
||||
reads = []
|
||||
original = logs._tail_utf8_lines
|
||||
def read(path, limit):
|
||||
reads.append(path)
|
||||
return original(path, limit)
|
||||
monkeypatch.setattr(logs, '_tail_utf8_lines', read)
|
||||
for _ in range(4):
|
||||
logs.append_task_event(context, level='INFO', task_id='a', operation='step')
|
||||
path = tmp_path / 'tasks/a/events.jsonl'
|
||||
assert [json.loads(s)['sequence'] for s in path.read_text().splitlines()] == [1, 2, 3, 4]
|
||||
assert len(reads) <= 1
|
||||
|
||||
|
||||
def test_replaced_or_external_appended_log_invalidates_cached_sequence(tmp_path):
|
||||
context = logs.configure_logging(tmp_path)
|
||||
logs.append_task_event(context, level='INFO', task_id='a', operation='step')
|
||||
path = tmp_path / 'tasks/a/events.jsonl'
|
||||
with path.open('a') as stream:
|
||||
stream.write(json.dumps({'sequence': 50}) + '\n')
|
||||
event = logs.append_task_event(context, level='INFO', task_id='a', operation='step')
|
||||
assert event['sequence'] == 51
|
||||
replacement = path.with_suffix('.new')
|
||||
replacement.write_text(json.dumps({'sequence': 80}) + '\n')
|
||||
replacement.replace(path)
|
||||
event = logs.append_task_event(context, level='INFO', task_id='a', operation='step')
|
||||
assert event['sequence'] == 81
|
||||
@@ -62,6 +62,41 @@ def test_long_evidence_path_remains_visible_to_real_vbs(tmp_path):
|
||||
assert result.returncode == 0 and result.stdout.strip() == 'True'
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows VBS path compatibility')
|
||||
def test_long_evidence_without_83_names_is_readable_and_writable_by_real_vbs(tmp_path, monkeypatch):
|
||||
import ctypes
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from dx_productivity.trial_task_center.quick_run import _vbs_worker_paths, _resolve_cscript
|
||||
# Reproduce a Windows volume without usable 8.3 names.
|
||||
monkeypatch.setattr(ctypes, 'WinDLL', lambda *args, **kwargs:
|
||||
SimpleNamespace(GetShortPathNameW=lambda *args: 0))
|
||||
root = tmp_path / ('evidence-' + 'x' * 80) / ('discovery-' + 'y' * 60)
|
||||
root.mkdir(parents=True)
|
||||
script = root / 'QuickPartReplace.vbs'
|
||||
script.write_text('Set f=CreateObject("Scripting.FileSystemObject")\n'
|
||||
'WScript.Echo CStr(f.FileExists(f.BuildPath(WScript.Arguments(0), WScript.Arguments(1))))\n'
|
||||
'Set s=f.CreateTextFile(f.BuildPath(WScript.Arguments(0), "written-by-vbs.txt"),True)\n'
|
||||
's.Write "saved"\ns.Close\n')
|
||||
marker = 'monitor-' + 'a' * 32 + '.ready'
|
||||
(root / marker).write_text('token')
|
||||
assert len(str(root / marker)) > 259
|
||||
script_arg, root_arg = _vbs_worker_paths(script, root)
|
||||
try:
|
||||
assert len(root_arg) + 100 < 260
|
||||
assert Path(root_arg).resolve() == root.resolve()
|
||||
assert _vbs_worker_paths(script, root) == (script_arg, root_arg)
|
||||
result = subprocess.run((str(_resolve_cscript()), '//nologo', script_arg, root_arg, marker),
|
||||
capture_output=True, text=True, timeout=10)
|
||||
assert result.returncode == 0 and result.stdout.strip() == 'True'
|
||||
assert (root / 'written-by-vbs.txt').read_text() == 'saved'
|
||||
finally:
|
||||
from dx_productivity.trial_task_center.legacy_paths import cleanup_worker_aliases
|
||||
cleanup_worker_aliases()
|
||||
assert root.is_dir() and (root / marker).read_text() == 'token'
|
||||
assert not Path(root_arg).exists()
|
||||
|
||||
|
||||
def test_external_status_append_blocks_next_worker_before_cad_write(tmp_path):
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import os
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import append_task_event
|
||||
from test_ui_remediation import window
|
||||
|
||||
|
||||
def test_results_use_executed_readback_and_clear_when_switching_tasks(window, qtbot):
|
||||
task = window.service.create_task('Executed')
|
||||
for state, ref in [('saved_ok', 'R1'), ('batch_failed', 'R2'), ('no_match', 'R3')]:
|
||||
append_task_event(window.service._logging, level='INFO', task_id=task.task_id,
|
||||
operation='quick_run_executed', message=f'Replacements: {ref} OLD -> ACTUAL Saved, reopened',
|
||||
details={'state': state, 'schematic_name': 'MAIN', 'sheet_number': '1'})
|
||||
window.open_task(task.task_id)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
window._show_task_log()
|
||||
qtbot.waitUntil(lambda: not window._log_presenter.query.busy)
|
||||
results = window.run_panel.log_dialog.result_view.model()
|
||||
assert results.rowCount() == 1
|
||||
assert results.index(0, 1).data() == 'R1'
|
||||
assert results.index(0, 3).data() == 'ACTUAL'
|
||||
assert '已保存并核验' in results.index(0, 4).data()
|
||||
other = window.service.create_task('Unexecuted')
|
||||
window.open_task(other.task_id)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
assert results.rowCount() == 0
|
||||
@@ -0,0 +1,132 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
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
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def failed_native(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
path = tmp_path / 'board.prj'
|
||||
path.touch()
|
||||
task = store.create_task('native failed')
|
||||
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
|
||||
project = store.set_project_selected(project.project_id, True)
|
||||
store.bind_project_task(task.task_id, project.project_id, 'batch', 0)
|
||||
service.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
facade = service.for_project_task(task.task_id)
|
||||
handoff = facade._quick_run_preparer.prepare(task.task_id, (project,), store.list_rules(task.task_id))
|
||||
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\n'
|
||||
f'{job}\tawaiting_native_replace\t\tprepared\n'
|
||||
f'{job}\tbatch_failed\t-2147220665\tfailed project closed without saving; native rollback not executed\n', encoding='utf-8')
|
||||
root = handoff.command_path.parent
|
||||
snapshot = root / f'snapshot-{job}.tsv'
|
||||
snapshot.write_text('original snapshot evidence')
|
||||
report = Path(str(snapshot) + '.native.json')
|
||||
report.write_text(json.dumps({'ok': False, 'stage': 'pin_promotion_started', 'replaced_uids': ['uid']}))
|
||||
service.quick_run_progress(task.task_id)
|
||||
yield service, store, task.task_id, handoff, report
|
||||
store.close()
|
||||
|
||||
|
||||
def test_failed_after_native_mutation_is_interrupted_and_retry_does_not_archive(failed_native):
|
||||
service, store, task_id, handoff, report = failed_native
|
||||
context = service.task_context(task_id)
|
||||
assert context.interrupted and service.has_interrupted_quick_run(task_id)
|
||||
originals = {p: p.read_bytes() for p in (handoff.command_path, handoff.status_path, report)}
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
service.prepare_failed_quick_run(task_id)
|
||||
assert error.value.code == 'quick_run_uncertain'
|
||||
assert all(path.read_bytes() == contents for path, contents in originals.items())
|
||||
assert not (handoff.command_path.parent.parent / 'quick-run-history').exists()
|
||||
|
||||
|
||||
def test_verified_rollback_resolves_failed_native_uncertainty(failed_native):
|
||||
service, _, task_id, _, report = failed_native
|
||||
Path(str(report)[:-len('.json')] + '.rolled-back').write_text('native replacement rollback verified')
|
||||
assert not service.task_context(task_id).interrupted
|
||||
|
||||
|
||||
@pytest.mark.parametrize('contents', [None, '{truncated'])
|
||||
def test_native_awaiting_then_failed_without_readable_report_stays_uncertain(failed_native, contents):
|
||||
service, _, task_id, _, report = failed_native
|
||||
if contents is None:
|
||||
report.unlink()
|
||||
else:
|
||||
report.write_text(contents)
|
||||
assert service.has_interrupted_quick_run(task_id)
|
||||
|
||||
|
||||
def test_preflight_native_failure_does_not_claim_mutation(failed_native):
|
||||
service, _, task_id, _, report = failed_native
|
||||
report.write_text(json.dumps({'ok': False, 'stage': 'preflight', 'error': 'library target absent'}))
|
||||
assert not service.has_interrupted_quick_run(task_id)
|
||||
|
||||
|
||||
def test_recovery_selects_failed_job_with_native_mutation_evidence(failed_native):
|
||||
from dx_productivity.trial_task_center import quick_run, recovery
|
||||
_, _, _, handoff, _ = failed_native
|
||||
commands = quick_run._read_commands(handoff.command_path)
|
||||
statuses = quick_run._read_status_details(handoff.status_path)
|
||||
assert recovery._recovery_command(commands, statuses, root=handoff.command_path.parent) == commands[0]
|
||||
|
||||
|
||||
def test_native_failure_status_reaches_bound_recovery_validation(failed_native, monkeypatch):
|
||||
from dx_productivity.trial_task_center import recovery
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus
|
||||
service, store, task_id, _, _ = failed_native
|
||||
project = store.list_projects(task_id)[0]
|
||||
assert project.status is ProjectStatus.FAILED
|
||||
def validate(*args, **kwargs):
|
||||
raise TaskCenterError('bound_recovery_reached', 'validate immutable native evidence')
|
||||
monkeypatch.setattr(recovery, 'recover', validate)
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
service.recover_quick_run(task_id, confirmed=True)
|
||||
assert error.value.code == 'bound_recovery_reached'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('code', ['recovery_verified', 'recovery_saved_verified'])
|
||||
def test_verified_recovery_synchronizes_previously_failed_project(failed_native, code):
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus, TaskStatus
|
||||
service, store, task_id, handoff, _ = failed_native
|
||||
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
with handoff.status_path.open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\trestored_ok\t{code}\tsaved and verified\n')
|
||||
service.quick_run_progress(task_id)
|
||||
assert store.list_projects(task_id)[0].status is ProjectStatus.COMPLETED
|
||||
assert store.get_task(task_id).status is TaskStatus.COMPLETED
|
||||
|
||||
|
||||
def test_manual_failure_cannot_be_completed_by_native_progress(failed_native):
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus
|
||||
service, store, task_id, handoff, _ = failed_native
|
||||
project = store.list_projects(task_id)[0]
|
||||
store.set_project_status(project.project_id, ProjectStatus.FAILED, summary='manual failure')
|
||||
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
with handoff.status_path.open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\trestored_ok\trecovery_verified\tverified\n')
|
||||
with pytest.raises(TaskCenterError, match='quick_run_project_state'):
|
||||
service.quick_run_progress(task_id)
|
||||
|
||||
|
||||
def test_uncertain_batch_failed_blocks_next_project_in_task_queue(failed_native, tmp_path):
|
||||
from threading import Event
|
||||
from dx_productivity.trial_task_center.task_queue import execute_task_queue
|
||||
service, store, task_id, _, _ = failed_native
|
||||
other = store.create_task('next must not run')
|
||||
path = tmp_path / 'next.prj'
|
||||
path.touch()
|
||||
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
|
||||
result = execute_task_queue(service, (task_id, other.task_id), stop_event=Event())
|
||||
assert result.paused
|
||||
assert [entry.state for entry in result.entries] == ['blocked', 'pending']
|
||||
assert not (service.for_project_task(other.task_id)._quick_run_preparer.data_root / 'quick-run').exists()
|
||||
@@ -0,0 +1,162 @@
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from subprocess import CompletedProcess
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _ProjectDiscovery, _queue_has_mutation_evidence
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget
|
||||
|
||||
|
||||
def project_fixture(tmp_path):
|
||||
project = tmp_path / 'project' / 'board.prj'
|
||||
project.parent.mkdir()
|
||||
project.write_text('project')
|
||||
database = project.parent / 'database' / 'icdb.dat'
|
||||
database.parent.mkdir()
|
||||
database.write_text('session 0')
|
||||
rows = tuple(ComponentTarget(project, 'MAIN', str(i), f'u{i}', f'R{i}', 'OLD', 'V') for i in (1, 2))
|
||||
preparer = QuickRunPreparer(tmp_path / 'data')
|
||||
return project, database, rows, preparer
|
||||
|
||||
|
||||
def test_two_native_reads_ignore_component_and_sheet_enumeration_order(tmp_path):
|
||||
project, database, rows, preparer = project_fixture(tmp_path)
|
||||
calls = []
|
||||
def loader(*args, **kwargs):
|
||||
calls.append(1)
|
||||
database.write_text(f'session {len(calls)}')
|
||||
ordered = rows if len(calls) % 2 else rows[::-1]
|
||||
sheets = tuple((r.schematic_name, r.sheet_number) for r in ordered)
|
||||
return _ProjectDiscovery(sheets, {s: frozenset({'old'}) for s in sheets}, ordered)
|
||||
preparer._discover_project_sheets = loader
|
||||
assert {r.uid for r in preparer.collect_inventory(project, ('OLD',))} == {'u1', 'u2'}
|
||||
assert len(calls) == 2
|
||||
preparer.collect_inventory(project, ('OLD',))
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['value', 'duplicate', 'missing', 'refdes'])
|
||||
def test_native_comparison_rejects_actual_content_changes(tmp_path, change):
|
||||
project, database, rows, preparer = project_fixture(tmp_path)
|
||||
calls = []
|
||||
def loader(*args, **kwargs):
|
||||
calls.append(1)
|
||||
database.write_text(f'session {len(calls)}')
|
||||
altered = rows
|
||||
if len(calls) > 1:
|
||||
if change == 'value':
|
||||
altered = (replace(rows[0], old_value='changed'), rows[1])
|
||||
elif change == 'refdes':
|
||||
altered = (replace(rows[0], refdes='R99'), rows[1])
|
||||
elif change == 'duplicate':
|
||||
altered = rows + (rows[0],)
|
||||
else:
|
||||
altered = rows[1:]
|
||||
sheets = (('MAIN', '1'), ('MAIN', '2'))
|
||||
return _ProjectDiscovery(sheets, {s: frozenset({'old'}) for s in sheets}, altered)
|
||||
preparer._discover_project_sheets = loader
|
||||
with pytest.raises(TaskCenterError):
|
||||
preparer.collect_inventory(project, ('OLD',))
|
||||
|
||||
|
||||
def test_cancel_after_reader_returns_prevents_cache_and_next_read(tmp_path):
|
||||
project, database, rows, preparer = project_fixture(tmp_path)
|
||||
stop = Event()
|
||||
calls = []
|
||||
def loader(*args, **kwargs):
|
||||
calls.append(kwargs)
|
||||
assert kwargs['stop_event'] is stop
|
||||
stop.set()
|
||||
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})}, rows[:1])
|
||||
preparer._discover_project_sheets = loader
|
||||
with pytest.raises(TaskCenterError) as cancelled:
|
||||
preparer.collect_inventory(project, ('OLD',), stop_event=stop)
|
||||
assert cancelled.value.code == 'operation_cancelled'
|
||||
assert len(calls) == 1 and not preparer._discovery_cache._entries
|
||||
with pytest.raises(TaskCenterError):
|
||||
preparer.collect_inventory(project, ('OLD',), stop_event=stop)
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_default_discovery_forwards_abort_to_private_runner_and_waits_cleanup(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import isolated_cad, quick_run
|
||||
project, _, _, preparer = project_fixture(tmp_path)
|
||||
source = tmp_path / 'runtime.vbs'
|
||||
source.write_text('runtime')
|
||||
stop = Event()
|
||||
cleanup = []
|
||||
def run(command, timeout, *, abort_event=None, cooperative_abort=False):
|
||||
assert abort_event is stop
|
||||
assert cooperative_abort
|
||||
stop.set()
|
||||
cleanup.append('released')
|
||||
return CompletedProcess(command, 2, '', 'cancelled')
|
||||
monkeypatch.setattr(isolated_cad, 'run_isolated_process', run)
|
||||
monkeypatch.setattr(quick_run, '_native_helper_launch_arguments', lambda: ())
|
||||
preparer = QuickRunPreparer(tmp_path / 'data', script_source=source,
|
||||
cscript_resolver=lambda: Path('cscript.exe'))
|
||||
messages = []
|
||||
with pytest.raises(TaskCenterError) as cancelled:
|
||||
preparer.collect_inventory(project, ('OLD',), stop_event=stop, on_progress=messages.append)
|
||||
assert cancelled.value.code == 'operation_cancelled'
|
||||
assert cleanup == ['released'] and messages
|
||||
assert not preparer._discovery_cache._entries
|
||||
|
||||
|
||||
def test_cancel_does_not_hide_native_cleanup_failure(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import isolated_cad, quick_run
|
||||
project, _, _, _ = project_fixture(tmp_path)
|
||||
source = tmp_path / 'runtime.vbs'
|
||||
source.write_text('runtime')
|
||||
stop = Event()
|
||||
def run(command, timeout, **controls):
|
||||
stop.set()
|
||||
root = Path(command[3]).resolve()
|
||||
(root / 'uncertain.flag').write_text('owned CAD did not quit')
|
||||
raise OSError('cleanup failure')
|
||||
monkeypatch.setattr(isolated_cad, 'run_isolated_process', run)
|
||||
monkeypatch.setattr(quick_run, '_native_helper_launch_arguments', lambda: ())
|
||||
preparer = QuickRunPreparer(tmp_path / 'data', script_source=source,
|
||||
cscript_resolver=lambda: Path('cscript.exe'))
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
preparer.collect_inventory(project, ('OLD',), stop_event=stop)
|
||||
assert error.value.code == 'inventory_cleanup'
|
||||
|
||||
|
||||
def test_read_cancellation_requests_cooperative_stop_in_real_child_process(tmp_path):
|
||||
import json
|
||||
import sys
|
||||
from threading import Timer
|
||||
from dx_productivity.trial_task_center.worker_monitor import run_monitored_process
|
||||
script = tmp_path / 'reader.py'
|
||||
script.write_text('''import pathlib,sys,time
|
||||
root=pathlib.Path(sys.argv[1])
|
||||
token=sys.argv[-1]
|
||||
stop=root / f'monitor-{token}.stop'
|
||||
ready=root / f'monitor-{token}.ready'
|
||||
while not ready.exists(): time.sleep(.01)
|
||||
while not stop.exists(): time.sleep(.01)
|
||||
(root / 'cooperatively-closed.txt').write_text('closed')
|
||||
print('safe read cleanup finished', flush=True)
|
||||
''')
|
||||
stop = Event()
|
||||
timer = Timer(.2, stop.set)
|
||||
timer.start()
|
||||
try:
|
||||
result = run_monitored_process((sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job'),
|
||||
2, abort_event=stop, cooperative_abort=True)
|
||||
finally:
|
||||
timer.join()
|
||||
assert result.returncode == 0
|
||||
assert (tmp_path / 'cooperatively-closed.txt').read_text() == 'closed'
|
||||
assert json.loads((tmp_path / 'worker-progress.json').read_text())['stop_requested']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stage', ['native_replace_applied', 'pin_promotion_started'])
|
||||
def test_mutation_evidence_keeps_recovery_for_later_native_stages(tmp_path, stage):
|
||||
import json
|
||||
(tmp_path / 'snapshot-job.tsv.native.json').write_text(json.dumps({'ok': False, 'stage': stage}))
|
||||
assert _queue_has_mutation_evidence(tmp_path)
|
||||
@@ -0,0 +1,173 @@
|
||||
from dataclasses import replace
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from test_bom_batch import batch, records_for
|
||||
from dx_productivity.trial_task_center.bom_batch import preview_batch
|
||||
from dx_productivity.trial_task_center.bom_plan import write_bom_template
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
def seed(store, task, targets):
|
||||
store.record_target_inventory(task.task_id, targets)
|
||||
rows = store.list_target_plan(task.task_id)
|
||||
edited = (replace(rows[0], enabled=True, new_part_number='MANUAL',
|
||||
custom_value_enabled=True, custom_value='CUSTOM', sync_nc=False), *rows[1:])
|
||||
return store.replace_target_plan(task.task_id, edited)
|
||||
|
||||
|
||||
def expanded(targets):
|
||||
return (*targets, replace(targets[0], uid='u3', refdes='R3', old_part_number='EXTRA'))
|
||||
|
||||
|
||||
def test_inventory_addition_preserves_existing_edits(batch):
|
||||
service, store, tasks, targets, calls = batch
|
||||
task = tasks[0]
|
||||
before = seed(store, task, targets[task.task_id])
|
||||
rows = store.record_target_inventory(task.task_id, expanded(targets[task.task_id]))
|
||||
assert {row.target.key: row for row in rows}[before[0].target.key] == before[0]
|
||||
assert len(rows) == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['remove', 'uid', 'refdes', 'old_part_number', 'old_value', 'duplicate'])
|
||||
def test_inventory_rejects_changed_or_removed_baseline_atomically(batch, change):
|
||||
service, store, tasks, targets, calls = batch
|
||||
task = tasks[0]
|
||||
before = seed(store, task, targets[task.task_id])
|
||||
incoming = list(expanded(targets[task.task_id]))
|
||||
if change == 'remove':
|
||||
incoming.pop(0)
|
||||
elif change == 'duplicate':
|
||||
incoming.append(incoming[0])
|
||||
else:
|
||||
incoming[0] = replace(incoming[0], **{change: 'CHANGED'})
|
||||
with pytest.raises(TaskCenterError):
|
||||
store.record_target_inventory(task.task_id, incoming)
|
||||
assert store.list_target_plan(task.task_id) == before
|
||||
|
||||
|
||||
def extension_preview(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
before = {}
|
||||
records = []
|
||||
for task in tasks:
|
||||
before[task.task_id] = seed(store, task, targets[task.task_id])
|
||||
targets[task.task_id] = expanded(targets[task.task_id])
|
||||
records.append({'project_path': str(targets[task.task_id][0].project_path),
|
||||
'old_part_number': 'EXTRA', 'new_part_number': 'NEW', 'refdes': 'R3'})
|
||||
path = write_bom_template(tmp_path / 'extension.xlsx', records)
|
||||
return before, path
|
||||
|
||||
|
||||
def test_bom_extension_stages_union_preserves_edits_and_saves(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
before, path = extension_preview(batch, tmp_path)
|
||||
preview = preview_batch(service, tasks[0].task_id, path)
|
||||
assert all(set(parts) == {'OLD', 'EXTRA'} for _, parts in calls)
|
||||
assert len(calls) == 2
|
||||
for project in preview.projects:
|
||||
assert store.list_target_plan(project.task_id) == before[project.task_id]
|
||||
assert project.rows[0] == before[project.task_id][0]
|
||||
assert len(project.rows) == 3
|
||||
service.save_bom_batch(preview, {p.task_id: p.rows for p in preview.projects})
|
||||
assert all(len(store.list_target_plan(task.task_id)) == 3 for task in tasks)
|
||||
|
||||
|
||||
def test_extension_save_rolls_back_both_inventory_and_edits(batch, tmp_path, monkeypatch):
|
||||
service, store, tasks, targets, calls = batch
|
||||
before, path = extension_preview(batch, tmp_path)
|
||||
preview = preview_batch(service, tasks[0].task_id, path)
|
||||
original = store.replace_target_plan
|
||||
def fail(task_id, rows):
|
||||
if task_id == tasks[1].task_id:
|
||||
raise TaskCenterError('target_identity', 'failure')
|
||||
return original(task_id, rows)
|
||||
monkeypatch.setattr(store, 'replace_target_plan', fail)
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.save_bom_batch(preview, {p.task_id: p.rows for p in preview.projects})
|
||||
assert all(store.list_target_plan(task.task_id) == before[task.task_id] for task in tasks)
|
||||
|
||||
|
||||
def test_preview_cancellation_does_not_collect_or_write(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets))
|
||||
event = Event()
|
||||
event.set()
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
preview_batch(service, tasks[0].task_id, path, stop_event=event)
|
||||
assert error.value.code == 'operation_cancelled'
|
||||
assert not calls
|
||||
|
||||
|
||||
def test_preview_forwards_controls_and_reports_projects(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
path = write_bom_template(tmp_path / 'bom.xlsx', records_for(tasks, targets))
|
||||
event, progress = Event(), []
|
||||
for task in tasks:
|
||||
def collect(project, parts, *, stop_event, on_progress, task_id=task.task_id):
|
||||
assert stop_event is event
|
||||
on_progress('reading')
|
||||
return targets[task_id]
|
||||
service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory = collect
|
||||
preview_batch(service, tasks[0].task_id, path, stop_event=event, on_progress=progress.append)
|
||||
assert all(any(task.name in message for message in progress) for task in tasks)
|
||||
assert sum(message.endswith('reading') for message in progress) == 2
|
||||
assert any('1/2' in message for message in progress)
|
||||
assert any('2/2' in message for message in progress)
|
||||
|
||||
@pytest.mark.parametrize('change', ['remove', 'old_value'])
|
||||
def test_bom_extension_rejects_changed_baseline_without_writes(batch, tmp_path, change):
|
||||
service, store, tasks, targets, calls = batch
|
||||
before, path = extension_preview(batch, tmp_path)
|
||||
task_id = tasks[1].task_id
|
||||
incoming = list(targets[task_id])
|
||||
if change == 'remove':
|
||||
incoming.pop(0)
|
||||
else:
|
||||
incoming[0] = replace(incoming[0], old_value='different')
|
||||
targets[task_id] = tuple(incoming)
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
preview_batch(service, tasks[0].task_id, path)
|
||||
assert error.value.code == 'target_identity'
|
||||
assert all(store.list_target_plan(task.task_id) == before[task.task_id] for task in tasks)
|
||||
|
||||
|
||||
def test_extension_preview_concurrent_edit_rejects_every_save(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
before, path = extension_preview(batch, tmp_path)
|
||||
preview = preview_batch(service, tasks[0].task_id, path)
|
||||
task = tasks[1]
|
||||
changed = (replace(before[task.task_id][0], new_part_number='CONCURRENT'),
|
||||
*before[task.task_id][1:])
|
||||
store.replace_target_plan(task.task_id, changed)
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
service.save_bom_batch(preview, {p.task_id: p.rows for p in preview.projects})
|
||||
assert error.value.code == 'target_identity'
|
||||
assert store.list_target_plan(tasks[0].task_id) == before[tasks[0].task_id]
|
||||
assert store.list_target_plan(task.task_id) == changed
|
||||
|
||||
|
||||
def test_cancellation_after_collection_keeps_every_plan_unchanged(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
before, path = extension_preview(batch, tmp_path)
|
||||
event = Event()
|
||||
def collect(project, parts, *, stop_event):
|
||||
stop_event.set()
|
||||
return targets[tasks[0].task_id]
|
||||
service.for_project_task(tasks[0].task_id)._quick_run_preparer.collect_inventory = collect
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
preview_batch(service, tasks[0].task_id, path, stop_event=event)
|
||||
assert error.value.code == 'operation_cancelled'
|
||||
assert all(store.list_target_plan(task.task_id) == before[task.task_id] for task in tasks)
|
||||
|
||||
|
||||
def test_preview_without_controls_supports_two_argument_reader(batch, tmp_path):
|
||||
service, store, tasks, targets, calls = batch
|
||||
path = write_bom_template(tmp_path / 'legacy.xlsx', records_for(tasks, targets))
|
||||
for task in tasks:
|
||||
def legacy(project, parts):
|
||||
return next(items for items in targets.values() if items[0].project_path == project)
|
||||
service.for_project_task(task.task_id)._quick_run_preparer.collect_inventory = legacy
|
||||
preview = preview_batch(service, tasks[0].task_id, path)
|
||||
assert len(preview.projects) == 2
|
||||
@@ -12,6 +12,22 @@ from dx_productivity.trial_task_center import isolated_cad as runtime
|
||||
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows junction path handling')
|
||||
def test_private_evidence_uses_canonical_root_behind_a_legacy_alias(tmp_path):
|
||||
from dx_productivity.trial_task_center.legacy_paths import _AliasPool
|
||||
root = tmp_path / ('nested-' + 'x' * 90) / ('nested-' + 'y' * 90)
|
||||
root.mkdir(parents=True)
|
||||
pool = _AliasPool()
|
||||
try:
|
||||
alias = pool.alias(root.resolve())
|
||||
session = runtime.IsolatedCadSession(alias)
|
||||
session._record(state='starting')
|
||||
assert session.root == root.resolve()
|
||||
assert (root / 'private-desktop-sessions' / (session.token + '.json')).is_file()
|
||||
finally:
|
||||
assert not pool.close()
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows state-file sharing semantics')
|
||||
def test_private_record_survives_a_reader_temporarily_denying_replacement(tmp_path):
|
||||
import win32con
|
||||
@@ -91,6 +107,31 @@ def test_success_quits_owned_cad_before_releasing_desktop(monkeypatch, tmp_path)
|
||||
assert record['state'] == 'released' and record['clean']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ready_after', [90, None])
|
||||
def test_slow_startup_is_bounded_and_cleanup_remains_owned(monkeypatch, tmp_path, ready_after):
|
||||
events, _ = fake_desktop(monkeypatch, tmp_path)
|
||||
clock = [0.0]
|
||||
monkeypatch.setattr(runtime.time, 'monotonic', lambda: clock[0])
|
||||
monkeypatch.setattr(runtime.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0] + seconds))
|
||||
original = runtime.PrivateDesktop.start_process
|
||||
def start(self, command, **kwargs):
|
||||
process = original(self, command, **kwargs)
|
||||
if command[0] == 'probe':
|
||||
process.poll = lambda: 0 if ready_after is not None and clock[0] >= ready_after else None
|
||||
return process
|
||||
monkeypatch.setattr(runtime.PrivateDesktop, 'start_process', start)
|
||||
if ready_after is None:
|
||||
with pytest.raises(runtime.PrivateCadStartupError, match='bootstrap timed out'):
|
||||
with runtime.IsolatedCadSession(tmp_path):
|
||||
pytest.fail('unresponsive startup entered project work')
|
||||
assert 119 <= clock[0] <= 121
|
||||
assert ('release', False) in events
|
||||
else:
|
||||
with runtime.IsolatedCadSession(tmp_path):
|
||||
assert clock[0] >= ready_after
|
||||
assert ('release', False) in events
|
||||
|
||||
|
||||
def test_repeated_session_preserves_prior_release_evidence(monkeypatch, tmp_path):
|
||||
fake_desktop(monkeypatch, tmp_path)
|
||||
with runtime.IsolatedCadSession(tmp_path) as first:
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Resource lifetime is independent from task data and background reads."""
|
||||
from types import SimpleNamespace
|
||||
from threading import Event
|
||||
|
||||
from PySide6.QtCore import QCoreApplication, QEvent, Qt
|
||||
from PySide6.QtWidgets import QCheckBox, QTableView, QWidget
|
||||
from PySide6.QtTest import QTest
|
||||
from shiboken6 import isValid
|
||||
|
||||
from dx_productivity.trial_task_center.bom_import_report import BomImportReport
|
||||
from dx_productivity.trial_task_center.ui.mapping_table import MappingTable
|
||||
from dx_productivity.trial_task_center.ui.project_plan import ProjectPlanPanel
|
||||
from dx_productivity.trial_task_center.ui.run_panel import RunPanel
|
||||
from dx_productivity.trial_task_center.ui.detail_windows import TaskLogDialog
|
||||
from test_ui_responsiveness import browser, loaded
|
||||
|
||||
|
||||
def test_rule_model_reuses_rows_and_preserves_selection(qtbot):
|
||||
changes = []
|
||||
table = MappingTable(lambda *args: changes.append(args))
|
||||
qtbot.addWidget(table)
|
||||
rules = tuple(SimpleNamespace(rule_id=str(i), old_part_number='OLD', new_part_number='NEW',
|
||||
custom_value_enabled=False, sync_nc=True, enabled=True, position=i) for i in range(1000))
|
||||
table.populate(rules)
|
||||
assert isinstance(table, QTableView)
|
||||
assert not table.findChildren(QCheckBox)
|
||||
assert len(table.findChildren(QWidget)) < 30
|
||||
table.setCurrentIndex(table.model().index(800, 0))
|
||||
resets = []
|
||||
table.model().modelReset.connect(lambda: resets.append(True))
|
||||
table.populate(rules)
|
||||
assert not resets and table.current_rule_id() == '800'
|
||||
check = table.model().index(800, 4)
|
||||
assert table.model().setData(check, Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole)
|
||||
assert changes == [('800', False)]
|
||||
# The persisted context confirms changes; a failed write leaves the check intact.
|
||||
assert check.data(Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Checked
|
||||
table.set_rules_editable(False)
|
||||
assert not table.model().setData(check, Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole)
|
||||
|
||||
|
||||
def test_rule_check_uses_native_delegate_and_waits_for_persisted_context(qtbot):
|
||||
changes = []
|
||||
table = MappingTable(lambda *args: changes.append(args))
|
||||
qtbot.addWidget(table)
|
||||
rule = SimpleNamespace(rule_id='rule', old_part_number='OLD', new_part_number='NEW',
|
||||
custom_value_enabled=False, sync_nc=True, enabled=True, position=0)
|
||||
table.populate((rule,))
|
||||
table.show()
|
||||
index = table.model().index(0, 4)
|
||||
table.setCurrentIndex(index)
|
||||
# Keyboard follows the same built-in item delegate path as clicking the check.
|
||||
QTest.keyClick(table, Qt.Key.Key_Space)
|
||||
assert changes == [('rule', False)]
|
||||
assert index.data(Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Checked
|
||||
table.populate((SimpleNamespace(**(vars(rule) | {'enabled': False})),))
|
||||
assert index.data(Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Unchecked
|
||||
assert table.current_rule_id() == 'rule'
|
||||
table.set_rules_editable(False)
|
||||
QTest.keyClick(table, Qt.Key.Key_Space)
|
||||
assert len(changes) == 1
|
||||
|
||||
|
||||
def test_rule_delegate_persists_through_task_center(browser, qtbot):
|
||||
window, service, (task, _) = browser
|
||||
window.open_task(task.task_id)
|
||||
loaded(qtbot, window, task)
|
||||
table = window.mapping_table
|
||||
table.setCurrentIndex(table.model().index(0, 4))
|
||||
rule_id = table.current_rule_id()
|
||||
QTest.keyClick(table, Qt.Key.Key_Space)
|
||||
qtbot.waitUntil(lambda: not window._workers and not window._context_query.busy)
|
||||
assert not service.task_context(task.task_id).rules[0].enabled
|
||||
assert table.currentIndex().data(Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Unchecked
|
||||
assert table.current_rule_id() == rule_id
|
||||
|
||||
|
||||
def test_log_rendering_keeps_poll_position_and_explicit_page_navigation(qtbot):
|
||||
dialog = TaskLogDialog()
|
||||
qtbot.addWidget(dialog)
|
||||
dialog.show()
|
||||
dialog.tabs.setCurrentIndex(1)
|
||||
text = '\n'.join(f'line {n}' for n in range(500))
|
||||
dialog.set_content(text, (), scroll_to='bottom')
|
||||
scroll = dialog.log_view.verticalScrollBar()
|
||||
assert scroll.maximum() > 0 and scroll.value() == scroll.maximum()
|
||||
scroll.setValue(20)
|
||||
dialog.set_content(text + '\nnew', ())
|
||||
assert scroll.value() == 20
|
||||
dialog.set_content(text + '\nnew', (), scroll_to='bottom')
|
||||
assert scroll.value() == scroll.maximum()
|
||||
dialog.tabs.setCurrentIndex(0)
|
||||
dialog.set_content(text + '\nolder', (), scroll_to='top')
|
||||
dialog.tabs.setCurrentIndex(1)
|
||||
assert scroll.value() == 0
|
||||
|
||||
|
||||
def test_result_append_keeps_selected_readback(qtbot):
|
||||
dialog = TaskLogDialog()
|
||||
qtbot.addWidget(dialog)
|
||||
rows = tuple(('MAIN/1', f'R{i}', 'OLD', 'NEW', 'verified') for i in range(250))
|
||||
dialog.set_content('', rows)
|
||||
table = dialog.result_view
|
||||
table.setCurrentIndex(table.model().index(120, 1))
|
||||
dialog.set_content('', rows + (('MAIN/1', 'C1', 'OLD', 'NEW', 'verified'),))
|
||||
assert table.currentIndex().data() == 'R120'
|
||||
|
||||
|
||||
def test_log_tabs_are_lazy_and_closing_releases_widgets(qtbot):
|
||||
panel = RunPanel()
|
||||
qtbot.addWidget(panel)
|
||||
assert panel.log_dialog is None
|
||||
panel.toggle_log_button.setChecked(True)
|
||||
dialog = panel.log_dialog
|
||||
assert dialog.log_view is None
|
||||
dialog.set_content('persisted log', (('MAIN/1', 'R1', 'OLD', 'NEW', 'verified'),))
|
||||
assert dialog.result_view.model().rowCount() == 1
|
||||
dialog.tabs.setCurrentIndex(1)
|
||||
assert dialog.log_view.toPlainText() == 'persisted log'
|
||||
dialog.tabs.setCurrentIndex(0)
|
||||
dialog.set_content('new text while hidden', ())
|
||||
assert dialog.log_view.toPlainText() == 'persisted log'
|
||||
dialog.tabs.setCurrentIndex(1)
|
||||
assert dialog.log_view.toPlainText() == 'new text while hidden'
|
||||
rows = (('MAIN/2', 'C2', 'OLD', 'NEW', 'verified'),)
|
||||
dialog.set_content('new text while hidden', rows)
|
||||
assert dialog.result_view.model().rowCount() == 0
|
||||
dialog.tabs.setCurrentIndex(0)
|
||||
assert dialog.result_view.model().index(0, 1).data() == 'C2'
|
||||
dialog.close()
|
||||
assert panel.log_dialog is None and not panel.toggle_log_button.isChecked()
|
||||
panel.toggle_log_button.setChecked(True)
|
||||
newer = panel.log_dialog
|
||||
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
|
||||
assert not isValid(dialog) and panel.log_dialog is newer
|
||||
|
||||
|
||||
def test_bom_report_widgets_are_optional_and_report_survives_close(qtbot):
|
||||
owner = SimpleNamespace(_known_task_groups={'a': 'batch', 'b': 'batch', 'c': 'other'},
|
||||
_update_gates=lambda: None, service=SimpleNamespace(target_plan=lambda _: ()))
|
||||
panel = ProjectPlanPanel(owner)
|
||||
qtbot.addWidget(panel)
|
||||
panel.bind_task('a')
|
||||
panel._received_bom_report(BomImportReport((), (), errors=('invalid header',)))
|
||||
assert panel.report_dialog is None
|
||||
assert 'invalid header' in panel.report_text
|
||||
panel.report_toggle.setChecked(True)
|
||||
old = panel.report_dialog
|
||||
assert 'invalid header' in old.view.toPlainText()
|
||||
old.close()
|
||||
assert panel.report_dialog is None
|
||||
panel.bind_task('b')
|
||||
panel.report_toggle.setChecked(True)
|
||||
assert 'invalid header' in panel.report_dialog.view.toPlainText()
|
||||
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
|
||||
assert not isValid(old)
|
||||
panel.bind_task('c')
|
||||
assert panel.report_dialog is None and not panel.report_text
|
||||
panel.bind_task('a')
|
||||
assert 'invalid header' in panel.report_text
|
||||
|
||||
|
||||
def test_closed_log_cancels_pending_read_and_reopen_loads_latest(browser, qtbot, monkeypatch, tmp_path):
|
||||
window, service, (task, _) = browser
|
||||
path = tmp_path / 'data' / 'tasks' / task.task_id / 'events.jsonl'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('BEFORE\n')
|
||||
real = service.read_task_log
|
||||
entered, release = Event(), Event()
|
||||
controls = []
|
||||
def delayed(task_id, **kwargs):
|
||||
controls.append(kwargs['read_control'])
|
||||
page = real(task_id, **kwargs)
|
||||
if len(controls) == 1:
|
||||
entered.set()
|
||||
release.wait(3)
|
||||
return page
|
||||
monkeypatch.setattr(service, 'read_task_log', delayed)
|
||||
window.open_task(task.task_id)
|
||||
loaded(qtbot, window, task)
|
||||
try:
|
||||
window._show_task_log(force=True)
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
window.run_panel.log_dialog.close()
|
||||
assert controls[0].cancelled
|
||||
window._append_log('local error while hidden')
|
||||
assert window.run_panel.log_dialog is None
|
||||
path.write_text('AFTER\n')
|
||||
window._show_task_log()
|
||||
qtbot.waitUntil(lambda: 'AFTER' in window._log_presenter.log_text)
|
||||
assert 'BEFORE' not in window._log_presenter.log_text
|
||||
assert 'local error while hidden' in window._log_presenter.log_text
|
||||
assert len(controls) == 2
|
||||
finally:
|
||||
release.set()
|
||||
@@ -0,0 +1,40 @@
|
||||
from threading import Timer
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['native_report', 'queue_command'])
|
||||
def test_native_report_waits_for_reader_to_release_windows_replace_lock(tmp_path, kind):
|
||||
import win32file
|
||||
import win32con
|
||||
from dx_productivity.trial_task_center.native_helper import atomic_text
|
||||
from dx_productivity.trial_task_center.quick_run import _write_atomic_queue_text
|
||||
report = tmp_path / 'native.json'
|
||||
report.write_text('old complete report')
|
||||
held = win32file.CreateFile(str(report), win32con.GENERIC_READ,
|
||||
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None)
|
||||
timer = Timer(.2, held.Close)
|
||||
timer.start()
|
||||
try:
|
||||
if kind == 'native_report':
|
||||
atomic_text(report, 'new complete report')
|
||||
else:
|
||||
_write_atomic_queue_text(report, 'new complete report', 'quick_run_command', 'publish failed')
|
||||
finally:
|
||||
timer.join()
|
||||
assert report.read_text() == 'new complete report'
|
||||
|
||||
|
||||
def test_status_read_waits_for_exclusive_windows_reader(tmp_path):
|
||||
import win32file
|
||||
import win32con
|
||||
from dx_productivity.trial_task_center.quick_run import _open_status_for_read
|
||||
status = tmp_path / 'status.tsv'
|
||||
status.write_bytes(b'complete correlated status')
|
||||
held = win32file.CreateFile(str(status), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
timer = Timer(.2, held.Close)
|
||||
timer.start()
|
||||
try:
|
||||
with _open_status_for_read(status) as stream:
|
||||
assert stream.read() == b'complete correlated status'
|
||||
finally:
|
||||
timer.join()
|
||||
@@ -0,0 +1,275 @@
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
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.models import TaskStatus, ProjectStatus
|
||||
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, TargetPlanRow
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def completed(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
path = tmp_path / 'board.prj'
|
||||
path.touch()
|
||||
task = store.create_task('board')
|
||||
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
store.bind_project_task(task.task_id, project.project_id, 'batch', 0)
|
||||
service.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
target = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'before')
|
||||
store.record_target_inventory(task.task_id, (target,))
|
||||
store.replace_target_plan(task.task_id, (TargetPlanRow(target, True, 'NEW'),))
|
||||
store.record_quick_run_progress(task.task_id, (project.project_id,), queue_complete=True, has_progress=True)
|
||||
yield service, store, task.task_id, project.project_id, target
|
||||
store.close()
|
||||
|
||||
|
||||
def test_restart_preserves_plan_and_evidence_but_requires_new_baseline(completed):
|
||||
service, store, task_id, project_id, target = completed
|
||||
root = service.for_project_task(task_id)._quick_run_preparer.data_root
|
||||
history = root / 'quick-run-history' / 'obsolete-test'
|
||||
history.mkdir(parents=True)
|
||||
(history / 'native.log').write_text('original evidence')
|
||||
old_task = store.get_task(task_id)
|
||||
restarted = service.start_new_round(task_id)
|
||||
assert [t.task_id for t in restarted] == [task_id]
|
||||
task = store.get_task(task_id)
|
||||
assert task.status is TaskStatus.DRAFT and task.target_plan_mode
|
||||
assert task.group_id == old_task.group_id and task.primary_project_id == project_id
|
||||
assert task.completed_utc is None and task.started_utc is None
|
||||
assert store.get_project(project_id).status is ProjectStatus.PENDING
|
||||
assert not store.list_target_plan(task_id)
|
||||
archives = list((root / 'rounds').glob('*/plan.json'))
|
||||
assert len(archives) == 1
|
||||
snapshot = json.loads(archives[0].read_text(encoding='utf-8'))
|
||||
assert snapshot['targets'][0]['target']['old_part_number'] == 'OLD'
|
||||
assert (archives[0].parent / 'quick-run-history' / 'obsolete-test' / 'native.log').read_text() == 'original evidence'
|
||||
assert not service.task_context(task_id).has_evidence
|
||||
assert not service.task_context(task_id).progress.next_project_path
|
||||
# Previous UID with current PN/value becomes a new baseline only after collection.
|
||||
current = replace(target, old_part_number='NEW', old_value='after')
|
||||
store.record_target_inventory(task_id, (current,))
|
||||
store.replace_target_plan(task_id, (TargetPlanRow(current, True, 'NEXT'),))
|
||||
assert service.task_context(task_id).progress.next_old_part_number == 'NEW'
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.start_new_round(task_id)
|
||||
assert len(list((root / 'rounds').glob('*/plan.json'))) == 1
|
||||
|
||||
|
||||
def test_restart_rejects_interrupted_and_noncompleted_without_changing_plan(completed):
|
||||
service, store, task_id, _, _ = completed
|
||||
root = service.for_project_task(task_id)._quick_run_preparer.data_root / 'quick-run'
|
||||
root.mkdir(parents=True)
|
||||
(root / 'uncertain.flag').write_text('uncertain')
|
||||
before = store.list_target_plan(task_id)
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.start_new_round(task_id)
|
||||
assert store.get_task(task_id).status is TaskStatus.COMPLETED
|
||||
assert store.list_target_plan(task_id) == before
|
||||
assert (root / 'uncertain.flag').exists()
|
||||
|
||||
|
||||
def test_restart_rolls_back_files_when_database_reset_fails(completed, monkeypatch):
|
||||
service, store, task_id, _, _ = completed
|
||||
root = service.for_project_task(task_id)._quick_run_preparer.data_root
|
||||
history = root / 'quick-run-history'
|
||||
history.mkdir(parents=True)
|
||||
(history / 'proof.txt').write_text('retain')
|
||||
def fail(*args):
|
||||
raise RuntimeError('database failure')
|
||||
monkeypatch.setattr(store, 'reset_completed_round', fail)
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.start_new_round(task_id)
|
||||
assert (history / 'proof.txt').read_text() == 'retain'
|
||||
assert store.get_task(task_id).status is TaskStatus.COMPLETED
|
||||
assert store.list_target_plan(task_id)
|
||||
|
||||
|
||||
def test_completed_group_restarts_together_and_rules_are_editable(completed, tmp_path):
|
||||
service, store, task_id, _, _ = completed
|
||||
other = store.create_task('second')
|
||||
path = tmp_path / 'second.prj'
|
||||
path.touch()
|
||||
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
|
||||
store.record_quick_run_progress(other.task_id, (project.project_id,), queue_complete=True, has_progress=True)
|
||||
assert len(service.start_new_round(task_id)) == 2
|
||||
service.update_rule(store.list_rules(task_id)[0].rule_id, old_part_number='NEW', new_part_number='NEXT', enabled=True)
|
||||
assert store.list_rules(other.task_id)[-1].old_part_number == 'NEW'
|
||||
assert all(t.status is TaskStatus.DRAFT for t in store.list_project_group('batch'))
|
||||
|
||||
|
||||
def test_pristine_group_sibling_is_preserved_and_does_not_lock_rules(completed, tmp_path):
|
||||
service, store, task_id, _, _ = completed
|
||||
other = store.create_task('untouched')
|
||||
path = tmp_path / 'untouched.prj'
|
||||
path.touch()
|
||||
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
|
||||
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
|
||||
before = store.get_task(other.task_id)
|
||||
service.start_new_round(task_id)
|
||||
assert store.get_task(other.task_id) == before
|
||||
service.update_rule(store.list_rules(task_id)[0].rule_id, old_part_number='NEW', new_part_number='NEXT', enabled=True)
|
||||
assert store.list_rules(other.task_id)[-1].new_part_number == 'NEXT'
|
||||
|
||||
|
||||
def test_archived_handoff_cannot_supply_next_round_old_values(completed):
|
||||
service, store, task_id, project_id, _ = completed
|
||||
from dx_productivity.trial_task_center.target_plan import compile_target_rules
|
||||
facade = service.for_project_task(task_id)
|
||||
root = facade._quick_run_preparer.data_root
|
||||
handoff = facade._quick_run_preparer.prepare(task_id,
|
||||
(replace(store.get_project(project_id), status=ProjectStatus.PENDING),),
|
||||
compile_target_rules(store.list_target_plan(task_id)),
|
||||
sheet_targets={str(store.get_project(project_id).path).casefold(): (('MAIN', '1'),)})
|
||||
command = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')
|
||||
header = handoff.command_path.read_text(encoding='utf-8').splitlines()[0].split('\t')
|
||||
job = dict(zip(header, command))['job_id']
|
||||
handoff.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tsaved_ok\t\tverified\n', encoding='utf-8')
|
||||
old_bytes = handoff.command_path.read_bytes()
|
||||
service.start_new_round(task_id)
|
||||
assert not service.task_context(task_id).has_evidence
|
||||
assert not service.task_context(task_id).progress.next_project_path
|
||||
archives = list((root / 'rounds').glob('*/quick-run/command.tsv'))
|
||||
assert len(archives) == 1 and archives[0].read_bytes() == old_bytes
|
||||
assert not handoff.command_path.exists()
|
||||
|
||||
|
||||
def test_pending_journal_recovers_interrupted_archival_before_retry(completed):
|
||||
service, store, task_id, _, _ = completed
|
||||
root = service.for_project_task(task_id)._quick_run_preparer.data_root
|
||||
archive = root / 'rounds' / 'crashed' / 'quick-run-history'
|
||||
archive.mkdir(parents=True)
|
||||
(archive / 'evidence').write_text('unchanged')
|
||||
journal = service._logging.root / 'round-transitions' / 'crashed'
|
||||
journal.mkdir(parents=True)
|
||||
source = root / 'quick-run-history'
|
||||
(journal / 'journal.json').write_text(json.dumps(dict(task_ids=[task_id], summary='uncommitted round',
|
||||
moves=[(str(source), str(archive))])), encoding='utf-8')
|
||||
service.start_new_round(task_id)
|
||||
assert (journal / 'rolled-back').exists()
|
||||
assert any(path.read_text() == 'unchanged' for path in (root / 'rounds').glob('*/quick-run-history/evidence'))
|
||||
|
||||
|
||||
def test_restart_is_rejected_while_execution_lease_is_held(completed):
|
||||
service, store, task_id, _, _ = completed
|
||||
from dx_productivity.trial_task_center.service import _quick_run_lease
|
||||
with _quick_run_lease(service._logging.root):
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
service.start_new_round(task_id)
|
||||
assert error.value.code == 'quick_run_busy'
|
||||
assert store.get_task(task_id).status is TaskStatus.COMPLETED
|
||||
|
||||
|
||||
def test_new_round_ui_confirms_scope_and_invalidates_paused_queue_token(completed, qtbot, monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
service, store, task_id, _, _ = completed
|
||||
window = TrialTaskCenterWindow(service)
|
||||
qtbot.addWidget(window)
|
||||
window.open_task(task_id)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
assert window.run_panel.new_round_button.isEnabled()
|
||||
assert not window.run_panel.quick_run_button.isEnabled()
|
||||
assert window.plan_panel.table.rowCount() == 1
|
||||
window._project_queues['batch'] = ('old-queue-token', (task_id,))
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Yes)
|
||||
window.run_panel.new_round_button.click()
|
||||
qtbot.waitUntil(lambda: not window._workers and not window._loading and not window._context_query.busy)
|
||||
assert 'batch' not in window._project_queues
|
||||
assert window.plan_panel.table.rowCount() == 0
|
||||
assert not window.run_panel.quick_run_button.isEnabled()
|
||||
assert window.add_mapping_button.isEnabled()
|
||||
assert store.get_task(task_id).status is TaskStatus.DRAFT
|
||||
window.close()
|
||||
|
||||
|
||||
def test_commit_failure_rolls_back_database_and_restores_handoff(completed):
|
||||
service, store, task_id, _, _ = completed
|
||||
root = service.for_project_task(task_id)._quick_run_preparer.data_root
|
||||
history = root / 'quick-run-history'
|
||||
history.mkdir(parents=True)
|
||||
(history / 'proof').write_text('original')
|
||||
original = store._connection
|
||||
class FailCommit:
|
||||
def execute(self, sql, *args):
|
||||
if sql == 'COMMIT':
|
||||
raise RuntimeError('injected commit failure')
|
||||
return original.execute(sql, *args)
|
||||
def __getattr__(self, name):
|
||||
return getattr(original, name)
|
||||
store._connection = FailCommit()
|
||||
try:
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.start_new_round(task_id)
|
||||
assert not original.in_transaction
|
||||
assert store._transaction_depth == 0
|
||||
assert store.get_task(task_id).status is TaskStatus.COMPLETED
|
||||
assert store.list_target_plan(task_id)
|
||||
assert (history / 'proof').read_text() == 'original'
|
||||
finally:
|
||||
store._connection = original
|
||||
|
||||
|
||||
def test_committed_journal_uses_immutable_token_after_task_summary_changes(completed):
|
||||
from dx_productivity.trial_task_center.new_round import recover_archives
|
||||
service, store, task_id, _, _ = completed
|
||||
root = service.for_project_task(task_id)._quick_run_preparer.data_root
|
||||
history = root / 'quick-run-history'
|
||||
history.mkdir(parents=True)
|
||||
(history / 'proof').write_text('original')
|
||||
service.start_new_round(task_id)
|
||||
journal = next((service._logging.root / 'round-transitions').glob('*/journal.json'))
|
||||
(journal.parent / 'committed').unlink()
|
||||
store._connection.execute("UPDATE tasks SET summary = 'later edit' WHERE task_id = ?", (task_id,))
|
||||
recover_archives(service)
|
||||
assert (journal.parent / 'committed').exists()
|
||||
assert not history.exists()
|
||||
assert next((root / 'rounds').glob('*/quick-run-history/proof')).read_text() == 'original'
|
||||
|
||||
|
||||
def test_pristine_target_mode_sibling_with_no_enabled_rows_is_not_execution_validated(completed, tmp_path):
|
||||
service, store, task_id, _, target = completed
|
||||
other = store.create_task('draft-empty-plan')
|
||||
path = tmp_path / 'draft.prj'
|
||||
path.touch()
|
||||
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
|
||||
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
|
||||
store.record_target_inventory(other.task_id, (replace(target, project_path=path),))
|
||||
before = store.list_target_plan(other.task_id)
|
||||
service.start_new_round(task_id)
|
||||
assert store.list_target_plan(other.task_id) == before
|
||||
assert store.get_task(other.task_id).status is TaskStatus.DRAFT
|
||||
|
||||
|
||||
@pytest.mark.parametrize('marker', ['committed', 'rolled-back'])
|
||||
def test_terminal_corrupted_journal_does_not_block_round_recovery(completed, marker):
|
||||
from dx_productivity.trial_task_center.new_round import recover_archives
|
||||
service, _, _, _, _ = completed
|
||||
folder = service._logging.root / 'round-transitions' / 'terminal'
|
||||
folder.mkdir(parents=True)
|
||||
(folder / 'journal.json').write_text('{truncated')
|
||||
(folder / marker).touch()
|
||||
recover_archives(service)
|
||||
|
||||
|
||||
def test_failed_atomic_journal_write_does_not_publish_truncated_json(tmp_path, monkeypatch):
|
||||
from pathlib import Path
|
||||
from dx_productivity.trial_task_center.new_round import _write
|
||||
destination = tmp_path / 'journal.json'
|
||||
original = Path.write_text
|
||||
def fail_partial(path, text, **options):
|
||||
original(path, text[:4], **options)
|
||||
raise OSError('injected partial write')
|
||||
monkeypatch.setattr(Path, 'write_text', fail_partial)
|
||||
with pytest.raises(OSError, match='partial write'):
|
||||
_write(destination, {'moves': ['complete']})
|
||||
assert not destination.exists()
|
||||
assert not tuple(tmp_path.iterdir())
|
||||
@@ -0,0 +1,31 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow, compile_target_rules
|
||||
from dx_productivity.trial_task_center.store_target_plan import merge_target_inventory
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['compile', 'merge'])
|
||||
def test_plan_operations_resolve_each_project_once_and_refresh_next_call(tmp_path, monkeypatch, operation):
|
||||
projects = (tmp_path / 'one.prj', tmp_path / 'two.prj')
|
||||
rows = tuple(TargetPlanRow(ComponentTarget(path, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', 'V'), True, 'NEW')
|
||||
for path in projects for i in range(20))
|
||||
original = Path.resolve
|
||||
resolved = []
|
||||
def resolve(path, *args, **kwargs):
|
||||
resolved.append(str(path))
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'resolve', resolve)
|
||||
def run():
|
||||
if operation == 'compile':
|
||||
rules = compile_target_rules(rows)
|
||||
assert len(rules) == 2
|
||||
assert sum(len(rule.targets) for rule in rules) == 40
|
||||
else:
|
||||
assert merge_target_inventory(rows, tuple(row.target for row in rows)) == rows
|
||||
run()
|
||||
assert len(resolved) == 2
|
||||
resolved.clear()
|
||||
run()
|
||||
assert len(resolved) == 2, 'a later operation must resolve project identity again'
|
||||
@@ -0,0 +1,124 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center import legacy_paths, native_helper
|
||||
|
||||
|
||||
def long_project(tmp_path):
|
||||
folder = tmp_path / ('design-' + 'x' * 78) / ('revision-' + 'y' * 78)
|
||||
folder.mkdir(parents=True)
|
||||
project = folder / 'board.prj'
|
||||
project.write_text('project')
|
||||
assert len(str(project)) > 260
|
||||
return project
|
||||
|
||||
|
||||
def test_worker_prepares_project_access_without_changing_command_identity(tmp_path, monkeypatch):
|
||||
project = long_project(tmp_path)
|
||||
root = tmp_path / 'worker'
|
||||
root.mkdir()
|
||||
script = root / 'worker.vbs'
|
||||
script.write_text('runtime')
|
||||
command = f'job_id\tproject_path\njob\t{project}\n'
|
||||
(root / 'command.tsv').write_text(command, encoding='utf-8')
|
||||
monkeypatch.setattr(legacy_paths, '_short_path', lambda _: None)
|
||||
pool = legacy_paths._AliasPool()
|
||||
monkeypatch.setattr(legacy_paths, '_aliases', pool)
|
||||
try:
|
||||
legacy_paths.worker_paths(script, root)
|
||||
mapping = (root / 'project-access.tsv').read_text(encoding='utf-8').splitlines()
|
||||
assert mapping[0] == 'project_path\taccess_path'
|
||||
canonical, access = mapping[1].split('\t')
|
||||
assert Path(canonical) == project.resolve()
|
||||
assert len(access) < 160 and Path(access).resolve() == project.resolve()
|
||||
assert (root / 'command.tsv').read_text(encoding='utf-8') == command
|
||||
vbs = tmp_path / 'access-check.vbs'
|
||||
vbs.write_text('Set f=CreateObject("Scripting.FileSystemObject")\nWScript.Echo CStr(f.FileExists(WScript.Arguments(0)))\n')
|
||||
result = subprocess.run((r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(vbs), access), capture_output=True,text=True)
|
||||
assert result.stdout.strip() == 'True'
|
||||
finally:
|
||||
assert not pool.close()
|
||||
|
||||
|
||||
def test_native_context_accepts_same_project_via_junction_and_rejects_foreign(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import cad_identity
|
||||
project = long_project(tmp_path)
|
||||
pool = legacy_paths._AliasPool()
|
||||
monkeypatch.setattr(cad_identity, 'verify_application', lambda _: None)
|
||||
try:
|
||||
alias = pool.alias(project.parent) / project.name
|
||||
app = SimpleNamespace(GetProjectData=lambda: SimpleNamespace(GetProjectFilePath=lambda: str(alias)),
|
||||
ActiveView=SimpleNamespace(GetName=lambda _: 'MAIN', Block=SimpleNamespace(SheetNum='1')))
|
||||
metadata = ('job', str(project), 'OLD', 'NEW', 'MAIN:1')
|
||||
native_helper.check_active_context(app, metadata)
|
||||
with pytest.raises(ValueError, match='Active project changed'):
|
||||
native_helper.check_active_context(app, ('job', str(tmp_path / 'foreign.prj'), 'OLD', 'NEW', 'MAIN:1'))
|
||||
finally:
|
||||
assert not pool.close()
|
||||
|
||||
|
||||
def test_vbs_reopen_resolves_canonical_long_project_before_fso_check(tmp_path, monkeypatch):
|
||||
project = long_project(tmp_path)
|
||||
root = tmp_path / 'worker'
|
||||
root.mkdir()
|
||||
(root / 'command.tsv').write_text(f'project_path\n{project}\n', encoding='utf-8')
|
||||
pool = legacy_paths._AliasPool()
|
||||
monkeypatch.setattr(legacy_paths, '_aliases', pool)
|
||||
monkeypatch.setattr(legacy_paths, '_short_path', lambda _: None)
|
||||
source = (Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs').read_text(encoding='utf-8-sig')
|
||||
def function(name):
|
||||
return re.search(rf'(?ms)^Function {name}\(.*?^End Function', source).group()
|
||||
try:
|
||||
legacy_paths.worker_paths(root / 'worker.vbs', root)
|
||||
access = (root / 'project-access.tsv').read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
# Execute the production reopen boundary against real legacy FSO,
|
||||
# stopping before CAD calls; no imitation of path resolution here.
|
||||
boundary = re.search(r'(?ms)^Sub QPEnsureProject\(.*?(?= QP_Stage = "check_project")', source).group()
|
||||
script = tmp_path / 'reopen-check.vbs'
|
||||
script.write_text('Dim QP_Fso, QP_Root, QP_ProjectAccess, QP_AccessProject, App\n'
|
||||
'Set QP_Fso=CreateObject("Scripting.FileSystemObject")\n'
|
||||
'QP_Root=WScript.Arguments(0)\nSet App=Nothing\n'
|
||||
'QPEnsureProject App, WScript.Arguments(1)\n'
|
||||
+ boundary + 'WScript.Echo TargetPath\nEnd Sub\n'
|
||||
+ function('QPProjectAccessPath') + '\n'
|
||||
+ re.search(r'(?ms)^Sub QPEnsureProjectAccess\(\).*?^End Sub', source).group() + '\n'
|
||||
+ function('QPReadUtf8'), encoding='utf-8')
|
||||
result = subprocess.run((r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(script), str(root), str(project)),
|
||||
capture_output=True, text=True)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert Path(result.stdout.strip()) == Path(access)
|
||||
finally:
|
||||
assert not pool.close()
|
||||
|
||||
|
||||
def test_redirected_project_entry_is_rejected_before_native_launch(tmp_path, monkeypatch):
|
||||
import _winapi
|
||||
from dx_productivity.trial_task_center import quick_run
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
project = long_project(tmp_path)
|
||||
other = tmp_path / 'other'
|
||||
other.mkdir()
|
||||
(other / project.name).write_text('foreign')
|
||||
root = tmp_path / 'evidence'
|
||||
root.mkdir()
|
||||
pool = legacy_paths._AliasPool()
|
||||
try:
|
||||
access = pool.alias(project.parent)
|
||||
(root / 'project-access.tsv').write_text(f'project_path\taccess_path\n{project}\t{access / project.name}\n')
|
||||
access.rmdir()
|
||||
_winapi.CreateJunction(str(other), str(access))
|
||||
from dx_productivity.trial_task_center import isolated_cad
|
||||
monkeypatch.setattr(isolated_cad, 'run_isolated_process', lambda *a, **k: pytest.fail('foreign project launch'))
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
quick_run._run_process(('cscript', '//nologo', 'worker', str(root)), 1)
|
||||
assert error.value.code == 'target_identity'
|
||||
finally:
|
||||
# Restore the original binding before asking pool cleanup to remove it.
|
||||
if access.is_junction():
|
||||
access.rmdir()
|
||||
_winapi.CreateJunction(str(project.parent), str(access))
|
||||
assert not pool.close()
|
||||
@@ -22,7 +22,13 @@ while True:
|
||||
(root/'project-session-result.tsv').write_text(f'{session}\\t{job}\\tsaved_ok\\tsession_verified',encoding='utf-8')
|
||||
with (root/'steps.txt').open('a') as f:f.write(job+'\\n')
|
||||
while not (root/'project-session-next.tsv').exists():time.sleep(.005)
|
||||
token,job=(root/'project-session-next.tsv').read_text().split('\\t')
|
||||
# Match the real VBS continuation reader's bounded sharing-denial retry.
|
||||
for attempt in range(20):
|
||||
try:
|
||||
token,job=(root/'project-session-next.tsv').read_text().split('\\t')
|
||||
break
|
||||
except (PermissionError,FileNotFoundError):time.sleep(.05)
|
||||
else:raise RuntimeError('control read remained unavailable')
|
||||
(root/'project-session-next.tsv').unlink()
|
||||
if token!=session:sys.exit(8)
|
||||
if job=='close':break
|
||||
|
||||
@@ -52,11 +52,13 @@ def test_original_window_edits_target_plan_and_nc_without_export(qtbot, tmp_path
|
||||
qtbot.addWidget(window)
|
||||
window.open_task(task.task_id)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
assert '1.1.1' in window.windowTitle()
|
||||
assert '1.1.2' in window.windowTitle()
|
||||
table = window.plan_panel.table
|
||||
table.item(0, 0).setCheckState(Qt.CheckState.Checked)
|
||||
table.item(0, 9).setCheckState(Qt.CheckState.Unchecked)
|
||||
table.model().setData(table.model().index(0, 0), Qt.CheckState.Checked, Qt.ItemDataRole.CheckStateRole)
|
||||
table.model().setData(table.model().index(0, 9), Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole)
|
||||
assert '替换 1 个、保留 1 个' in window.plan_panel.summary.text()
|
||||
assert not window.run_panel.quick_run_button.isEnabled()
|
||||
assert window.plan_panel.export_bom_button.isEnabled()
|
||||
window.plan_panel.save()
|
||||
qtbot.waitUntil(lambda: not window._workers, timeout=5000)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
@@ -67,9 +69,10 @@ def test_original_window_edits_target_plan_and_nc_without_export(qtbot, tmp_path
|
||||
assert window.run_panel.quick_run_button.isEnabled()
|
||||
assert not (tmp_path / 'plan.xlsx').exists()
|
||||
# Switching tasks must not conceal an unsaved draft from group execution.
|
||||
table.item(0, 6).setText('OTHER')
|
||||
table.model().setData(table.model().index(0, 6), 'OTHER')
|
||||
window.plan_panel.bind_task(None)
|
||||
assert window.plan_panel.has_unsaved_plan((task.task_id,))
|
||||
window._close_plan_confirmer = lambda: "discard"
|
||||
window.close()
|
||||
store.close()
|
||||
|
||||
@@ -123,10 +126,39 @@ def test_project_plan_exposes_bom_import_and_template_actions(qtbot, tmp_path):
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
assert window.findChild(QPushButton, 'importBomPlan').text() == '导入 BOM'
|
||||
assert window.findChild(QPushButton, 'exportBomTemplate').text() == 'BOM 模板'
|
||||
assert window.plan_panel.export_bom_button.isEnabled()
|
||||
assert not window.task_list.filter.isVisible()
|
||||
window.close(); store.close()
|
||||
|
||||
|
||||
def test_blank_bom_can_be_downloaded_without_task_or_inventory(qtbot, tmp_path, monkeypatch):
|
||||
from openpyxl import load_workbook
|
||||
from PySide6.QtWidgets import QFileDialog
|
||||
from dx_productivity.trial_task_center.bom_plan import BOM_HEADERS
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
window = TrialTaskCenterWindow(service)
|
||||
qtbot.addWidget(window)
|
||||
qtbot.waitUntil(lambda: not window._task_query.busy)
|
||||
output = tmp_path / 'blank-bom.xlsx'
|
||||
monkeypatch.setattr(QFileDialog, 'getSaveFileName', lambda *args: (str(output), 'Excel (*.xlsx)'))
|
||||
assert window.plan_panel.export_bom_button.isEnabled()
|
||||
window.plan_panel.export_bom_button.click()
|
||||
qtbot.waitUntil(lambda: not window._workers and output.exists())
|
||||
workbook = load_workbook(output)
|
||||
try:
|
||||
assert tuple(cell.value for cell in workbook.active[1]) == BOM_HEADERS
|
||||
assert workbook.active.max_row == 1
|
||||
finally:
|
||||
workbook.close()
|
||||
window.close()
|
||||
store.close()
|
||||
|
||||
|
||||
def test_batch_rules_and_target_plan_are_above_project_summary(qtbot, tmp_path):
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
@@ -142,7 +174,8 @@ def test_batch_rules_and_target_plan_are_above_project_summary(qtbot, tmp_path):
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
qtbot.waitExposed(window)
|
||||
assert window.mapping_tabs.objectName() == 'batchPlanTabs'
|
||||
assert window.mapping_tabs.geometry().top() < window.project_summary.geometry().top()
|
||||
from PySide6.QtCore import QPoint
|
||||
assert window.mapping_tabs.mapTo(window, QPoint()).y() < window.project_summary.mapTo(window, QPoint()).y()
|
||||
assert window.mapping_tabs.tabText(0) == '本批料号规则'
|
||||
assert window.mapping_tabs.tabText(1) == '本批位号计划'
|
||||
window.close(); store.close()
|
||||
@@ -76,16 +76,19 @@ def test_all_steps_survive_reopening_completed_task(qtbot, tmp_path):
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
qtbot.waitUntil(lambda: not window._log_presenter.query.busy)
|
||||
assert window.run_panel.toggle_log_button.isChecked()
|
||||
assert window.run_panel.log_view.toPlainText().count('位号 R1:OLD → NEW') == 1
|
||||
assert window._log_presenter.log_text.count('位号 R1:OLD → NEW') == 1
|
||||
window.close(); store.close()
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(data))
|
||||
window = TrialTaskCenterWindow(service); qtbot.addWidget(window)
|
||||
window.open_task(task.task_id)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
# Reopening a completed task preserves the plan workspace; logs are on demand.
|
||||
assert not window.run_panel.toggle_log_button.isChecked()
|
||||
window._show_task_log()
|
||||
qtbot.waitUntil(lambda: not window._log_presenter.query.busy)
|
||||
assert window.run_panel.toggle_log_button.isChecked()
|
||||
text = window.run_panel.log_view.toPlainText()
|
||||
text = window._log_presenter.log_text
|
||||
assert '位号 R1:OLD → NEW' in text
|
||||
assert '位号 C2:OLD2 → NEW2' in text
|
||||
# Switching to a draft clears the previous task's modification details.
|
||||
@@ -93,7 +96,7 @@ def test_all_steps_survive_reopening_completed_task(qtbot, tmp_path):
|
||||
window.open_task(other.task_id)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
qtbot.waitUntil(lambda: not window._log_presenter.query.busy)
|
||||
assert '位号 R1' not in window.run_panel.log_view.toPlainText()
|
||||
assert '位号 R1' not in window._log_presenter.log_text
|
||||
window.close(); store.close()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
from dataclasses import replace
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
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, TargetPlanRow
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def group(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
root = tmp_path / 'projects'
|
||||
root.mkdir()
|
||||
for name in ('a', 'b'):
|
||||
(root / (name + '.prj')).write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
|
||||
tasks = service.create_project_tasks(root)
|
||||
targets = {t.task_id: ComponentTarget(store.list_projects(t.task_id)[0].path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V') for t in tasks}
|
||||
yield service, store, tasks, targets
|
||||
store.close()
|
||||
|
||||
|
||||
def test_save_all_rolls_back_confirmed_bom_when_later_standalone_plan_fails(group, tmp_path):
|
||||
service, store, tasks, targets = group
|
||||
a, b = (t.task_id for t in tasks)
|
||||
service.for_project_task(a)._quick_run_preparer.collect_inventory = lambda *args: (targets[a],)
|
||||
path = write_bom_template(tmp_path / 'a.xlsx', ({'project_path': str(targets[a].project_path),
|
||||
'old_part_number': 'OLD', 'new_part_number': 'NEW', 'refdes': 'R1'},))
|
||||
preview = service.preview_bom_batch(a, path)
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.save_plan_drafts(((preview, {a: preview.projects[0].rows}),), {b: (TargetPlanRow(targets[b], True, 'NEW'),)})
|
||||
assert not store.list_target_plan(a)
|
||||
assert not store.get_task(a).target_plan_mode
|
||||
# Retrying the very same preview must still work after the rollback.
|
||||
result = service.save_plan_drafts(((preview, {a: preview.projects[0].rows}),), {})
|
||||
assert result[a][0].enabled
|
||||
|
||||
|
||||
def test_service_extends_inventory_with_known_parts_and_preserves_saved_edits(group):
|
||||
service, store, tasks, targets = group
|
||||
task_id = tasks[0].task_id
|
||||
first = targets[task_id]
|
||||
second = replace(first, uid='u2', refdes='R2', old_part_number='OTHER')
|
||||
store.record_target_inventory(task_id, (first,))
|
||||
prior = TargetPlanRow(first, True, 'MANUAL', True, 'manual value', False)
|
||||
store.replace_target_plan(task_id, (prior,))
|
||||
service.add_rule(task_id, 'OTHER', 'OTHER-NEW', sync_nc=False)
|
||||
seen = []
|
||||
def collect(project, parts, **controls):
|
||||
seen.append(parts)
|
||||
return first, second
|
||||
service.for_project_task(task_id)._quick_run_preparer.collect_inventory = collect
|
||||
result = service.collect_target_inventory(task_id, ('OTHER',))
|
||||
assert set(seen[0]) == {'OLD', 'OTHER'}
|
||||
assert result[0] == prior
|
||||
assert not result[1].enabled and result[1].new_part_number == 'OTHER-NEW' and not result[1].sync_nc
|
||||
|
||||
|
||||
def test_cancelled_service_inventory_does_not_save_any_targets(group):
|
||||
service, store, tasks, targets = group
|
||||
task_id = tasks[0].task_id
|
||||
stop = Event()
|
||||
def collect(project, parts, **controls):
|
||||
stop.set()
|
||||
return (targets[task_id],)
|
||||
service.for_project_task(task_id)._quick_run_preparer.collect_inventory = collect
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
service.collect_target_inventory(task_id, ('OLD',), stop_event=stop)
|
||||
assert error.value.code == 'operation_cancelled'
|
||||
assert not store.list_target_plan(task_id) and not store.get_task(task_id).target_plan_mode
|
||||
@@ -0,0 +1,43 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
from threading import Timer
|
||||
|
||||
|
||||
def test_real_vbs_continuation_read_waits_out_windows_sharing_denial(tmp_path):
|
||||
import win32file
|
||||
import win32con
|
||||
source = (Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs').read_text(encoding='utf-8')
|
||||
functions = []
|
||||
for name in ('QPReadUtf8', 'QPReadContinuation'):
|
||||
match = re.search(r'^Function ' + name + r'\(.*?^End Function', source, re.M | re.S)
|
||||
assert match, name
|
||||
functions.append(match.group())
|
||||
script = tmp_path / 'read_control.vbs'
|
||||
script.write_text('\n'.join(functions) + '\nWScript.Echo "reading"\nWScript.Echo QPReadContinuation(WScript.Arguments(0))\n')
|
||||
control = tmp_path / 'control.tsv'
|
||||
control.write_text('token\tjob')
|
||||
held = win32file.CreateFile(str(control), win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
released = False
|
||||
def release():
|
||||
nonlocal released
|
||||
if not released:
|
||||
released = True
|
||||
held.Close()
|
||||
process = subprocess.Popen((r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(script), str(control)),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
timer = None
|
||||
try:
|
||||
assert process.stdout.readline().strip() == 'reading'
|
||||
timer = Timer(.2, release)
|
||||
timer.start()
|
||||
stdout, stderr = process.communicate(timeout=5)
|
||||
assert process.returncode == 0, stderr
|
||||
assert stdout.strip() == 'token\tjob'
|
||||
finally:
|
||||
if timer:
|
||||
timer.join()
|
||||
release()
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
|
||||
from dx_productivity.trial_task_center import application
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus, TaskStatus
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
|
||||
|
||||
def test_idle_startup_does_not_read_projects_of_every_task(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
for index in range(30):
|
||||
task = store.create_task(f'Board {index}')
|
||||
store.sync_projects(task.task_id, tmp_path, (tmp_path / f'{index}.prj',))
|
||||
queries = []
|
||||
store._connection.set_trace_callback(queries.append)
|
||||
try:
|
||||
TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
project_reads = [q for q in queries if q.startswith('SELECT * FROM projects WHERE task_id')]
|
||||
assert not project_reads, 'startup scans projects of every idle task'
|
||||
finally:
|
||||
store._connection.set_trace_callback(None)
|
||||
store.close()
|
||||
|
||||
|
||||
def test_application_restart_preserves_before_and_after_recovery_events(tmp_path, monkeypatch):
|
||||
store = TaskStore(tmp_path / 'task-center.db')
|
||||
task = store.create_task('Interrupted')
|
||||
project_path = tmp_path / 'board.prj'
|
||||
project_path.touch()
|
||||
project = store.sync_projects(task.task_id, tmp_path, (project_path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
store.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
probe = tmp_path / 'probe.json'
|
||||
probe.write_text('baseline')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path), probe_source_resolver=lambda *_: probe)
|
||||
service.start_task(task.task_id, disposable_copy_confirmed=True)
|
||||
store.close()
|
||||
|
||||
class Application:
|
||||
def __init__(self, _args):
|
||||
pass
|
||||
def exec(self):
|
||||
return 0
|
||||
|
||||
class Window:
|
||||
def __init__(self, service):
|
||||
assert service.get_task(task.task_id).status is TaskStatus.PAUSED
|
||||
assert service.projects(task.task_id)[0].status is ProjectStatus.FAILED
|
||||
def show(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(application, 'QApplication', Application)
|
||||
monkeypatch.setattr(application, '_load_window', lambda: Window)
|
||||
assert application.main(['--data-root', str(tmp_path)]) == 0
|
||||
events = [json.loads(line) for line in (tmp_path / 'tasks' / task.task_id / 'events.jsonl').read_text().splitlines()]
|
||||
recovery = [event for event in events if event['operation'] == 'recover_interrupted_work'
|
||||
and event['project_id'] == project.project_id]
|
||||
assert [event['details']['phase'] for event in recovery] == ['before', 'after']
|
||||
assert f'recovered_interrupted_projects={project.project_id}' in (tmp_path / 'logs/application.log').read_text()
|
||||
@@ -62,7 +62,8 @@ def test_recovery_selects_saved_unverified_job_before_next_pending_job():
|
||||
assert _recovery_command(commands, statuses) == commands[0]
|
||||
|
||||
|
||||
def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path):
|
||||
@pytest.mark.parametrize('code', ['recovery_verified', 'recovery_saved_verified'])
|
||||
def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path, code):
|
||||
script = tmp_path / 'QuickPartReplace.vbs'
|
||||
script.write_text("' fixture\n", encoding='ascii')
|
||||
preparer = QuickRunPreparer(tmp_path / 'data', script_source=script)
|
||||
@@ -74,9 +75,14 @@ def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path):
|
||||
(root / 'status.tsv').write_text(
|
||||
'job_id\tstate\tcode\tmessage\n'
|
||||
'a\tbatch_saved_unverified\t\treadback failed\n'
|
||||
'a\trestored_ok\t\trecovered\n', encoding='utf-8')
|
||||
f'a\trestored_ok\t{code}\trecovered\n', encoding='utf-8')
|
||||
|
||||
assert preparer.has_interrupted('t') is False
|
||||
from dx_productivity.trial_task_center.quick_run import _progress_from_queue
|
||||
project = type('Project', (), {'path': Path('board.prj')})()
|
||||
progress = _progress_from_queue((project,), _read_commands(root / 'command.tsv'),
|
||||
(('a', 'restored_ok', code, 'recovered'),), None)
|
||||
assert progress.saved_items == 1
|
||||
|
||||
|
||||
def test_native_context_rejects_missing_or_changed_target_without_no_match():
|
||||
|
||||
@@ -75,3 +75,21 @@ def test_target_table_find_next_selects_next_matching_row(qtbot):
|
||||
assert table.find_next() == 1
|
||||
assert table.find_next() == 2
|
||||
assert table.find_next() == 0
|
||||
|
||||
|
||||
def test_header_sort_edit_and_bulk_actions_keep_uid_binding(qtbot):
|
||||
table = TargetTable()
|
||||
qtbot.addWidget(table)
|
||||
rows = tuple(TargetPlanRow(ComponentTarget(Path('board.prj'), 'MAIN', '1', uid, ref, 'OLD', 'V'), enabled=True)
|
||||
for uid, ref in [('u2', 'R2'), ('u1', 'R1')])
|
||||
table.populate(rows)
|
||||
assert table.isSortingEnabled()
|
||||
table.sortByColumn(3, Qt.SortOrder.AscendingOrder)
|
||||
assert table.model().index(0, 3).data() == 'R1'
|
||||
table.model().setData(table.model().index(0, 6), 'NEW-R1')
|
||||
table.selectRow(1)
|
||||
table.apply_to_selected('NEW-R2')
|
||||
assert {r.target.uid: r.new_part_number for r in table.rows()} == {'u1': 'NEW-R1', 'u2': 'NEW-R2'}
|
||||
table.set_find_text('R1')
|
||||
table.select_all_targets(False)
|
||||
assert {r.target.uid: r.enabled for r in table.rows()} == {'u1': False, 'u2': True}
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user