Convert reviewed CBB BOM into existing template with source audit
This commit is contained in:
1 parent
791b3854b3
commit
4d8ba4c5bb
3 files changed
+249
No files matched your search
@@ -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,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,162 @@
|
||||
"""Convert a reviewed CBB list using the application's unchanged BOM writer.
|
||||
|
||||
This is an offline conversion utility. It never opens CAD or changes task data.
|
||||
M is the proposed replacement; V is retained as history, never a silent fallback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
import csv
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
||||
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl.comments import Comment
|
||||
|
||||
from dx_productivity.trial_task_center.bom_plan import write_bom_template, read_bom_records
|
||||
from dx_productivity.trial_task_center.project_tasks import scan_project_directory
|
||||
|
||||
|
||||
PART = re.compile(r'(?<![A-Za-z0-9-])[A-Za-z0-9]{4}-[A-Za-z0-9]+-[A-Za-z0-9]+(?![A-Za-z0-9-])')
|
||||
|
||||
|
||||
def project_index(projects):
|
||||
result = defaultdict(set)
|
||||
for project in projects:
|
||||
project = Path(project).resolve()
|
||||
for name in {project.stem, project.parent.name}:
|
||||
result[name.casefold()].add(project)
|
||||
return result
|
||||
|
||||
|
||||
def _text(value):
|
||||
return '' if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _csv_value(value):
|
||||
# Keep source formulas as visible text when the audit is opened in Excel.
|
||||
text = _text(value)
|
||||
return "'" + text if text.startswith(('=', '+', '-', '@')) else text
|
||||
|
||||
|
||||
def _export(path, entries):
|
||||
write_bom_template(path, (entry['record'] for entry in entries))
|
||||
workbook = load_workbook(path)
|
||||
try:
|
||||
for number, entry in enumerate(entries, 2):
|
||||
workbook.active.cell(number, 4).comment = Comment(entry['comment'], 'CBB conversion')
|
||||
workbook.save(path)
|
||||
finally:
|
||||
workbook.close()
|
||||
assert len(read_bom_records(path)) == len(entries)
|
||||
|
||||
|
||||
def convert(source: Path, projects, output_dir: Path):
|
||||
source, output_dir = Path(source), Path(output_dir)
|
||||
index = project_index(projects)
|
||||
workbook = load_workbook(source, read_only=True, data_only=False)
|
||||
try:
|
||||
sheet = workbook['结果']
|
||||
rows = list(sheet.iter_rows(values_only=True))
|
||||
finally:
|
||||
workbook.close()
|
||||
headers = rows[0]
|
||||
expected = {0: '文件名', 2: 'REFDES', 9: '旧料号', 12: '更换为新料号',
|
||||
21: '更换物料料号', 23: '是否更换完毕'}
|
||||
if any(len(headers) <= i or _text(headers[i]) != title for i, title in expected.items()):
|
||||
raise ValueError('结果表的列结构与本次 CBB 转换规则不一致')
|
||||
entries, audit = [], []
|
||||
names, mapped_names, conflicts = set(), set(), 0
|
||||
identities = defaultdict(list)
|
||||
for number, row in enumerate(rows[1:], 2):
|
||||
if not any(value is not None for value in row):
|
||||
continue
|
||||
row = tuple(row) + ('',) * max(0, 26 - len(row))
|
||||
name, refs, old, proposal, history = (_text(row[i]) for i in (0, 2, 9, 12, 21))
|
||||
names.add(name)
|
||||
paths = index.get(name.casefold(), set())
|
||||
path = str(next(iter(paths))) if len(paths) == 1 else ''
|
||||
if path:
|
||||
mapped_names.add(name)
|
||||
notes = []
|
||||
if not path:
|
||||
notes.append('工程路径待绑定' if not paths else '存在多个同名工程,待确认路径')
|
||||
exact = bool(PART.fullmatch(proposal))
|
||||
codes = PART.findall(proposal) if not proposal.startswith('=') else []
|
||||
new = proposal if exact else (codes[0] if len(codes) == 1 else '')
|
||||
conflict = exact and bool(PART.fullmatch(history)) and proposal != history
|
||||
conflicts += int(conflict)
|
||||
if conflict:
|
||||
notes.append('M/V新料号不同,保留M候选并停用待确认')
|
||||
if new and not exact:
|
||||
notes.append('M列含说明文字,提取的候选料号待确认')
|
||||
if '手工' in _text(row[4]):
|
||||
notes.append('原表标记手工处理')
|
||||
if new == old and new:
|
||||
notes.append('新旧料号相同')
|
||||
valid = bool(new and PART.fullmatch(old) and refs)
|
||||
if not valid:
|
||||
notes.append('未转为替换行:缺少明确的新旧料号或位号;原值保留在核对清单')
|
||||
status = 'converted' if valid else 'review_only'
|
||||
audit_row = [sheet.title, number, path, status, '; '.join(notes), *row[:len(headers)]]
|
||||
audit.append(audit_row)
|
||||
if not valid:
|
||||
continue
|
||||
comment = (f'来源:结果!{number}\nM(方案):{proposal}\nV(原记录):{history}\n'
|
||||
f'是否更换完毕(原标记):{_text(row[23])}\n原VALUE:{_text(row[3])}\n'
|
||||
f'原表说明:' + '\n'.join(_text(row[i]) for i in (4, 5, 7, 24, 25) if row[i])
|
||||
+ '\n转换核对:' + '; '.join(notes))
|
||||
entry = {'record': {'project_name': name, 'project_path': path, 'old_part_number': old,
|
||||
'new_part_number': new, 'refdes': refs, 'enabled': not notes,
|
||||
'sync_nc': True}, 'comment': comment, 'audit': audit_row, 'duplicate': False}
|
||||
entries.append(entry)
|
||||
for ref in re.split(r'[,,;;、\s]+', refs):
|
||||
if ref:
|
||||
identities[(path or name.casefold(), old.casefold(), ref.casefold())].append(entry)
|
||||
for group in identities.values():
|
||||
if len(group) > 1:
|
||||
for entry in group:
|
||||
entry['duplicate'] = True
|
||||
entry['record']['enabled'] = False
|
||||
message = '重复工程/旧料号/位号,待核对'
|
||||
if message not in entry['comment']:
|
||||
entry['comment'] += '\n' + message
|
||||
entry['audit'][4] += '; ' + message
|
||||
mapped = [entry for entry in entries if entry['record']['project_path'] and not entry['duplicate']]
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
full = output_dir / 'CBB_转换模板_全量待核对.xlsx'
|
||||
ready = output_dir / 'CBB_转换模板_已匹配工程.xlsx'
|
||||
audit_path = output_dir / 'CBB_逐行转换核对.csv'
|
||||
_export(full, entries)
|
||||
_export(ready, mapped)
|
||||
with audit_path.open('w', encoding='utf-8-sig', newline='') as stream:
|
||||
writer = csv.writer(stream)
|
||||
writer.writerow(['来源表', '来源行', '匹配工程路径', '转换状态', '核对说明', *headers])
|
||||
writer.writerows([_csv_value(value) for value in row] for row in audit)
|
||||
report = {'source_rows': len(audit), 'project_labels': len(names), 'matched_project_labels': len(mapped_names),
|
||||
'converted_rows': len(entries), 'mapped_rows': len(mapped),
|
||||
'mapped_enabled_rows': sum(e['record']['enabled'] for e in mapped),
|
||||
'conflict_rows': conflicts, 'review_only_rows': len(audit) - len(entries),
|
||||
'duplicate_candidate_rows': sum(e['duplicate'] for e in entries),
|
||||
'unmapped_projects': sorted(names - mapped_names), 'basis': 'M column; V retained for comparison',
|
||||
'completion_marker_filtered': False, 'template_headers_changed': False,
|
||||
'cad_started': False, 'task_database_changed': False,
|
||||
'full_file': str(full.resolve()), 'mapped_file': str(ready.resolve()),
|
||||
'audit_file': str(audit_path.resolve())}
|
||||
(output_dir / 'conversion-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
return report
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('source', type=Path)
|
||||
parser.add_argument('--project-root', type=Path, required=True)
|
||||
parser.add_argument('--output-dir', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(convert(args.source, scan_project_directory(args.project_root), args.output_dir),
|
||||
ensure_ascii=False, indent=2))
|
||||
Reference in new issue
Block a user