示例#1
0
def get_bom_action(row, action_dict):
    print('\n')

    c = action_dict['client']
    did = action_dict['did']
    wvm = action_dict['wvm']
    eid = action_dict['eid']

    types = ["flattened", "top-level", "multi-level"]
    type_vals = {
        "flattened": (False, False),
        "top-level": (True, False),
        "multi-level": (True, True)
    }
    prompt_str = f'BOM type ({", ".join(types)})'
    type_cleaner = ci.ChoiceCleaner(types)
    use_type = ci.get_string(prompt=prompt_str,
                             cleaners=type_cleaner,
                             default="flattened",
                             commands=std_commands)
    indented, multi_level = type_vals[use_type]

    print(
        f'Fetching {multi_level} BOM from OnShape (did={did}, wvm={wvm}, eid={eid})'
    )
    response = c.get_assembly_bom(did,
                                  wvm,
                                  eid,
                                  indented=indented,
                                  multi_level=multi_level,
                                  generate_if_absent=True)
    response_json = json.loads(response.text)

    try:
        status = response_json['status']
        if status == 404:
            msg = response_json['message']
            print("\nStatus 404 returned: {}\n".format(msg))
            return
    except:
        pass

    bom_table = response_json['bomTable']
    format_ver = bom_table['formatVersion']
    name = bom_table['name']
    bom_type = bom_table['type']
    created_at = bom_table['createdAt']
    doc_name = bom_table['bomSource']['document']['name']
    top_pn = bom_table['bomSource']['element']['partNumber']

    try:
        top_revision = bom_table['bomSource']['element'][
            'revision']  # column may not be there..
    except (KeyError):
        top_revision = '--'

    state = bom_table['bomSource']['element']['state']
    title = (
        f"\n\n{bom_type} {name} (format version {format_ver}) - {doc_name} ({state} {top_pn}{top_revision}) created_at: {created_at}"
    )

    rows = []
    for idx, item in enumerate(bom_table['items']):
        item_num = item['item']
        qty = item['quantity']
        part_num = item['partNumber']
        desc = item['description']
        revision = item['revision']
        state = item['state']
        rows.append(
            ci.TableItem([qty, part_num, revision, state, desc], tag=item_num))

    col_names = "Qty PartNum Rev State Desc".split()
    ci.Table(rows, col_names=col_names, title=title,
             tag_str='ItemNums').show_table()
    print('\n')

    # export to csv
    if ci.get_yes_no(prompt='Export to CSV file', default='no') == 'yes':
        cmds = {'/cancel': ci.GetInputCommand(cancel_cmd_action)}
        file_name = ci.get_string(prompt="CSV file_name to export to: ",
                                  default=f"{top_pn}_bom_export.csv",
                                  commands=cmds)

        with open(file_name, "w", encoding='utf-8', newline='') as f:
            hdr = 'ITEM_NUM QUANTITY PART_NUM REVISION STATE DESCRIPTION'
            csv_writer = csv.writer(f)
            csv_writer.writerow([f'{bom_type} BOM for:', top_pn])
            csv_writer.writerow([])
            csv_writer.writerow(hdr.split())

            for item in bom_table['items']:
                csv_writer.writerow([
                    item['item'], item['quantity'], item['partNumber'],
                    item['revision'], item['state'], item['description']
                ])
示例#2
0
    print('/first (/f)\tGo to first page of the table')
    print('/last (/l)\tGo to last page of the table')
    print('/prev (/p)\tGo to previous page of the table')
    print('/next (/n)\tGo to next page of the table')
    print()

    return (ci.COMMAND_ACTION_NOP, None)


def cancel_cmd_action(cmd_str, cmd_vars, cmd_dict):
    print('\nCommand cancelled...')
    return (ci.COMMAND_ACTION_CANCEL, None)


std_commands = {
    '/?': ci.GetInputCommand(help_cmd_action),
    '/h': ci.GetInputCommand(help_cmd_action),
    '/help': ci.GetInputCommand(help_cmd_action),
    '/cancel': ci.GetInputCommand(cancel_cmd_action),
}

table_commands = {
    '/?': ci.GetInputCommand(help_cmd_action),
    '/h': ci.GetInputCommand(help_cmd_action),
    '/help': ci.GetInputCommand(help_cmd_action),
    '/cancel': ci.GetInputCommand(cancel_cmd_action),
    '/first': ci.GetInputCommand(ci.first_page_cmd_action),
    '/last': ci.GetInputCommand(ci.last_page_cmd_action),
    '/prev': ci.GetInputCommand(ci.prev_page_cmd_action),
    '/next': ci.GetInputCommand(ci.next_page_cmd_action),
}
示例#3
0

def cancel_action(cmd_str, cmd_vars, cmd_dict):
    print('\nCANCELLING OPERATION\n')
    return (ci.COMMAND_ACTION_CANCEL, None)


