small fixes (#13342)

* merge duplicate branches

* fix type

* remove impossible branches

* fix types

* make more tolerant

* update queries

* fix sec check
This commit is contained in:
Matthias Mair authored and GitHub committed 2026-11-23 23:40:30 +11:00
1 parent 4dfbabe496
commit 629a411612
14 files changed
+103 -111

No files matched your search

@@ -34,15 +34,13 @@ class Command(BaseCommand):
self.stdout.write('Database connection failed, retrying ...')
self.stdout.flush()
else:
if not connection.is_usable():
if verbose:
self.stdout.write('Database configuration is not usable')
self.stdout.flush()
if connected:
if verbose:
self.stdout.write('Database connection successful!')
if not connection.is_usable() and verbose:
self.stdout.write('Database configuration is not usable')
self.stdout.flush()
if connected and verbose:
self.stdout.write('Database connection successful!')
self.stdout.flush()
else:
time.sleep(1)
+5 -5
View File
@@ -145,11 +145,11 @@ class InvenTreeMetadata(SimpleMetadata):
del actions[method]
# Add a 'DELETE' action if we are allowed to delete
if 'DELETE' in view.allowed_methods:
if check_user_permission(user, self.model, 'delete') or (
role_required and check_user_role(user, role_required, 'delete')
):
actions['DELETE'] = {}
if 'DELETE' in view.allowed_methods and (
check_user_permission(user, self.model, 'delete')
or (role_required and check_user_role(user, role_required, 'delete'))
):
actions['DELETE'] = {}
metadata['actions'] = actions
+28 -20
View File
@@ -85,9 +85,9 @@ class FilterableSerializerMixin:
This introduces overhead during initialization, so only use this mixin when necessary.
"""
optional_filters: dict = None
fields_to_remove: set = None
optional_fields: set = None
optional_filters: Optional[dict[str, bool]] = None
fields_to_remove: Optional[set[str]] = None
optional_fields: Optional[set[str]] = None
filter_on_query: bool = True
# Keyword argument used to pass the requesting user to nested serializers
@@ -113,8 +113,9 @@ class FilterableSerializerMixin:
super().__init__(*args, **kwargs)
# Ensure any fields we are *not* using are removed
for field_name in self.fields_to_remove:
self.fields.pop(field_name, None)
if _fields := self.fields_to_remove:
for field_name in _fields:
self.fields.pop(field_name, None)
def is_exporting(self) -> bool:
"""Determine if we are exporting data."""
@@ -152,8 +153,11 @@ class FilterableSerializerMixin:
# This allows multiple optional fields to share the same filter value
# Note: fields sharing a filter_ref may still embed different models, so the
# permission gate is re-applied per-field even when the raw value is cached
cached_value = self.optional_filters.get(field_ref, None)
cached_value = (
self.optional_filters.get(field_ref, None)
if self.optional_filters is not None
else None
)
if cached_value is not None:
return self.check_field_permission(field, cached_value)
@@ -165,7 +169,7 @@ class FilterableSerializerMixin:
if InvenTree.ready.isGeneratingSchema():
return True
if value is not None:
if value is not None and self.optional_filters is not None:
# Cache the value for future reference
self.optional_filters[field_ref] = value
@@ -316,14 +320,16 @@ class FilterableSerializerMixin:
field_names = list(super().get_field_names(declared_fields, info))
# Add any optional fields which are included
for field_name in self.optional_fields:
if field_name not in field_names:
field_names.append(field_name)
if _fields := self.optional_fields:
for field_name in _fields:
if field_name not in field_names:
field_names.append(field_name)
# Remove any fields which are marked for removal
for field_name in self.fields_to_remove:
if field_name in field_names:
field_names.remove(field_name)
if _fields := self.fields_to_remove:
for field_name in _fields:
if field_name in field_names:
field_names.remove(field_name)
return field_names
@@ -358,17 +364,19 @@ class FilterableSerializerMixin:
def build_relational_field(self, field_name, relation_info):
"""Handle a special case where an OptionalField shadows a model relation."""
if field_name in self.optional_fields:
if field := self.build_optional_field(field_name):
return field
if _fields := self.optional_fields:
if field_name in _fields:
if field := self.build_optional_field(field_name):
return field
return super().build_relational_field(field_name, relation_info)
def build_property_field(self, field_name, model_class):
"""Handle a special case where an OptionalField shadows a model property."""
if field_name in self.optional_fields:
if field := self.build_optional_field(field_name):
return field
if _fields := self.optional_fields:
if field_name in _fields:
if field := self.build_optional_field(field_name):
return field
return super().build_property_field(field_name, model_class)
+5 -7
View File
@@ -2400,15 +2400,13 @@ class BuildItem(InvenTreeMetadataModel):
iii) The Part referenced by the StockItem is a valid substitute for the BomItem
"""
if self.build.part == self.bom_item.part:
if self.build.part == self.bom_item.part or (
self.bom_item.inherited
and self.build.part
in self.bom_item.part.get_descendants(include_self=False)
):
valid = self.bom_item.is_stock_item_valid(self.stock_item)
elif self.bom_item.inherited:
if self.build.part in self.bom_item.part.get_descendants(
include_self=False
):
valid = self.bom_item.is_stock_item_valid(self.stock_item)
# If the existing BomItem is *not* valid, try to find a match
if not valid and self.build and self.stock_item:
ancestors = self.stock_item.part.get_ancestors(
+10 -12
View File
@@ -1830,13 +1830,12 @@ class SalesOrder(AuditedOrderMixin, TotalPriceMixin, Order):
serials_not_exist.add(serial)
continue
if get_global_setting('SALESORDER_BLOCK_INCOMPLETE_ITEM_TESTS'):
if (
stock_item.hasRequiredTests()
and not stock_item.passedAllRequiredTests()
):
serials_unavailable.add(serial)
continue
if get_global_setting('SALESORDER_BLOCK_INCOMPLETE_ITEM_TESTS') and (
stock_item.hasRequiredTests()
and not stock_item.passedAllRequiredTests()
):
serials_unavailable.add(serial)
continue
if not stock_item.in_stock:
serials_unavailable.add(serial)
@@ -2628,11 +2627,10 @@ class SalesOrderLineItem(AuditedLineItemMixin, OrderLineItem):
"""
super().clean()
if self.part:
if not self.part.salable:
raise ValidationError({
'part': _('Only salable parts can be assigned to a sales order')
})
if self.part and not self.part.salable:
raise ValidationError({
'part': _('Only salable parts can be assigned to a sales order')
})
def __str__(self):
"""Render a string representation of a SalesOrderLineItem instance."""
+6 -8
View File
@@ -1813,14 +1813,12 @@ class SalesOrderShipmentAllocationItemSerializer(serializers.Serializer):
stock_item = data['stock_item']
quantity = data['quantity']
if get_global_setting('SALESORDER_BLOCK_INCOMPLETE_ITEM_TESTS'):
if (
stock_item.hasRequiredTests()
and not stock_item.passedAllRequiredTests()
):
raise ValidationError({
'stock_item': _('Stock item has not passed all required tests')
})
if get_global_setting('SALESORDER_BLOCK_INCOMPLETE_ITEM_TESTS') and (
stock_item.hasRequiredTests() and not stock_item.passedAllRequiredTests()
):
raise ValidationError({
'stock_item': _('Stock item has not passed all required tests')
})
if stock_item.serialized and quantity != 1:
raise ValidationError({
@@ -685,11 +685,8 @@ class InvenTreePlugin(VersionMixin, MixinBase, MetaBase):
full_path = str(Path(*self.get_static_path(), *file_path, file_name))
if check_exists:
if not storage.exists(full_path):
logger.error(
f"Static file not found for plugin '{self.SLUG}': {full_path}"
)
if check_exists and not storage.exists(full_path):
logger.error(f"Static file not found for plugin '{self.SLUG}': {full_path}")
# Resolve the URL to the static file
url = storage.url(full_path)
@@ -951,10 +951,9 @@ class PluginsRegistry:
package_name = getattr(plugin, 'package_name', None)
# Auto-enable default builtin plugins
if plg_db and plg_db.is_mandatory():
if not plg_db.active:
plg_db.active = True
plg_db.save()
if plg_db and plg_db.is_mandatory() and not plg_db.active:
plg_db.active = True
plg_db.save()
# Save the package_name attribute to the plugin
if plg_db and plg_db.package_name != package_name:
@@ -66,7 +66,11 @@ class BarcodeView(CreateAPIView):
from common.models import BarcodeScanResult
# Extract context data from the request
context = {**request.GET.dict(), **request.POST.dict(), **request.data}
context: dict[str, str] = {
**request.GET.dict(),
**request.POST.dict(),
**request.data,
}
barcode = context.pop('barcode', '')
@@ -83,12 +87,7 @@ class BarcodeView(CreateAPIView):
response = str(response)
# Ensure that the context data is stringified first, otherwise cannot be JSON encoded
if isinstance(context, dict):
context = {key: str(value) for key, value in context.items()}
elif context is None:
pass
else:
context = str(context)
context = {key: str(value) for key, value in context.items()}
# Ensure data is not too long
if len(barcode) > BarcodeScanResult.BARCODE_SCAN_MAX_LEN:
+22 -24
View File
@@ -19,32 +19,30 @@ def get_plugin_urls():
urls = []
if registry.is_ready:
if (
get_global_setting('ENABLE_PLUGINS_URL', False)
or settings.PLUGIN_TESTING_SETUP
):
for plugin in registry.with_mixin(PluginMixinEnum.URLS):
try:
if plugin_urls := plugin.urlpatterns:
# Check if the plugin has a custom URL pattern
for url in plugin_urls:
# Attempt to resolve against the URL pattern as a validation check
try:
url.resolve('')
except Resolver404:
pass
if registry.is_ready and (
settings.PLUGIN_TESTING_SETUP or get_global_setting('ENABLE_PLUGINS_URL', False)
):
for plugin in registry.with_mixin(PluginMixinEnum.URLS):
try:
if plugin_urls := plugin.urlpatterns:
# Check if the plugin has a custom URL pattern
for url in plugin_urls:
# Attempt to resolve against the URL pattern as a validation check
try:
url.resolve('')
except Resolver404:
pass
urls.append(
re_path(
f'^{plugin.slug}/',
include((plugin_urls, plugin.slug)),
name=plugin.slug,
)
urls.append(
re_path(
f'^{plugin.slug}/',
include((plugin_urls, plugin.slug)),
name=plugin.slug,
)
except Exception:
log_error('get_plugin_urls', plugin=plugin.slug)
continue
)
except Exception:
log_error('get_plugin_urls', plugin=plugin.slug)
continue
# Redirect anything else to the root index
urls.append(
@@ -563,9 +563,8 @@ def part_image(part: Part, preview: bool = False, thumbnail: bool = False, **kwa
image_filename = InvenTree.helpers.image2name(part.image, preview, thumbnail)
if kwargs.get('check_exists'):
if not media_file_exists(image_filename):
raise FileNotFoundError(_('Image file not found') + f": '{image_filename}'")
if kwargs.get('check_exists') and not media_file_exists(image_filename):
raise FileNotFoundError(_('Image file not found') + f": '{image_filename}'")
return uploaded_image(
InvenTree.helpers.image2name(part.image, preview, thumbnail), **kwargs
+5 -4
View File
@@ -589,11 +589,12 @@ class StockItem(
Arguments:
ignore_serial_check: If True, allow deletion of serialized stock items regardless of global setting
"""
if not ignore_serial_check and not get_global_setting(
'STOCK_ALLOW_DELETE_SERIALIZED', cache=False
if (
not ignore_serial_check
and not get_global_setting('STOCK_ALLOW_DELETE_SERIALIZED', cache=False)
and self.serialized
):
if self.serialized:
raise ValidationError(_('Serialized stock items cannot be deleted'))
raise ValidationError(_('Serialized stock items cannot be deleted'))
with transaction.atomic():
# Re-link any child items to the parent of this item,
+2 -3
View File
@@ -1971,9 +1971,8 @@ class StockAdjustmentItemSerializer(serializers.Serializer):
check_status=False, check_quantity=False, check_in_production=False
):
raise ValidationError(_('Stock item is not in stock'))
elif self.require_in_stock == False:
if stock_item.is_in_stock():
raise ValidationError(_('Stock item is already in stock'))
elif self.require_in_stock == False and stock_item.is_in_stock():
raise ValidationError(_('Stock item is already in stock'))
return stock_item