1# -*- coding: utf-8 -*-23from dataclasses import asdict4from itertools import groupby5from typing import Any, Dict, List, Optional, Tuple, Union67from wireviz.DataClasses import AdditionalComponent, Cable, Color, Connector8from wireviz.wv_colors import translate_color9from wireviz.wv_gv_html import html_bgcolor_attr, html_line_breaks10from wireviz.wv_helper import clean_whitespace1112BOM_COLUMNS_ALWAYS = ('id', 'description', 'qty', 'unit', 'designators')13BOM_COLUMNS_OPTIONAL = ('pn', 'manufacturer', 'mpn', 'supplier', 'spn')14BOM_COLUMNS_IN_KEY = ('description', 'unit') + BOM_COLUMNS_OPTIONAL1516HEADER_PN = 'P/N'17HEADER_MPN = 'MPN'18HEADER_SPN = 'SPN'1920BOMKey = Tuple[str, ...]21BOMColumn = str # = Literal[*BOM_COLUMNS_ALWAYS, *BOM_COLUMNS_OPTIONAL]22BOMEntry = Dict[BOMColumn, Union[str, int, float, List[str], None]]2324def optional_fields(part: Union[Connector, Cable, AdditionalComponent]) -> BOMEntry:25 """Return part field values for the optional BOM columns as a dict."""26 part = asdict(part)27 return {field: part.get(field) for field in BOM_COLUMNS_OPTIONAL}2829def get_additional_component_table(harness: "Harness", component: Union[Connector, Cable]) -> List[str]:30 """Return a list of diagram node table row strings with additional components."""31 rows = []32 if component.additional_components:33 rows.append(["Additional components"])34 for part in component.additional_components:35 common_args = {36 'qty': part.qty * component.get_qty_multiplier(part.qty_multiplier),37 'unit': part.unit,38 'bgcolor': part.bgcolor,39 }40 if harness.options.mini_bom_mode:41 id = get_bom_index(harness.bom(), bom_entry_key({**asdict(part), 'description': part.description}))42 rows.append(component_table_entry(f'#{id} ({part.type.rstrip()})', **common_args))43 else:44 rows.append(component_table_entry(part.description, **common_args, **optional_fields(part)))45 return rows4647def get_additional_component_bom(component: Union[Connector, Cable]) -> List[BOMEntry]:48 """Return a list of BOM entries with additional components."""49 bom_entries = []50 for part in component.additional_components:51 bom_entries.append({52 'description': part.description,53 'qty': part.qty * component.get_qty_multiplier(part.qty_multiplier),54 'unit': part.unit,55 'designators': component.name if component.show_name else None,56 **optional_fields(part),57 })58 return bom_entries5960def bom_entry_key(entry: BOMEntry) -> BOMKey:61 """Return a tuple of string values from the dict that must be equal to join BOM entries."""62 if 'key' not in entry:63 entry['key'] = tuple(clean_whitespace(make_str(entry.get(c))) for c in BOM_COLUMNS_IN_KEY)64 return entry['key']6566def generate_bom(harness: "Harness") -> List[BOMEntry]:67 """Return a list of BOM entries generated from the harness."""68 from wireviz.Harness import Harness # Local import to avoid circular imports69 bom_entries = []70 # connectors71 for connector in harness.connectors.values():72 if not connector.ignore_in_bom:73 description = ('Connector'74 + (f', {connector.type}' if connector.type else '')75 + (f', {connector.subtype}' if connector.subtype else '')76 + (f', {connector.pincount} pins' if connector.show_pincount else '')77 + (f', {translate_color(connector.color, harness.options.color_mode)}' if connector.color else ''))78 bom_entries.append({79 'description': description, 'designators': connector.name if connector.show_name else None,80 **optional_fields(connector),81 })8283 # add connectors aditional components to bom84 bom_entries.extend(get_additional_component_bom(connector))8586 # cables87 # TODO: If category can have other non-empty values than 'bundle', maybe it should be part of description?88 for cable in harness.cables.values():89 if not cable.ignore_in_bom:90 if cable.category != 'bundle':91 # process cable as a single entity92 description = ('Cable'93 + (f', {cable.type}' if cable.type else '')94 + (f', {cable.wirecount}')95 + (f' x {cable.gauge} {cable.gauge_unit}' if cable.gauge else ' wires')96 + ( ' shielded' if cable.shield else '')97 + (f', {translate_color(cable.color, harness.options.color_mode)}' if cable.color else ''))98 bom_entries.append({99 'description': description, 'qty': cable.length, 'unit': cable.length_unit, 'designators': cable.name if cable.show_name else None,100 **optional_fields(cable),101 })102 else:103 # add each wire from the bundle to the bom104 for index, color in enumerate(cable.colors):105 description = ('Wire'106 + (f', {cable.type}' if cable.type else '')107 + (f', {cable.gauge} {cable.gauge_unit}' if cable.gauge else '')108 + (f', {translate_color(color, harness.options.color_mode)}' if color else ''))109 bom_entries.append({110 'description': description, 'qty': cable.length, 'unit': cable.length_unit, 'designators': cable.name if cable.show_name else None,111 **{k: index_if_list(v, index) for k, v in optional_fields(cable).items()},112 })113114 # add cable/bundles aditional components to bom115 bom_entries.extend(get_additional_component_bom(cable))116117 # add harness aditional components to bom directly, as they both are List[BOMEntry]118 bom_entries.extend(harness.additional_bom_items)119120 # remove line breaks if present and cleanup any resulting whitespace issues121 bom_entries = [{k: clean_whitespace(v) for k, v in entry.items()} for entry in bom_entries]122123 # deduplicate bom124 bom = []125 for _, group in groupby(sorted(bom_entries, key=bom_entry_key), key=bom_entry_key):126 group_entries = list(group)127 designators = sum((make_list(entry.get('designators')) for entry in group_entries), [])128 total_qty = sum(entry.get('qty', 1) for entry in group_entries)129 bom.append({**group_entries[0], 'qty': round(total_qty, 3), 'designators': sorted(set(designators))})130131 # add an incrementing id to each bom entry132 return [{**entry, 'id': index} for index, entry in enumerate(bom, 1)]133134def get_bom_index(bom: List[BOMEntry], target: BOMKey) -> int:135 """Return id of BOM entry or raise exception if not found."""136 for entry in bom:137 if bom_entry_key(entry) == target:138 return entry['id']139 raise Exception('Internal error: No BOM entry found matching: ' + '|'.join(target))140141def bom_list(bom: List[BOMEntry]) -> List[List[str]]:142 """Return list of BOM rows as lists of column strings with headings in top row."""143 keys = list(BOM_COLUMNS_ALWAYS) # Always include this fixed set of BOM columns.144 for fieldname in BOM_COLUMNS_OPTIONAL: # Include only those optional BOM columns that are in use.145 if any(entry.get(fieldname) for entry in bom):146 keys.append(fieldname)147 # Custom mapping from internal name to BOM column headers.148 # Headers not specified here are generated by capitilising the internal name.149 bom_headings = {150 'pn': HEADER_PN,151 'mpn': HEADER_MPN,152 'spn': HEADER_SPN,153 }154 return ([[bom_headings.get(k, k.capitalize()) for k in keys]] + # Create header row with key names155 [[make_str(entry.get(k)) for k in keys] for entry in bom]) # Create string list for each entry row156157def component_table_entry(158 type: str,159 qty: Union[int, float],160 unit: Optional[str] = None,161 bgcolor: Optional[Color] = None,162 pn: Optional[str] = None,163 manufacturer: Optional[str] = None,164 mpn: Optional[str] = None,165 supplier: Optional[str] = None,166 spn: Optional[str] = None,167 ) -> str:168 """Return a diagram node table row string with an additional component."""169 part_number_list = [170 pn_info_string(HEADER_PN, None, pn),171 pn_info_string(HEADER_MPN, manufacturer, mpn),172 pn_info_string(HEADER_SPN, supplier, spn),173 ]174 output = (f'{qty}'175 + (f' {unit}' if unit else '')176 + f' x {type}'177 + ('<br/>' if any(part_number_list) else '')178 + (', '.join([pn for pn in part_number_list if pn])))179 # format the above output as left aligned text in a single visible cell180 # indent is set to two to match the indent in the generated html table181 return f'''<table border="0" cellspacing="0" cellpadding="3" cellborder="1"{html_bgcolor_attr(bgcolor)}><tr>182 <td align="left" balign="left">{html_line_breaks(output)}</td>183 </tr></table>'''184185def pn_info_string(header: str, name: Optional[str], number: Optional[str]) -> Optional[str]:186 """Return the company name and/or the part number in one single string or None otherwise."""187 number = str(number).strip() if number is not None else ''188 if name or number:189 return f'{name if name else header}{": " + number if number else ""}'190 else:191 return None192193def index_if_list(value: Any, index: int) -> Any:194 """Return the value indexed if it is a list, or simply the value otherwise."""195 return value[index] if isinstance(value, list) else value196197def make_list(value: Any) -> list:198 """Return value if a list, empty list if None, or single element list otherwise."""199 return value if isinstance(value, list) else [] if value is None else [value]200201def make_str(value: Any) -> str:202 """Return comma separated elements if a list, empty string if None, or value as a string otherwise."""203 return ', '.join(str(element) for element in make_list(value))