def use_red_action(cmd_str, cmd_vars, cmd_dict):
    return (ci.COMMAND_ACTION_USE_VALUE, 'red')


if __name__ == '__main__':
    prompt_str = 'Color (cmds /h, /?, /cancel, /red)'
    colors = ['red', 'blue', 'green', 'yellow', '/?']
    rows = [ci.TableItem(val, tag=val) for val in colors]
    show_help_cmd = ci.GetInputCommand(show_help_action)

    cmds = {
        '/h': show_help_cmd,
        '/?': show_help_cmd,
        '/cancel': ci.GetInputCommand(cancel_action),
        '/red': ci.GetInputCommand(use_red_action, {'color': 'red'})
    }

    try:
        tbl = ci.Table(rows,
                       col_names=['Color'],
                       prompt=prompt_str,
                       add_exit=False,
                       default_action=ci.TABLE_RETURN_FIRST_VAL,
                       commands=cmds)
示例#4
0
def make_table(start=32, end=0x007F, cat_filter='**', name_filter=''):
    """
    Creates and returns a cooked_input table containing Unicode characters (with ordinal values from start to end). The
    cat_filter and name_filter are added to the action_dict and used as an item filter for the table. For instance to look
    for letters use cat_filter 'L*', for upper case letters 'Lu', and for currency symbols '*c'. name_filter looks for a
    substring in the unicode character name. For example to fine a latin character use 'LATIN'.

    for start and stop values:

     code charts: https://www.unicode.org/Public/UCD/latest/charts/CodeCharts.pdf
        basic latin: 0000-00FF
        latin extended: 0100-024F
        spacing and modifiers: 02B0-02FF
        greek: 0370-03FF
        hebrew: 0590-05FF
        superscripts and subscripts: 2070-209F
        currency: 20A0-20CF
        math operators: 2200-22FF
        technical: 2300-23FF
        box drawing: 2500-257F
        block elements: 2580-259F
        misc symbols: 2600-26FF
        dingbats: 2700-27BF
        muscial symbols: 1D100-1D1FF
        emoticons: 1F600-1F64F

    utf-8 is: https://en.wikipedia.org/wiki/UTF-8, single octet - 0000-007F
    """
    tis = []
    col_names = "Character Category Name".split()
    for i in range(start, end):
        try:
            ch = chr(i)
            name = unicodedata.name(ch)
            cat = unicodedata.category(ch)
            ti = ci.TableItem(col_values=[ch, name, cat],
                              tag='{:X}'.format(i))  # use hex value as tag
            tis.append(ti)
        except (ValueError) as err:
            name = 'n/a'
        except (UnicodeEncodeError) as err:
            print('UnicodeEncodeError: couldn\'t encode char {}'.format(i))

    ad = {'cat_filter': cat_filter, 'name_filter': name_filter}

    help_cmd = ci.GetInputCommand(help_cmd_action)

    cmds = {
        '?': help_cmd,
        'help': help_cmd,
        'filter': ci.GetInputCommand(filter_cmd_action, cmd_dict=ad),
        'next': ci.GetInputCommand(ci.next_page_cmd_action),
        'prev': ci.GetInputCommand(ci.prev_page_cmd_action),
        'home': ci.GetInputCommand(ci.first_page_cmd_action),
        'end': ci.GetInputCommand(ci.last_page_cmd_action),
    }

    table = ci.Table(rows=tis,
                     col_names=col_names,
                     default_action=ci.TABLE_RETURN_FIRST_VAL,
                     item_filter=unicode_item_filter,
                     action_dict=ad,
                     add_exit=False,
                     commands=cmds)
    ad['table'] = table
    return table
示例#5
0

def cancel_cmd_action(cmd_str, cmd_vars, cmd_dict):
    if ci.get_yes_no(prompt='Are you sure you want to cancel?',
                     default='no') == 'yes':
        print('\nCommand cancelled...')
        return ci.CommandResponse(ci.COMMAND_ACTION_CANCEL, None)
    else:
        return ci.CommandResponse(ci.COMMAND_ACTION_NOP, None)


def exit_cmd_action(cmd_str, cmd_vars, cmd_dict):
    return ci.CommandResponse(ci.COMMAND_ACTION_EXIT, None)


help_cmd = ci.GetInputCommand(help_cmd_action)
cancel_cmd = ci.GetInputCommand(cancel_cmd_action)
app_cmds = {'/?': help_cmd, '/h': help_cmd, '/cancel': cancel_cmd}


def reset_db_action(row, action_item):
    cmds = action_dict['commands']
    if ci.get_yes_no(prompt='Delete all events? ', default='no',
                     commands=cmds) == 'yes':
        action_dict['events'] = []


def add_event_action(row, action_item):
    events = action_dict['events']
    event_types = action_dict['event_types']
    cmds = action_dict['commands']