From 629a411612e7ea29aa9a11c785b63b3a595b3da7 Mon Sep 17 00:00:00 2001 From: Matthias Mair Date: Mon, 23 Nov 2026 13:40:30 +0100 Subject: [PATCH] small fixes (#13342) * merge duplicate branches * fix type * remove impossible branches * fix types * make more tolerant * update queries * fix sec check --- .../management/commands/wait_for_db.py | 14 +++--- src/backend/InvenTree/InvenTree/metadata.py | 10 ++-- .../InvenTree/InvenTree/serializers.py | 48 +++++++++++-------- src/backend/InvenTree/build/models.py | 12 ++--- src/backend/InvenTree/order/models.py | 22 ++++----- src/backend/InvenTree/order/serializers.py | 14 +++--- .../InvenTree/plugin/_internal/base.py | 7 +-- .../InvenTree/plugin/_internal/registry.py | 7 ++- .../InvenTree/plugin/base/barcodes/api.py | 13 +++-- src/backend/InvenTree/plugin/urls.py | 46 +++++++++--------- .../InvenTree/report/templatetags/report.py | 5 +- src/backend/InvenTree/stock/models.py | 9 ++-- src/backend/InvenTree/stock/serializers.py | 5 +- tasks.py | 2 +- 14 files changed, 103 insertions(+), 111 deletions(-) diff --git a/src/backend/InvenTree/InvenTree/management/commands/wait_for_db.py b/src/backend/InvenTree/InvenTree/management/commands/wait_for_db.py index 84fcb2ebff..dbc03648cc 100644 --- a/src/backend/InvenTree/InvenTree/management/commands/wait_for_db.py +++ b/src/backend/InvenTree/InvenTree/management/commands/wait_for_db.py @@ -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) diff --git a/src/backend/InvenTree/InvenTree/metadata.py b/src/backend/InvenTree/InvenTree/metadata.py index fb52106da1..ee65f11392 100644 --- a/src/backend/InvenTree/InvenTree/metadata.py +++ b/src/backend/InvenTree/InvenTree/metadata.py @@ -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 diff --git a/src/backend/InvenTree/InvenTree/serializers.py b/src/backend/InvenTree/InvenTree/serializers.py index 1483f95b55..e4041a1b05 100644 --- a/src/backend/InvenTree/InvenTree/serializers.py +++ b/src/backend/InvenTree/InvenTree/serializers.py @@ -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) diff --git a/src/backend/InvenTree/build/models.py b/src/backend/InvenTree/build/models.py index 79363784e3..77749b1b43 100644 --- a/src/backend/InvenTree/build/models.py +++ b/src/backend/InvenTree/build/models.py @@ -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( diff --git a/src/backend/InvenTree/order/models.py b/src/backend/InvenTree/order/models.py index f81d59853a..ec34e60701 100644 --- a/src/backend/InvenTree/order/models.py +++ b/src/backend/InvenTree/order/models.py @@ -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.""" diff --git a/src/backend/InvenTree/order/serializers.py b/src/backend/InvenTree/order/serializers.py index 125ebaf532..fab0543eb8 100644 --- a/src/backend/InvenTree/order/serializers.py +++ b/src/backend/InvenTree/order/serializers.py @@ -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({ diff --git a/src/backend/InvenTree/plugin/_internal/base.py b/src/backend/InvenTree/plugin/_internal/base.py index 6d8ebd1d7f..c7ef7224e4 100644 --- a/src/backend/InvenTree/plugin/_internal/base.py +++ b/src/backend/InvenTree/plugin/_internal/base.py @@ -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) diff --git a/src/backend/InvenTree/plugin/_internal/registry.py b/src/backend/InvenTree/plugin/_internal/registry.py index 5d56f9b71d..c019a72d9e 100644 --- a/src/backend/InvenTree/plugin/_internal/registry.py +++ b/src/backend/InvenTree/plugin/_internal/registry.py @@ -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: diff --git a/src/backend/InvenTree/plugin/base/barcodes/api.py b/src/backend/InvenTree/plugin/base/barcodes/api.py index 3a0129d303..044b855563 100644 --- a/src/backend/InvenTree/plugin/base/barcodes/api.py +++ b/src/backend/InvenTree/plugin/base/barcodes/api.py @@ -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: diff --git a/src/backend/InvenTree/plugin/urls.py b/src/backend/InvenTree/plugin/urls.py index 7fac893f9b..11a50f06a8 100644 --- a/src/backend/InvenTree/plugin/urls.py +++ b/src/backend/InvenTree/plugin/urls.py @@ -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( diff --git a/src/backend/InvenTree/report/templatetags/report.py b/src/backend/InvenTree/report/templatetags/report.py index a3f615ba48..5df04e1cec 100644 --- a/src/backend/InvenTree/report/templatetags/report.py +++ b/src/backend/InvenTree/report/templatetags/report.py @@ -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 diff --git a/src/backend/InvenTree/stock/models.py b/src/backend/InvenTree/stock/models.py index dfc66916ad..dd4b9704ed 100644 --- a/src/backend/InvenTree/stock/models.py +++ b/src/backend/InvenTree/stock/models.py @@ -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, diff --git a/src/backend/InvenTree/stock/serializers.py b/src/backend/InvenTree/stock/serializers.py index 1fd387ca23..40d3a7128a 100644 --- a/src/backend/InvenTree/stock/serializers.py +++ b/src/backend/InvenTree/stock/serializers.py @@ -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 diff --git a/tasks.py b/tasks.py index b81e5e8ff8..575f4515f3 100644 --- a/tasks.py +++ b/tasks.py @@ -35,7 +35,7 @@ def safe_value(fnc): try: return fnc() except (ModuleNotFoundError, ImportError): - return wrap_color('N/A', 93) # Yellow color for "Not Available" + return wrap_color('N/A', '93') # Yellow color for "Not Available" def is_true(x):