Files
dxdesigner-part-replacement/tools/convert_cbb_bom.py
T

163 lines
7.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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))