internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: inventree/InvenTree

Issue:
Admin interface can be super slow
Some pages on the admin interface takes ages (like, 10 seconds) to render.. 

Need to profile them to work out where the inefficiencies are.


Discussion:
For example the admin page for a "purchase order" is extremely slow to load.
I've noticed that too, thought it was my setup 😬 
Might be something that the django-debug-toolbar plugin can help us debug..
:thinking: Umm what?

![image](https://user-images.githubusercontent.com/4020546/125469676-658800ca-bbd0-4873-9fd9-f72038ff9e33.png)

Removed the inline items:

![image](https://user-images.githubusercontent.com/4020546/125476155-3eab8d9c-1d49-4354-8a0d-6506e7312714.png)


Resolving patch:
diff --git a/InvenTree/company/api.py b/InvenTree/company/api.py
--- a/InvenTree/company/api.py
+++ b/InvenTree/company/api.py
@@ -263,11 +263,7 @@ class SupplierPartList(generics.ListCreateAPIView):
     - POST: Create a new SupplierPart object
     """
 
-    queryset = SupplierPart.objects.all().prefetch_related(
-        'part',
-        'supplier',
-        'manufacturer_part__manufacturer',
-    )
+    queryset = SupplierPart.objects.all()
 
     def get_queryset(self):
 
diff --git a/InvenTree/company/models.py b/InvenTree/company/models.py
--- a/InvenTree/company/models.py
+++ b/InvenTree/company/models.py
@@ -430,6 +430,22 @@ class Meta:
     )
 
 
+class SupplierPartManager(models.Manager):
+    """ Define custom SupplierPart objects manager
+
+        The main purpose of this manager is to improve database hit as the
+        SupplierPart model involves A LOT of foreign keys lookups
+    """
+
+    def get_queryset(self):
+        # Always prefetch related models
+        return super().get_queryset().prefetch_related(
+            'part',
+            'supplier',
+            'manufacturer_part__manufacturer',
+        )
+
+
 class SupplierPart(models.Model):
     """ Represents a unique part as provided by a Supplier
     Each SupplierPart is identified by a SKU (Supplier Part Number)
@@ -450,6 +466,8 @@ class SupplierPart(models.Model):
         packaging: packaging that the part is supplied in, e.g. "Reel"
     """
 
+    objects = SupplierPartManager()
+
     @staticmethod
     def get_api_url():
         return reverse('api-supplier-part-list')
diff --git a/InvenTree/order/admin.py b/InvenTree/order/admin.py
--- a/InvenTree/order/admin.py
+++ b/InvenTree/order/admin.py
@@ -15,6 +15,7 @@
 
 class PurchaseOrderLineItemInlineAdmin(admin.StackedInline):
     model = PurchaseOrderLineItem
+    extra = 0
 
 
 class PurchaseOrderAdmin(ImportExportModelAdmin):


Test patch:
Repository: inventree/InvenTree

Issue:
Allow BOM pricing to be valid when using internal pricing
When Inventree pricing for the BOM is set to use internal pricing for BOM calculation it returns that a warning message: 
**Note: BOM pricing is incomplete for this part** 
even though all BOM components have valid internal pricing.
This PR will check if internal pricing is used.




Discussion:

Resolving patch:
diff --git a/InvenTree/part/models.py b/InvenTree/part/models.py
--- a/InvenTree/part/models.py
+++ b/InvenTree/part/models.py
@@ -1473,16 +1473,16 @@ def supplier_count(self):
         return self.supplier_parts.count()
 
     @property
-    def has_pricing_info(self):
+    def has_pricing_info(self, internal=False):
         """ Return true if there is pricing information for this part """
-        return self.get_price_range() is not None
+        return self.get_price_range(internal=internal) is not None
 
     @property
     def has_complete_bom_pricing(self):
         """ Return true if there is pricing information for each item in the BOM. """
-
+        use_internal = common.models.get_setting('PART_BOM_USE_INTERNAL_PRICE', False)
         for item in self.get_bom_items().all().select_related('sub_part'):
-            if not item.sub_part.has_pricing_info:
+            if not item.sub_part.has_pricing_info(use_internal):
                 return False
 
         return True


Test patch:
Repository: inventree/InvenTree

Issue:
Migration warns for phantom part changes 
Here is the warning:

```
Your models in app(s): 'part' have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
```

Running `manage.py makemigrations` does **not** generate new migration file...

Running `manage.py showmigrations part` shows all part migrations are complete.

I found this warning both with PostGreSQL and SQLite3, if that has anything to do with backend dependency.


Discussion:

Resolving patch:
diff --git a/InvenTree/InvenTree/fields.py b/InvenTree/InvenTree/fields.py
--- a/InvenTree/InvenTree/fields.py
+++ b/InvenTree/InvenTree/fields.py
@@ -55,7 +55,7 @@ class InvenTreeModelMoneyField(ModelMoneyField):
     
     def __init__(self, **kwargs):
         # detect if creating migration
-        if 'makemigrations' in sys.argv:
+        if 'migrate' in sys.argv or 'makemigrations' in sys.argv:
             # remove currency information for a clean migration
             kwargs['default_currency'] = ''
             kwargs['currency_choices'] = []


Test patch:
Repository: inventree/InvenTree

Issue:
Internal price is not filtered by part
Is this a normal behavior?
It looks like API call is missing `part` filter. So all parts have the same `Internal Cost` table.
![image](https://user-images.githubusercontent.com/10057327/128554895-e260548a-72fc-4b72-bbc9-6bb20f68cbd0.png)

![image](https://user-images.githubusercontent.com/10057327/128555122-911201c7-8a8a-415b-a2c2-324c7fc8cdcc.png)



Discussion:
@matmair do you have time to have a look at this one?
@SchrodingersGat will do

Resolving patch:
diff --git a/InvenTree/part/serializers.py b/InvenTree/part/serializers.py
--- a/InvenTree/part/serializers.py
+++ b/InvenTree/part/serializers.py
@@ -15,7 +15,8 @@
 
 from InvenTree.serializers import (InvenTreeAttachmentSerializerField,
                                    InvenTreeImageSerializerField,
-                                   InvenTreeModelSerializer)
+                                   InvenTreeModelSerializer,
+                                   InvenTreeMoneySerializer)
 from InvenTree.status_codes import BuildStatus, PurchaseOrderStatus
 from stock.models import StockItem
 
@@ -102,7 +103,12 @@ class PartSalePriceSerializer(InvenTreeModelSerializer):
 
     quantity = serializers.FloatField()
 
-    price = serializers.CharField()
+    price = InvenTreeMoneySerializer(
+        max_digits=19, decimal_places=4,
+        allow_null=True
+    )
+
+    price_string = serializers.CharField(source='price', read_only=True)
 
     class Meta:
         model = PartSellPriceBreak
@@ -111,6 +117,7 @@ class Meta:
             'part',
             'quantity',
             'price',
+            'price_string',
         ]
 
 
@@ -121,7 +128,12 @@ class PartInternalPriceSerializer(InvenTreeModelSerializer):
 
     quantity = serializers.FloatField()
 
-    price = serializers.CharField()
+    price = InvenTreeMoneySerializer(
+        max_digits=19, decimal_places=4,
+        allow_null=True
+    )
+
+    price_string = serializers.CharField(source='price', read_only=True)
 
     class Meta:
         model = PartInternalPriceBreak
@@ -130,6 +142,7 @@ class Meta:
             'part',
             'quantity',
             'price',
+            'price_string',
         ]
 
 


Test patch:
Repository: inventree/InvenTree

Issue:
Heartbeat has a datetime warning
From the worker logs:
`inventree-worker    | 00:51:15 [Q] INFO Process-1 created a task from schedule [InvenTree.tasks.heartbeat]
inventree-worker    | 00:51:15 [Q] INFO Process-1:3 processing [may-cat-eleven-beer]
inventree-worker    | Could not perform heartbeat task - App registry not ready
inventree-worker    | /usr/lib/python3.8/site-packages/django/db/models/fields/__init__.py:1416: RuntimeWarning: DateTimeField Task.started received a naive datetime (2021-08-10 00:21:15.816018) while time zone support is active.
inventree-worker    |   warnings.warn("DateTimeField %s received a naive datetime (%s)"
`

The heartbeat task references a non timezoned date which django complains about as USE_TZ is True in the settings.py



Discussion:

Resolving patch:
diff --git a/InvenTree/InvenTree/tasks.py b/InvenTree/InvenTree/tasks.py
--- a/InvenTree/InvenTree/tasks.py
+++ b/InvenTree/InvenTree/tasks.py
@@ -6,7 +6,8 @@
 import requests
 import logging
 
-from datetime import datetime, timedelta
+from datetime import timedelta
+from django.utils import timezone
 
 from django.core.exceptions import AppRegistryNotReady
 from django.db.utils import OperationalError, ProgrammingError
@@ -125,7 +126,7 @@ def heartbeat():
     except AppRegistryNotReady:
         return
 
-    threshold = datetime.now() - timedelta(minutes=30)
+    threshold = timezone.now() - timedelta(minutes=30)
 
     # Delete heartbeat results more than half an hour old,
     # otherwise they just create extra noise
@@ -149,7 +150,7 @@ def delete_successful_tasks():
         logger.info("Could not perform 'delete_successful_tasks' - App registry not ready")
         return
 
-    threshold = datetime.now() - timedelta(days=30)
+    threshold = timezone.now() - timedelta(days=30)
 
     results = Success.objects.filter(
         started__lte=threshold


Test patch:
Repository: inventree/InvenTree

Issue:
[FR] Turn off reports by default
**Problem**
A lot of report buttons do nothing on a fresh install

**Suggested solution**
Make reports a global setting and disable them by default.

**Describe alternatives you've considered**
We could also do nothing

**Do you want to develop this?**
Yes


Discussion:
@SchrodingersGat thoughts?
Yeah good point. Perhaps we could disable report buttons if there are no available report template associated with the view?

e.g. if there are no active "build order" report templates, then the "print report" button won't appear on the build page.

This may be in addition to a global "enable reporting" setting, which would remove the report buttons globally.
@SchrodingersGat do you want to dev this or should I?
Either way is fine, if you decide to go ahead with it let me know, there are some subtleties around reporting that I might need to point out :)
@SchrodingersGat  Ok, I will try to do this. Really need to better my understanding of the reporting features. What should I look out for?

Resolving patch:
diff --git a/InvenTree/common/models.py b/InvenTree/common/models.py
--- a/InvenTree/common/models.py
+++ b/InvenTree/common/models.py
@@ -768,6 +768,13 @@ class InvenTreeSetting(BaseInvenTreeSetting):
             'validator': InvenTree.validators.validate_part_name_format
         },
 
+        'REPORT_ENABLE': {
+            'name': _('Enable Reports'),
+            'description': _('Enable generation of reports'),
+            'default': False,
+            'validator': bool,
+        },
+
         'REPORT_DEBUG_MODE': {
             'name': _('Debug Mode'),
             'description': _('Generate reports in debug mode (HTML output)'),


Test patch:
Repository: inventree/InvenTree

Issue:
It would be great to be able to search by MPN.
It would be great to be able to search by MPN.

_Originally posted by @r0l1 in https://github.com/inventree/InvenTree/issues/2384#issuecomment-982929233_


Discussion:

Resolving patch:
diff --git a/InvenTree/part/api.py b/InvenTree/part/api.py
--- a/InvenTree/part/api.py
+++ b/InvenTree/part/api.py
@@ -1075,6 +1075,7 @@ def filter_queryset(self, queryset):
         'revision',
         'keywords',
         'category__name',
+        'manufacturer_parts__MPN',
     ]
 
 


Test patch:
Repository: inventree/InvenTree

Issue:
[BUG] Unable to create build output
<!---
Everything inside these brackets is hidden - please remove them where you fill out information.
--->


**Describe the bug**
On a fully allocated Build Order, I'm unable to create a build output.

**Steps to Reproduce**

1. Create any new Build Order
2. Fully allocate the stock as normal
3. Under the "Pending Items" tab, click "New Build Output"
4. Populate the Quantity field, check "Confirm" then click Submit

**Expected behavior**
The Build Output would be created.

**Actual Behavior**
Blocker: The application presents "Form errors exist" and no further action can be taken (as the required fields are complete)
![image](https://user-images.githubusercontent.com/2242776/155065676-936f6ece-8864-4227-a9ba-103af6f6addf.png)

Further inspection of the network in DevTools, shows a post to /api/build/1/create-output/ with the response:
```json
{"auto_allocate":["This field may not be null."]}
```

**Deployment Method**
- Docker

**Version Information**
InvenTree-Version: 0.6.0
Django Version: 3.2.12
Commit Hash: 37bd573
Commit Date: 2022-02-21
Database: postgresql
Debug-Mode: False
Deployed using Docker: True



Discussion:
Welcome to InvenTree! Please check the [contributing docs](https://inventree.readthedocs.io/en/latest/contribute/) on how to help.\nIf you experience setup / install issues please read all [install docs]( https://inventree.readthedocs.io/en/latest/start/intro/).
Confirmed that intercepting the POST and changing the payload to include `"auto_allocate":false` in the JSON results is successful creation of the build output.
@ssewell thanks for reporting!
I will take a deeper look in a few hours, should be a simple fix.
@ssewell could you provide the settings of the part you are trying to build?
Do you have a particular query I can run against PostgreSQL? Or which attributes do you need?
A screenshot of the parts page should be enough
![grafik](https://user-images.githubusercontent.com/66015116/155243904-f8a2b784-72f7-4a69-9272-c5149e6545eb.png)


Resolving patch:
diff --git a/InvenTree/build/serializers.py b/InvenTree/build/serializers.py
--- a/InvenTree/build/serializers.py
+++ b/InvenTree/build/serializers.py
@@ -236,6 +236,7 @@ def validate_serial_numbers(self, serial_numbers):
     auto_allocate = serializers.BooleanField(
         required=False,
         default=False,
+        allow_null=True,
         label=_('Auto Allocate Serial Numbers'),
         help_text=_('Automatically allocate required items with matching serial numbers'),
     )


Test patch:
Repository: inventree/InvenTree

Issue:
[BUG] part.has_complete_bom_pricing is broken by c6fd2281
**Describe the bug**

There are two code errors in https://github.com/inventree/InvenTree/commit/c6fd2281d689309007b06c46560e6f446ee931bd which completely break the part.has_complete_bom_pricing property (at least in head, and the current stable release... and afaict, the code was never correct, but I haven't gone back to check).

The issues are:
1) before the loop - calling common.models.get_setting instead of common_models.InvenTreeSetting.get_setting when trying to retrieve PART_BOM_USE_INTERNAL_PRICE - afaict there is no get_setting method at the module level and never has been, only in the class... 
2) within the loop passing an argument (use_internal) to the has_pricing_info property of the sub_part, e.g. attempts to call a property as a method, this is not supported, and Python raises an exception. 

These problems have been hidden, because the way this property is used (within template if statements, as a property checking for falseness) falls victim to Django's bug (https://code.djangoproject.com/ticket/17664) where the exception is wrapped and compared to the == False part of the statement.... so the fact an exception is being raised in this method is not highlighted. 

**Steps to Reproduce**

1. Create a part with no pricing info
2. Create a part with pricing info
3. Create a composite part with a BOM that includes each of the parts created at step 1 and 2
4. Navigate to the Pricing tab of part created in 3

**Expected behavior**

A warning should be shown below the BOM pricing table stating that BOM pricing is incomplete for this part. Instead no warning is shown because the method is failing and the exception is somehow being eaten within the template processing... 

**Deployment Method**
N/A

**Version Information**

Running from HEAD


Discussion:
I have a fix for this and will send a pull request shortly. 

Resolving patch:
diff --git a/InvenTree/part/models.py b/InvenTree/part/models.py
--- a/InvenTree/part/models.py
+++ b/InvenTree/part/models.py
@@ -1529,17 +1529,12 @@ def supplier_count(self):
         """Return the number of supplier parts available for this part."""
         return self.supplier_parts.count()
 
-    @property
-    def has_pricing_info(self, internal=False):
-        """Return true if there is pricing information for this part."""
-        return self.get_price_range(internal=internal) is not None
-
     @property
     def has_complete_bom_pricing(self):
         """Return true if there is pricing information for each item in the BOM."""
-        use_internal = common.models.get_setting('PART_BOM_USE_INTERNAL_PRICE', False)
+        use_internal = common.models.InvenTreeSetting.get_setting('PART_BOM_USE_INTERNAL_PRICE', False)
         for item in self.get_bom_items().all().select_related('sub_part'):
-            if not item.sub_part.has_pricing_info(use_internal):
+            if item.sub_part.get_price_range(internal=use_internal) is None:
                 return False
 
         return True


Test patch:
Repository: inventree/InvenTree

Issue:
[FR] Make "confirm" buttons a user-configurable option
Some complaints from users that the "confirm" buttons on some dialogs are too "onerous"

Might be worth making this a simple user-configurable option (default=on)


Discussion:
While I cannot see me disabling this an option cannot hurt.
I assume this is referring to the confirm slider on some dialogs not the entire confirm dialog in general?

If it is just the slider, I can see where power users would like to not have the extra click.  If it is the entire dialog, I like Matmair, can't see me using it.
I mean a default that does not change the current behavior should be fine. Hobbyists probably do not need the extra check.

Resolving patch:
diff --git a/InvenTree/common/models.py b/InvenTree/common/models.py
--- a/InvenTree/common/models.py
+++ b/InvenTree/common/models.py
@@ -850,6 +850,13 @@ def save(self, *args, **kwargs):
             'default': False,
         },
 
+        'INVENTREE_REQUIRE_CONFIRM': {
+            'name': _('Require confirm'),
+            'description': _('Require explicit user confirmation for certain action.'),
+            'validator': bool,
+            'default': True,
+        },
+
         'BARCODE_ENABLE': {
             'name': _('Barcode Support'),
             'description': _('Enable barcode scanner support'),


Test patch:
Repository: inventree/InvenTree

Issue:
[FR] Add plugin keys, state and version  to version info
We should include info about the plugin environment to make debugging that stuff easier.

I want to develop this.

Ref: https://github.com/inventree/InvenTree/issues/3355#issuecomment-1206532243_


Discussion:
@matmair This sound like a brilliant idea. Another good idea will be if the author of the plugin didn't confirm the plugin works for > X version and modified it accordingly to support it, the plugin will be disabled by default and can't be re-enabled unless the version is modified. Basically, each plugin will have env version and if it's 0.7.X but the version is 0.8.X then the plugin will be disabled by default.
@Zontex that might also be good but will most likely require a breaking change to the basic plugin metadata so the earliest this could be done is 0.9.x
Do you mind opening a issue for that?
> @Zontex that might also be good but will most likely require a breaking change to the basic plugin metadata so the earliest this could be done is 0.9.x Do you mind opening an issue for that?

#3478 

Resolving patch:
diff --git a/InvenTree/InvenTree/api.py b/InvenTree/InvenTree/api.py
--- a/InvenTree/InvenTree/api.py
+++ b/InvenTree/InvenTree/api.py
@@ -12,6 +12,7 @@
 
 from InvenTree.mixins import ListCreateAPI
 from InvenTree.permissions import RolePermission
+from part.templatetags.inventree_extras import plugins_info
 
 from .status import is_worker_running
 from .version import (inventreeApiVersion, inventreeInstanceName,
@@ -36,6 +37,7 @@ def get(self, request, *args, **kwargs):
             'apiVersion': inventreeApiVersion(),
             'worker_running': is_worker_running(),
             'plugins_enabled': settings.PLUGINS_ENABLED,
+            'active_plugins': plugins_info(),
         }
 
         return JsonResponse(data)
diff --git a/InvenTree/part/templatetags/inventree_extras.py b/InvenTree/part/templatetags/inventree_extras.py
--- a/InvenTree/part/templatetags/inventree_extras.py
+++ b/InvenTree/part/templatetags/inventree_extras.py
@@ -17,6 +17,7 @@
 from common.models import ColorTheme, InvenTreeSetting, InvenTreeUserSetting
 from common.settings import currency_code_default
 from InvenTree import settings, version
+from plugin import registry
 from plugin.models import NotificationUserSetting, PluginSetting
 
 register = template.Library()
@@ -149,6 +150,25 @@ def plugins_enabled(*args, **kwargs):
     return djangosettings.PLUGINS_ENABLED
 
 
+@register.simple_tag()
+def plugins_info(*args, **kwargs):
+    """Return information about activated plugins."""
+    # Check if plugins are even enabled
+    if not djangosettings.PLUGINS_ENABLED:
+        return False
+
+    # Fetch plugins
+    plug_list = [plg for plg in registry.plugins.values() if plg.plugin_config().active]
+    # Format list
+    return [
+        {
+            'name': plg.name,
+            'slug': plg.slug,
+            'version': plg.version
+        } for plg in plug_list
+    ]
+
+
 @register.simple_tag()
 def inventree_db_engine(*args, **kwargs):
     """Return the InvenTree database backend e.g. 'postgresql'."""


Test patch:
Repository: inventree/InvenTree

Issue:
Django not available on startup
@matmair bad news. This has broken *stuff*..

https://github.com/inventree/InvenTree/runs/7837878419?check_suite_focus=true

Basically, the `invoke` script makes use of this file and must run *before* django is installed. Classic chicken and egg.

I think we might have to revert this one? LMK if you can see a cleaner solution otherwise I'll rewind this.

_Originally posted by @SchrodingersGat in https://github.com/inventree/InvenTree/issues/3536#issuecomment-1214999583_


Discussion:

Resolving patch:
diff --git a/InvenTree/InvenTree/config.py b/InvenTree/InvenTree/config.py
--- a/InvenTree/InvenTree/config.py
+++ b/InvenTree/InvenTree/config.py
@@ -7,9 +7,6 @@
 import string
 from pathlib import Path
 
-from django.contrib.staticfiles.storage import StaticFilesStorage
-from django.core.files.storage import default_storage
-
 import yaml
 
 logger = logging.getLogger('inventree')
@@ -213,6 +210,9 @@ def get_custom_file(env_ref: str, conf_ref: str, log_ref: str, lookup_media: boo
 
     Set lookup_media to True to also search in the media folder.
     """
+    from django.contrib.staticfiles.storage import StaticFilesStorage
+    from django.core.files.storage import default_storage
+
     value = get_setting(env_ref, conf_ref, None)
 
     if not value:


Test patch: