コード例 #1
0
    def test_caps(self):

        cat = PartCategory(self.api, 6)
        self.assertEqual(cat.name, "Transceivers")
        parts = cat.getParts()

        n_parts = len(parts)

        for p in parts:
            self.assertEqual(p.category, cat.pk)

        # Create some new parts
        for i in range(10):

            name = f"Part_{cat.pk}_{n_parts + i}"

            prt = Part.create(
                self.api, {
                    "category": cat.pk,
                    "name": name,
                    "description": "A new part in this category",
                })

            self.assertIsNotNone(prt)

            self.assertEqual(prt.name, name)

        parts = cat.getParts()

        self.assertEqual(len(parts), n_parts + 10)
コード例 #2
0
ファイル: inventree_api.py プロジェクト: KrypTiK1/Ki-nTree
def is_new_part(category_id: int, part_info: dict) -> int:
    ''' Check if part exists based on parameters (or description) '''
    global inventree_api

    # Get category object
    part_category = PartCategory(inventree_api, category_id)

    # Fetch all parts from category and subcategories
    part_list = []
    part_list.extend(part_category.getParts())
    for subcategory in part_category.getChildCategories():
        part_list.extend(subcategory.getParts())

    # Extract parameter from part info
    new_part_parameters = part_info['parameters']

    template_list = ParameterTemplate.list(inventree_api)

    def fetch_template_name(template_id):
        for item in template_list:
            if item.pk == template_id:
                return item.name

    # Retrieve parent category name for parameters compare
    try:
        category_name = part_category.getParentCategory().name
    except AttributeError:
        category_name = part_category.name
    filters = config_interface.load_category_parameters_filters(
        category=category_name,
        supplier_config_path=settings.CONFIG_PARAMETERS_FILTERS)
    # cprint(filters)

    for part in part_list:
        # Get part parameters
        db_part_parameters = part.getParameters()
        part_parameters = {}
        for parameter in db_part_parameters:
            parameter_name = fetch_template_name(parameter.template)
            parameter_value = parameter.data
            part_parameters[parameter_name] = parameter_value

        if new_part_parameters:
            # Compare database part with new part
            compare = part_tools.compare(
                new_part_parameters=new_part_parameters,
                db_part_parameters=part_parameters,
                include_filters=filters)
        else:
            # Compare with name and description
            compare = part_info['name'] == part.name or part_info[
                'description'] == part.description

        if compare:
            cprint(f'\n[TREE]\tFound part match in database (pk = {part.pk})',
                   silent=settings.HIDE_DEBUG)
            return part.pk

    cprint(f'\n[TREE]\tNo match found in database', silent=settings.HIDE_DEBUG)
    return 0
コード例 #3
0
def get_category_parameters(category_id: int) -> list:
    ''' Get all default parameter templates for category '''
    global inventree_api

    parameter_templates = []

    category = PartCategory(inventree_api, category_id)

    try:
        category_templates = category.get_category_parameter_templates(
            fetch_parent=True)
    except AttributeError:
        category_templates = None

    if category_templates:
        for template in category_templates:

            default_value = template.default_value
            if not default_value:
                default_value = '-'

            parameter_templates.append(
                [template.parameter_template['name'], default_value])

    return parameter_templates
コード例 #4
0
def checkAndCreatePartCat(partnodeCat,parent):
    partnodeCat = partnodeCat.replace('/','-')
    try:
        parent = parent.replace('/', '-')
    except:
        pass
    #print("checkAndCreatePartCat %s %s" % (partnodeCat,parent))
    cats = PartCategory.list(api,search=partnodeCat)
    for c in cats:
        if (c.name==partnodeCat):
            #print ("found ",partnodeCat)
            #print(c.name)
            if (c.parent==None) and (parent==None):
                return c
            if not(c.parent==None):
                parentCat = PartCategory(api,c.parent)
                #print("parentCat ",parentCat)
                #print("parentCat ", parentCat.name)
                if (parentCat.name == parent):
                    return c




    if (parent==None):
        cat = PartCategory.create(api,{
            'name' : partnodeCat,
            'description' : ''
        })
        #print("created ",cat," ",cat.pk)
        return cat
    else:
        parentCat = PartCategory.list(api, search=parent)
        #print("got parent ",parentCat)
        if (len(parentCat)>0):
            parentpk=None
            for pc in parentCat:
                if (pc.name==parent):
                    parentpk = pc
                    break

            #print(parentpk.name)
            #print(parentpk.pk)
            cat = PartCategory.create(api, {
                'name': partnodeCat,
                'description': '',
                'parent' : parentpk.pk
            })
            print("created ",cat," ",cat.pk)
            return cat
        else:
            print("checkAndCreatePartCat %s %s" % (partnodeCat, parent))
            print("Error parent given but not created previously")
            return None
コード例 #5
0
    def test_elec(self):
        electronics = PartCategory(self.api, 1)

        # This is a top-level category, should not have a parent!
        self.assertIsNone(electronics.getParentCategory())
        self.assertEqual(electronics.name, "Electronics")

        children = electronics.getChildCategories()
        self.assertGreaterEqual(len(children), 3)

        for child in children:
            self.assertEqual(child.parent, 1)

        child = PartCategory(self.api, pk=3)
        self.assertEqual(child.name, 'Capacitors')
        self.assertEqual(child.getParentCategory().pk, electronics.pk)

        # Grab all child categories
        children = PartCategory.list(self.api, parent=child.pk)

        n = len(children)

        for c in children:
            self.assertEqual(c.parent, child.pk)

        # Create some new categories under this one
        for idx in range(3):
            name = f"Subcategory {n+idx}"

            cat = PartCategory.create(
                self.api, {
                    "parent": child.pk,
                    "name": name,
                    "description": "A new subcategory",
                })

            self.assertEqual(cat.parent, child.pk)
            self.assertEqual(cat.name, name)

            # Edit the name of the new location
            cat.save({
                "name": f"{name}_suffix",
            })

            # Reload from server, and check
            cat.reload()
            self.assertEqual(cat.name, f"{name}_suffix")

        # Number of children should have increased!
        self.assertEqual(len(child.getChildCategories()), n + 3)
コード例 #6
0
def create_category(parent: str, name: str):
    ''' Create InvenTree category, use parent for subcategories '''
    global inventree_api

    parent_id = 0
    is_new_category = False

    # Check if category already exists
    category_list = PartCategory.list(inventree_api)
    for category in category_list:
        if name == category.name:
            try:
                # Check if parents are the same
                if category.getParentCategory().name == parent:
                    # Return category ID
                    return category.pk, is_new_category
            except:
                return category.pk, is_new_category
        elif parent == category.name:
            # Get Parent ID
            parent_id = category.pk
        else:
            pass

    if parent:
        if parent_id > 0:
            category = PartCategory.create(inventree_api, {
                'name': name,
                'parent': parent_id,
            })

            is_new_category = True
        else:
            cprint(f'[TREE]\tError: Check parent category name ({parent})', silent=settings.SILENT)
            return -1, is_new_category
    else:
        # No parent
        category = PartCategory.create(inventree_api, {
            'name': name,
            'parent': None,
        })
        is_new_category = True

    try:
        category_pk = category.pk
    except AttributeError:
        # User does not have the permission to create categories
        category_pk = 0

    return category_pk, is_new_category
コード例 #7
0
    def test_part_cats(self):
        """
        Tests for category filtering
        """

        # All categories
        cats = PartCategory.list(self.api)
        n = len(cats)
        self.assertTrue(len(cats) >= 9)

        # Filtered categories must be fewer than *all* categories
        cats = PartCategory.list(self.api, parent=1)

        self.assertGreater(len(cats), 0)
        self.assertLess(len(cats), n)
コード例 #8
0
def get_inventree_category_id(category_name: str,
                              parent_category_id=None) -> int:
    ''' Get InvenTree category ID from name, specificy parent if subcategory '''
    global inventree_api

    # Fetch all categories
    part_categories = PartCategory.list(inventree_api)

    for item in part_categories:
        if category_name == item.name:
            # Check parent id match (if passed as argument)
            match = True
            if parent_category_id:
                cprint(
                    f'[TREE]\t{item.getParentCategory().pk} ?= {parent_category_id}',
                    silent=settings.HIDE_DEBUG)
                if item.getParentCategory().pk != parent_category_id:
                    match = False
            if match:
                cprint(f'[TREE]\t{item.name} ?= {category_name} => True',
                       silent=settings.HIDE_DEBUG)
                return item.pk
        else:
            cprint(f'[TREE]\t{item.name} ?= {category_name} => False',
                   silent=settings.HIDE_DEBUG)

    return -1
コード例 #9
0
def find_category():
    categories = PartCategory.list(API)
    print("="*20)
    print("Choose a category")
    for idx, category in enumerate(categories):
        print("\t%d %s" %(idx, category.name))
    print("="*20)
    idx = int(input("> "))
    return categories[idx]
コード例 #10
0
MY_PASSWORD = '******'

api = InvenTreeAPI(SERVER_ADDRESS, username=MY_USERNAME, password=MY_PASSWORD)

#delete all the exisiting parts

itparts = Part.list(api)
for p in itparts:
    print("delete p ",p.name)
    p._data['active'] = False
    p.save()
    p.delete()

#delete all of the exisitng categories

cat = PartCategory.list(api)


for c in cat:
    print("delete c ",c.name)
    c.delete()



def checkAndCreatePartCat(partnodeCat,parent):
    partnodeCat = partnodeCat.replace('/','-')
    try:
        parent = parent.replace('/', '-')
    except:
        pass
    #print("checkAndCreatePartCat %s %s" % (partnodeCat,parent))