Example #1
0
def list_parts_action(row, action_dict):
    print('\n')

    c = action_dict['client']
    did = action_dict['did']
    wvm = action_dict['wvm']
    response = c.get_parts_list(did, wvm)
    response_json = json.loads(response.text)

    rows = []
    for i, item in enumerate(response_json):
        name = item['name']
        desc = item['description']
        state = item['state']
        element_id = item['elementId']
        part_num = item['partNumber']
        revision = item['revision']
        microversion_id = item['microversionId']
        is_hidden = item['isHidden']
        # is_mesh = item['isMesh']
        # lots more... appearance, bodyType, etc.

        # print('item {}: name={}, desc={}, state={},  elementID={}, partNumber={}, revision={}, microversionId={}, isHidden={}'.format(i,
        #         name, desc, state, element_id, part_num, revision, microversion_id, is_hidden))
        rows.append(
            ci.TableItem([
                name, desc, state, element_id, part_num, revision,
                microversion_id, is_hidden
            ]))

    col_names = "Name Description State Id PartNum Revision, MicroversionId isHidden".split(
    )
    ci.Table(rows, col_names=col_names, title='OnShape Parts',
             tag_str='#').show_table()
    print('\n')
Example #2
0
def create_docs_table(c, docs):
    """
    Create a table containing documents from OnShape. c is the onShape client and docs
    :param c: an onshapepy client
    :param docs: a json list of documents from onshapepy

    :return: a cooked_input Table containing a list of documents
    """
    style = ci.TableStyle(show_cols=True,
                          show_border=True,
                          hrules=ci.RULE_FRAME,
                          vrules=ci.RULE_ALL)
    rows = []
    print('fetching documents ', end='', flush=True)
    for page in Pager(c, docs):
        print('.', end='', flush=True)
        for item in page['items']:
            rows.append(DocRow(item))

    print('\n\n')
    fields = ["Name", "did", "CreatedAt", "Default Workspace", "ModifiedAt"]
    tis = [
        ci.TableItem([
            row.name, row.did, row.created_at, row.default_workspace,
            row.modified_at
        ],
                     tag=None,
                     item_data={'row': row}) for row in rows
    ]
    tbl = ci.Table(tis,
                   fields,
                   default_action=ci.TABLE_RETURN_TABLE_ITEM,
                   add_exit=False,
                   style=style)
    return tbl
Example #3
0
def db_submenu_action(row, action_item):
    style = action_dict['menu_style']
    items = [ci.TableItem('Delete all events', action=reset_db_action)]
    menu = ci.Table(rows=items,
                    add_exit=ci.TABLE_ADD_RETURN,
                    style=style,
                    action_dict=action_dict)
    menu.run()
Example #4
0
def list_teams_action(row, action_dict):
    c = action_dict['client']
    response = c.list_teams()

    rows = []

    for response_json in Pager(c, response):
        for item in response_json['items']:
            name = item['name']
            item_id = item['id']
            description = item['description']
            href = item['href']
            rows.append(ci.TableItem([name, item_id, description, href]))

    col_names = "Name Id Description HREF".split()
    ci.Table(rows, col_names=col_names, title='OnShape Teams',
             tag_str='#').show_table()
    print('\n')
Example #5
0
def create_eids_table(c, eids, assemblies_only=True):
    """
    Create a table containing elements for an  OnShape document

    :param c: an onshapepy client
    :param eids: a json list of document elements from onshapepy
    :param assemblies_only: if true only shows assembly elements

    tables are ignoring: type, lengthUnits, angleUnits, massUnits, foreignDataId

    :return: a cooked_input Table containing a list of elements
    """
    style = ci.TableStyle(show_cols=True,
                          show_border=True,
                          hrules=ci.RULE_FRAME,
                          vrules=ci.RULE_ALL)
    tis = []

    for item in eids:
        element_type = item['elementType']

        if assemblies_only and element_type != "ASSEMBLY":
            continue

        name = item['name']
        item_id = item['id']
        micro_version_id = item['microversionId']
        tis.append(
            ci.TableItem([name, item_id, element_type, micro_version_id],
                         tag=None,
                         item_data={'item': item}))

    fields = "Name Id ElementType MicroversionId".split()
    tbl = ci.Table(tis,
                   fields,
                   default_action=ci.TABLE_RETURN_TABLE_ITEM,
                   add_exit=False,
                   tag_str='#',
                   style=style)
    print('\n')
    return tbl
Example #6
0
def list_workspaces_action(row, action_dict):
    print('\n')

    c = action_dict['client']
    did = action_dict['did']
    response = c.get_workspaces(did)
    response_json = json.loads(response.text)

    rows = []
    for i, item in enumerate(response_json):
        read_only = item['isReadOnly']
        modified_at = item['modifiedAt']
        name = item['name']
        item_id = item['id']
        href = item['href']
        rows.append(
            ci.TableItem([name, item_id, read_only, modified_at, href[:50]]))

    col_names = "Name ItemId ReadOnly Modified HREF".split()
    ci.Table(rows,
             col_names=col_names,
             title='OnShape Workspaces',
             tag_str='#').show_table()
    print('\n')
Example #7
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']
                ])
Example #8
0
    ad = {
        'client': c,
        'did': TEST_ASSEM_DOC_ID,
        'team': IO_ENGR_TEAM_ID,
        'company': IO_COMPANY_ID,
        'did': TEST_ASSEM_DOC_ID,
        'wvm': MAIN_WORKSPACE,
        'eid': TEST_ASSEM_ELEM_ID,
        'name_filter': None,
    }

    style = ci.TableStyle(show_cols=False, show_border=False)

    tis = [
        # ci.TableItem('Set document name filter string', action=set_name_filter_action),
        ci.TableItem('List Documents', action=list_documents_action),
        ci.TableItem('Get did for a document', action=get_document_action),
        ci.TableItem('Get eid for a document', action=get_eid_action),
        ci.TableItem('Get did, wvm and eid from a url',
                     action=get_dwe_from_url_action),
        ci.TableItem('List Teams', action=list_teams_action),
        ci.TableItem('List Workspaces', action=list_workspaces_action),
        ci.TableItem('List Elements', action=list_elements_action),
        ci.TableItem('List Parts', action=list_parts_action),
        ci.TableItem('List Stats', action=list_stats_action),
        ci.TableItem('Get BOM', action=get_bom_action),
    ]
    print()
    menu = ci.Table(tis,
                    add_exit=ci.TABLE_ADD_EXIT,
                    style=style,
Example #9
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
Example #10
0
    return (ci.COMMAND_ACTION_NOP, None)


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,
Example #11
0
def table_item_factory(row):
    values = [row[1], '${:.2f}'.format(row[2])]
    ti = ci.TableItem(values, item_data={'price': row[2]})
    return ti
Example #12
0

def db_submenu_action(row, action_item):
    style = action_dict['menu_style']
    items = [ci.TableItem('Delete all events', action=reset_db_action)]
    menu = ci.Table(rows=items,
                    add_exit=ci.TABLE_ADD_RETURN,
                    style=style,
                    action_dict=action_dict)
    menu.run()


if __name__ == '__main__':
    style = ci.TableStyle(show_cols=False, show_border=False)
    action_dict = {
        'events': events,
        'event_types': event_types,
        'commands': app_cmds,
        'style': style
    }

    items = [
        ci.TableItem('Add an event', action=add_event_action),
        ci.TableItem('List events', action=list_event_action),
        ci.TableItem('Database submenu', action=db_submenu_action)
    ]
    menu = ci.Table(rows=items,
                    add_exit=ci.TABLE_ADD_EXIT,
                    style=style,
                    action_dict=action_dict)
    menu.run()
Example #13
0
            cache_content = (created.timestamp(), endpoints)
            with open(CACHED_ENDPOINT_FILE, 'w') as f:
                f.write(json.dumps(cache_content))
    else:
        print('Using saved api endpoints...\n')

        with open(CACHED_ENDPOINT_FILE, 'r') as f:
            content_str = f.read()
            cache_content = json.loads(content_str)
            created = datetime.date.fromtimestamp(cache_content[0])
            endpoints = cache_content[1]

    style = ci.TableStyle(rows_per_page=99, show_cols=False, show_border=False)
    item_data = {'endpoints': endpoints, 'style': style}
    action_dict = {'endpoints': endpoints, 'created': created, 'style': style}

    main_menu_items = [
        ci.TableItem(col_values=["Get info for an individual endpoint"],
                     action=get_endpoint_groups_action,
                     item_data=item_data),
        ci.TableItem(col_values=["Export api documentation as html"],
                     action=create_html_action,
                     item_data=item_data),
    ]
    main_menu = ci.Table(rows=main_menu_items,
                         prompt='Choose a menu item',
                         style=style,
                         add_exit=True,
                         action_dict=action_dict)
    main_menu.run()