Compare commits

...

15 Commits

Author SHA1 Message Date
Oliver
ec67f10fc8 Fix build API URL (#6219)
- Backport of https://github.com/inventree/InvenTree/pull/6218
2024-01-13 00:01:02 +11:00
Oliver
a6693d3bf8 fixed depreceated is_ajax (#6210) (#6216)
* fixed depreceated is_ajax (#6210)

* File cleanup

---------

Co-authored-by: Matthias Mair <code@mjmair.com>
2024-01-12 22:23:23 +11:00
github-actions[bot]
421081b8f6 Specify ForeignKey widget for importing destination field (#6205) (#6206)
- Fixes https://github.com/inventree/InvenTree/issues/6201

(cherry picked from commit 7f231cb6c1)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2024-01-11 22:55:51 +11:00
github-actions[bot]
a41efb31b6 Fix for mobile app documentation URL (#6198) (#6199)
Closes https://github.com/inventree/InvenTree/issues/6140

(cherry picked from commit 9715af564f)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2024-01-11 09:11:35 +11:00
github-actions[bot]
78b559306b Ready fix (#6191) (#6194)
* Update "isRunningMigrations" method

* Update other apps.py files

(cherry picked from commit 445551e6f3)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2024-01-11 00:37:36 +11:00
github-actions[bot]
8708ec9bac Fix resource classes for order models (#6188) (#6190)
- PurchaseOrder
- ReturnOrder
- SalesOrder

Fixes https://github.com/inventree/InvenTree/issues/6155

(cherry picked from commit 73cc39bb68)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2024-01-10 23:53:27 +11:00
github-actions[bot]
864236b27a Handle case where ref_url is invalid (#6186) (#6189)
(cherry picked from commit 9f01962c4e)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2024-01-10 23:48:35 +11:00
Oliver
5a06e00159 Update version.py (#6187)
Bump version number to 0.13.1
2024-01-10 23:37:13 +11:00
github-actions[bot]
cb7b4cbc1a Improve data import for PartParameterTemplate (#6182) (#6185)
- Create Resource class which uses InvenTreeResource base
- Ensure 'units' field is converted to string if empty
- Handle null choices field in PartParameterTemplate model

(cherry picked from commit a23235400d)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2024-01-10 22:53:17 +11:00
github-actions[bot]
74e8f92be5 Re-implement no-frontend flag in "invoke update" (#6183) (#6184)
- Allows old installers to work once more
- Ref: https://github.com/inventree/InvenTree/issues/6177

(cherry picked from commit 53ac6c724d)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2024-01-10 22:53:00 +11:00
github-actions[bot]
264b560f37 Cancel purchase order - Error object (#6137) (#6138)
Fixes #6136

Error introduced in https://github.com/inventree/InvenTree/pull/6017

(cherry picked from commit 88f86efd4c)

Co-authored-by: Matthias Mair <code@mjmair.com>
2023-12-27 11:57:36 +01:00
github-actions[bot]
9f8ee5a095 Fix to clear SO Allocations on receipt of Return Order Line Item (#6117) (#6124)
* Added stock_item.clearAllocations() to order.models.py

* Update models.py ReturnOrder clear allocations on line receipt

(cherry picked from commit fc5645a9a5)

Co-authored-by: mcollins-DL <71047397+mcollins-DL@users.noreply.github.com>
2023-12-21 10:45:57 +04:00
github-actions[bot]
79fdf9243b Update django-allauth version (#6099) (#6114)
* Patch for django-allauth 0.55.0

- Some breaking changes here
- Add logger error if auth provider cannot be imported
- Fix for API endpoints

* Only provide URLs for configured plugins

* Update for django-allauth 0.56.0

- Remove support for keycloak
- Remove example from configuration template

* Update django-allauth in requirements.txt

* Update requirements.in

* Refactor SSO functions into common file

* Update config template file

* Update docs

* Fix template files

* Log SSO exceptions to the database

- WIll help greatly with debugging installs

* Add note about error handling in docs

(cherry picked from commit a63529a9cf)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2023-12-18 17:39:26 +11:00
github-actions[bot]
35266b80f4 Remove --no-frontend option from installer (#6111) (#6112)
- This swtich is no longer present in `invoke update`
- Frontend installation is off by default
- Fixes https://github.com/inventree/InvenTree/discussions/6109

(cherry picked from commit 148bf0764b)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2023-12-18 10:46:42 +11:00
github-actions[bot]
05d3458f67 Small tweak for log output (#6102) (#6103)
(cherry picked from commit 95d29f18e9)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
2023-12-16 11:46:41 +11:00
35 changed files with 306 additions and 155 deletions

View File

@@ -19,6 +19,9 @@ class InvenTreeResource(ModelResource):
MAX_IMPORT_ROWS = 1000
MAX_IMPORT_COLS = 100
# List of fields which should be converted to empty strings if they are null
CONVERT_NULL_FIELDS = []
def import_data_inner(
self,
dataset,
@@ -79,6 +82,13 @@ class InvenTreeResource(ModelResource):
return [f for f in fields if f.column_name not in fields_to_exclude]
def before_import_row(self, row, row_number=None, **kwargs):
"""Run custom code before importing each row"""
for field in self.CONVERT_NULL_FIELDS:
if field in row and row[field] is None:
row[field] = ''
class CustomRateAdmin(RateAdmin):
"""Admin interface for the Rate class"""

View File

@@ -12,10 +12,9 @@ from django.db import transaction
from django.db.utils import IntegrityError, OperationalError
import InvenTree.conversion
import InvenTree.ready
import InvenTree.tasks
from InvenTree.config import get_setting
from InvenTree.ready import (canAppAccessDatabase, isInMainThread,
isInTestMode, isPluginRegistryLoaded)
logger = logging.getLogger("inventree")
@@ -37,17 +36,21 @@ class InvenTreeConfig(AppConfig):
- Adding users set in the current environment
"""
# skip loading if plugin registry is not loaded or we run in a background thread
if not isPluginRegistryLoaded() or not isInMainThread():
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
return
if canAppAccessDatabase() or settings.TESTING_ENV:
# Skip if running migrations
if InvenTree.ready.isRunningMigrations():
return
if InvenTree.ready.canAppAccessDatabase() or settings.TESTING_ENV:
self.remove_obsolete_tasks()
self.collect_tasks()
self.start_background_tasks()
if not isInTestMode(): # pragma: no cover
if not InvenTree.ready.isInTestMode(): # pragma: no cover
self.update_exchange_rates()
# Let the background worker check for migrations
InvenTree.tasks.offload_task(InvenTree.tasks.check_for_migrations)
@@ -58,7 +61,7 @@ class InvenTreeConfig(AppConfig):
# Ensure the unit registry is loaded
InvenTree.conversion.get_unit_registry()
if canAppAccessDatabase() or settings.TESTING_ENV:
if InvenTree.ready.canAppAccessDatabase() or settings.TESTING_ENV:
self.add_user_on_startup()
def remove_obsolete_tasks(self):

View File

@@ -62,7 +62,7 @@ def reload_unit_registry():
pass
dt = time.time() - t_start
logger.debug('Loaded unit registry in %s.3f s', dt)
logger.debug('Loaded unit registry in %.3f s', dt)
return reg

View File

@@ -13,7 +13,7 @@ from django.utils.translation import gettext_lazy as _
from allauth.account.adapter import DefaultAccountAdapter
from allauth.account.forms import LoginForm, SignupForm, set_form_field_order
from allauth.exceptions import ImmediateHttpResponse
from allauth.core.exceptions import ImmediateHttpResponse
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth_2fa.adapter import OTPAdapter
from allauth_2fa.utils import user_has_valid_totp_device
@@ -24,6 +24,7 @@ from crispy_forms.layout import Field, Layout
from dj_rest_auth.registration.serializers import RegisterSerializer
from rest_framework import serializers
import InvenTree.sso
from common.models import InvenTreeSetting
from InvenTree.exceptions import log_error
@@ -228,7 +229,7 @@ class CustomSignupForm(SignupForm):
def registration_enabled():
"""Determine whether user registration is enabled."""
if InvenTreeSetting.get_setting('LOGIN_ENABLE_REG') or InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO_REG'):
if InvenTreeSetting.get_setting('LOGIN_ENABLE_REG') or InvenTree.sso.registration_enabled():
if settings.EMAIL_HOST:
return True
else:
@@ -358,6 +359,13 @@ class CustomSocialAccountAdapter(CustomUrlMixin, RegistratonMixin, DefaultSocial
# Otherwise defer to the original allauth adapter.
return super().login(request, user)
def authentication_error(self, request, provider_id, error=None, exception=None, extra_context=None):
"""Callback method for authentication errors."""
# Log the error to the database
log_error(request.path if request else 'sso')
logger.error("SSO error for provider '%s' - check admin error log", provider_id)
# override dj-rest-auth
class CustomRegisterSerializer(RegisterSerializer):

View File

@@ -840,3 +840,8 @@ def inheritors(cls):
subcls.add(child)
work.append(child)
return subcls
def is_ajax(request):
"""Check if the current request is an AJAX request."""
return request.headers.get('x-requested-with') == 'XMLHttpRequest'

View File

@@ -16,7 +16,11 @@ def isImportingData():
def isRunningMigrations():
"""Return True if the database is currently running migrations."""
return 'migrate' in sys.argv or 'makemigrations' in sys.argv
return any((x in sys.argv for x in [
'migrate',
'makemigrations',
'showmigrations'
]))
def isInMainThread():

View File

@@ -288,6 +288,7 @@ MIDDLEWARE = CONFIG.get('middleware', [
'InvenTree.middleware.InvenTreeRemoteUserMiddleware', # Remote / proxy auth
'django_otp.middleware.OTPMiddleware', # MFA support
'InvenTree.middleware.CustomAllauthTwoFactorMiddleware', # Flow control for allauth
'allauth.account.middleware.AccountMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'InvenTree.middleware.AuthRequiredMiddleware',
@@ -956,6 +957,13 @@ SITE_ID = 1
SOCIAL_BACKENDS = get_setting('INVENTREE_SOCIAL_BACKENDS', 'social_backends', [], typecast=list)
for app in SOCIAL_BACKENDS:
# Ensure that the app starts with 'allauth.socialaccount.providers'
social_prefix = 'allauth.socialaccount.providers.'
if not app.startswith(social_prefix): # pragma: no cover
app = social_prefix + app
INSTALLED_APPS.append(app) # pragma: no cover
SOCIALACCOUNT_PROVIDERS = get_setting('INVENTREE_SOCIAL_PROVIDERS', 'social_providers', None, typecast=dict)

View File

@@ -2,13 +2,10 @@
import logging
from importlib import import_module
from django.urls import include, path, reverse
from django.urls import NoReverseMatch, include, path, reverse
from allauth.account.models import EmailAddress
from allauth.socialaccount import providers
from allauth.socialaccount.models import SocialApp
from allauth.socialaccount.providers.keycloak.views import \
KeycloakOAuth2Adapter
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView)
from drf_spectacular.utils import OpenApiResponse, extend_schema
@@ -16,6 +13,7 @@ from rest_framework.exceptions import NotFound
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
import InvenTree.sso
from common.models import InvenTreeSetting
from InvenTree.mixins import CreateAPI, ListAPI, ListCreateAPI
from InvenTree.serializers import InvenTreeModelSerializer
@@ -51,14 +49,6 @@ def handle_oauth2(adapter: OAuth2Adapter):
]
def handle_keycloak():
"""Define urls for keycloak."""
return [
path('login/', GenericOAuth2ApiLoginView.adapter_view(KeycloakOAuth2Adapter), name='keycloak_api_login'),
path('connect/', GenericOAuth2ApiConnectView.adapter_view(KeycloakOAuth2Adapter), name='keycloak_api_connet'),
]
legacy = {
'twitter': 'twitter_oauth2',
'bitbucket': 'bitbucket_oauth2',
@@ -72,10 +62,13 @@ legacy = {
social_auth_urlpatterns = []
provider_urlpatterns = []
for provider in providers.registry.get_list():
for name, provider in providers.registry.provider_map.items():
try:
prov_mod = import_module(provider.get_package() + ".views")
except ImportError:
logger.exception("Could not import authentication provider %s", name)
continue
# Try to extract the adapter class
@@ -89,8 +82,6 @@ for provider in providers.registry.get_list():
if provider.id in legacy:
logger.warning('`%s` is not supported on platform UI. Use `%s` instead.', provider.id, legacy[provider.id])
continue
elif provider.id == 'keycloak':
urls = handle_keycloak()
else:
logger.error('Found handler that is not yet ready for platform UI: `%s`. Open an feature request on GitHub if you need it implemented.', provider.id)
continue
@@ -107,26 +98,31 @@ class SocialProviderListView(ListAPI):
def get(self, request, *args, **kwargs):
"""Get the list of providers."""
provider_list = []
for provider in providers.registry.get_list():
for provider in providers.registry.provider_map.values():
provider_data = {
'id': provider.id,
'name': provider.name,
'login': request.build_absolute_uri(reverse(f'{provider.id}_api_login')),
'connect': request.build_absolute_uri(reverse(f'{provider.id}_api_connect')),
'configured': False
}
try:
provider_app = provider.get_app(request)
provider_data['display_name'] = provider_app.name
provider_data['configured'] = True
except SocialApp.DoesNotExist:
provider_data['display_name'] = provider.name
provider_data['login'] = request.build_absolute_uri(reverse(f'{provider.id}_api_login'))
except NoReverseMatch:
provider_data['login'] = None
try:
provider_data['connect'] = request.build_absolute_uri(reverse(f'{provider.id}_api_connect'))
except NoReverseMatch:
provider_data['connect'] = None
provider_data['configured'] = InvenTree.sso.check_provider(provider)
provider_data['display_name'] = InvenTree.sso.provider_display_name(provider)
provider_list.append(provider_data)
data = {
'sso_enabled': InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO'),
'sso_registration': InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO_REG'),
'sso_enabled': InvenTree.sso.login_enabled(),
'sso_registration': InvenTree.sso.registration_enabled(),
'mfa_required': InvenTreeSetting.get_setting('LOGIN_ENFORCE_MFA'),
'providers': provider_list
}

View File

@@ -0,0 +1,81 @@
"""Helper functions for Single Sign On functionality"""
import logging
from common.models import InvenTreeSetting
from InvenTree.helpers import str2bool
logger = logging.getLogger('inventree')
def get_provider_app(provider):
"""Return the SocialApp object for the given provider"""
from allauth.socialaccount.models import SocialApp
try:
apps = SocialApp.objects.filter(provider__iexact=provider.id)
except SocialApp.DoesNotExist:
logger.warning("SSO SocialApp not found for provider '%s'", provider.id)
return None
if apps.count() > 1:
logger.warning("Multiple SocialApps found for provider '%s'", provider.id)
if apps.count() == 0:
logger.warning("SSO SocialApp not found for provider '%s'", provider.id)
return apps.first()
def check_provider(provider, raise_error=False):
"""Check if the given provider is correctly configured.
To be correctly configured, the following must be true:
- Provider must either have a registered SocialApp
- Must have at least one site enabled
"""
import allauth.app_settings
# First, check that the provider is enabled
app = get_provider_app(provider)
if not app:
return False
if allauth.app_settings.SITES_ENABLED:
# At least one matching site must be specified
if not app.sites.exists():
logger.error("SocialApp %s has no sites configured", app)
return False
# At this point, we assume that the provider is correctly configured
return True
def provider_display_name(provider):
"""Return the 'display name' for the given provider"""
if app := get_provider_app(provider):
return app.name
# Fallback value if app not found
return provider.name
def login_enabled() -> bool:
"""Return True if SSO login is enabled"""
return str2bool(InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO'))
def registration_enabled() -> bool:
"""Return True if SSO registration is enabled"""
return str2bool(InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO_REG'))
def auto_registration_enabled() -> bool:
"""Return True if SSO auto-registration is enabled"""
return str2bool(InvenTreeSetting.get_setting('LOGIN_SIGNUP_SSO_AUTO'))

View File

@@ -19,7 +19,7 @@ from dulwich.repo import NotGitRepository, Repo
from .api_version import INVENTREE_API_TEXT, INVENTREE_API_VERSION
# InvenTree software version
INVENTREE_SW_VERSION = "0.13.0"
INVENTREE_SW_VERSION = "0.13.1"
# Discover git
try:
@@ -105,7 +105,7 @@ def inventreeDocUrl():
def inventreeAppUrl():
"""Return URL for InvenTree app site."""
return f'{inventreeDocUrl()}/app/app',
return f'{inventreeDocUrl()}/app/app/'
def inventreeCreditsUrl():

View File

@@ -33,7 +33,7 @@ from part.models import PartCategory
from users.models import RuleSet, check_user_role
from .forms import EditUserForm, SetPasswordForm
from .helpers import remove_non_printable_characters, strip_html_tags
from .helpers import is_ajax, remove_non_printable_characters, strip_html_tags
def auth_request(request):
@@ -258,7 +258,7 @@ class AjaxMixin(InvenTreeRoleMixin):
if not data:
data = {}
if not request.is_ajax():
if not is_ajax(request):
return HttpResponseRedirect('/')
if context is None:

View File

@@ -4,7 +4,7 @@ import logging
from django.apps import AppConfig
from InvenTree.ready import isImportingData
import InvenTree.ready
logger = logging.getLogger('inventree')
@@ -19,6 +19,10 @@ class CommonConfig(AppConfig):
def ready(self):
"""Initialize restart flag clearance on startup."""
if InvenTree.ready.isRunningMigrations():
return
self.clear_restart_flag()
def clear_restart_flag(self):
@@ -29,7 +33,7 @@ class CommonConfig(AppConfig):
if common.models.InvenTreeSetting.get_setting('SERVER_RESTART_REQUIRED', backup_value=False, create=False, cache=False):
logger.info("Clearing SERVER_RESTART_REQUIRED flag")
if not isImportingData():
if not InvenTree.ready.isImportingData():
common.models.InvenTreeSetting.set_setting('SERVER_RESTART_REQUIRED', False, None)
except Exception:
pass

View File

@@ -233,13 +233,13 @@ remote_login_header: HTTP_REMOTE_USER
# social_backends:
# - 'allauth.socialaccount.providers.google'
# - 'allauth.socialaccount.providers.github'
# - 'allauth.socialaccount.providers.keycloak'
# Add specific settings for social account providers (if required)
# Refer to the djngo-allauth documentation for more details:
# https://docs.allauth.org/en/latest/socialaccount/provider_configuration.html
# social_providers:
# keycloak:
# KEYCLOAK_URL: 'https://keycloak.custom/auth'
# KEYCLOAK_REALM: 'master'
# github:
# VERIFIED_EMAIL: true
# Add LDAP support
# ldap:

View File

@@ -12,8 +12,7 @@ from django.conf import settings
from django.core.exceptions import AppRegistryNotReady
from django.db.utils import IntegrityError, OperationalError, ProgrammingError
from InvenTree.ready import (canAppAccessDatabase, isImportingData,
isInMainThread, isPluginRegistryLoaded)
import InvenTree.ready
logger = logging.getLogger("inventree")
@@ -37,10 +36,13 @@ class LabelConfig(AppConfig):
def ready(self):
"""This function is called whenever the label app is loaded."""
# skip loading if plugin registry is not loaded or we run in a background thread
if not isPluginRegistryLoaded() or not isInMainThread():
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
return
if canAppAccessDatabase(allow_test=False) and not isImportingData():
if InvenTree.ready.isRunningMigrations():
return
if InvenTree.ready.canAppAccessDatabase(allow_test=False) and not InvenTree.ready.isImportingData():
try:
self.create_labels() # pragma: no cover
except (AppRegistryNotReady, IntegrityError, OperationalError, ProgrammingError):

View File

@@ -7,6 +7,7 @@ from import_export import widgets
from import_export.admin import ImportExportModelAdmin
from import_export.fields import Field
import stock.models
from InvenTree.admin import InvenTreeResource
from order import models
@@ -79,9 +80,30 @@ class PurchaseOrderLineItemInlineAdmin(admin.StackedInline):
extra = 0
class PurchaseOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, InvenTreeResource):
"""Class for managing import / export of PurchaseOrder data."""
class Meta:
"""Metaclass"""
model = models.PurchaseOrder
skip_unchanged = True
clean_model_instances = True
exclude = [
'metadata',
]
# Add number of line items
line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True)
# Is this order overdue?
overdue = Field(attribute='is_overdue', widget=widgets.BooleanWidget(), readonly=True)
class PurchaseOrderAdmin(ImportExportModelAdmin):
"""Admin class for the PurchaseOrder model"""
resource_class = PurchaseOrderResource
exclude = [
'reference_int',
]
@@ -107,9 +129,30 @@ class PurchaseOrderAdmin(ImportExportModelAdmin):
autocomplete_fields = ('supplier',)
class SalesOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, InvenTreeResource):
"""Class for managing import / export of SalesOrder data."""
class Meta:
"""Metaclass options"""
model = models.SalesOrder
skip_unchanged = True
clean_model_instances = True
exclude = [
'metadata',
]
# Add number of line items
line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True)
# Is this order overdue?
overdue = Field(attribute='is_overdue', widget=widgets.BooleanWidget(), readonly=True)
class SalesOrderAdmin(ImportExportModelAdmin):
"""Admin class for the SalesOrder model"""
resource_class = SalesOrderResource
exclude = [
'reference_int',
]
@@ -131,25 +174,6 @@ class SalesOrderAdmin(ImportExportModelAdmin):
autocomplete_fields = ('customer',)
class PurchaseOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, InvenTreeResource):
"""Class for managing import / export of PurchaseOrder data."""
class Meta:
"""Metaclass"""
model = models.PurchaseOrder
skip_unchanged = True
clean_model_instances = True
exclude = [
'metadata',
]
# Add number of line items
line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True)
# Is this order overdue?
overdue = Field(attribute='is_overdue', widget=widgets.BooleanWidget(), readonly=True)
class PurchaseOrderLineItemResource(PriceResourceMixin, InvenTreeResource):
"""Class for managing import / export of PurchaseOrderLineItem data."""
@@ -168,6 +192,11 @@ class PurchaseOrderLineItemResource(PriceResourceMixin, InvenTreeResource):
SKU = Field(attribute='part__SKU', readonly=True)
destination = Field(
attribute='destination',
widget=widgets.ForeignKeyWidget(stock.models.StockLocation),
)
def dehydrate_purchase_price(self, line):
"""Return a string value of the 'purchase_price' field, rather than the 'Money' object"""
if line.purchase_price:
@@ -184,25 +213,6 @@ class PurchaseOrderExtraLineResource(PriceResourceMixin, InvenTreeResource):
model = models.PurchaseOrderExtraLine
class SalesOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, InvenTreeResource):
"""Class for managing import / export of SalesOrder data."""
class Meta:
"""Metaclass options"""
model = models.SalesOrder
skip_unchanged = True
clean_model_instances = True
exclude = [
'metadata',
]
# Add number of line items
line_items = Field(attribute='line_count', widget=widgets.IntegerWidget(), readonly=True)
# Is this order overdue?
overdue = Field(attribute='is_overdue', widget=widgets.BooleanWidget(), readonly=True)
class SalesOrderLineItemResource(PriceResourceMixin, InvenTreeResource):
"""Class for managing import / export of SalesOrderLineItem data."""
@@ -334,6 +344,8 @@ class ReturnOrderResource(ProjectCodeResourceMixin, TotalPriceResourceMixin, Inv
class ReturnOrderAdmin(ImportExportModelAdmin):
"""Admin class for the ReturnOrder model"""
resource_class = ReturnOrderResource
exclude = [
'reference_int',
]

View File

@@ -1926,6 +1926,7 @@ class ReturnOrder(TotalPriceMixin, Order):
stock_item.customer = None
stock_item.sales_order = None
stock_item.save(add_note=False)
stock_item.clearAllocations()
# Add a tracking entry to the StockItem
stock_item.add_tracking_entry(

View File

@@ -247,7 +247,7 @@ class PurchaseOrderCancelSerializer(serializers.Serializer):
self.order = self.context['order']
return {
'can_cancel': self.order.can_cancel(),
'can_cancel': self.order.can_cancel,
}
def save(self):
@@ -1219,7 +1219,7 @@ class SalesOrderCancelSerializer(serializers.Serializer):
order = self.context['order']
return {
'can_cancel': order.can_cancel(),
'can_cancel': order.can_cancel,
}
def save(self):

View File

@@ -356,9 +356,32 @@ class BomItemAdmin(ImportExportModelAdmin):
autocomplete_fields = ('part', 'sub_part',)
class ParameterTemplateResource(InvenTreeResource):
"""Class for managing ParameterTemplate import/export"""
# The following fields will be converted from None to ''
CONVERT_NULL_FIELDS = [
'choices',
'units'
]
class Meta:
"""Metaclass definition"""
model = models.PartParameterTemplate
skip_unchanged = True
report_skipped = False
clean_model_instances = True
exclude = [
'metadata',
]
class ParameterTemplateAdmin(ImportExportModelAdmin):
"""Admin class for the PartParameterTemplate model"""
resource_class = ParameterTemplateResource
list_display = ('name', 'units')
search_fields = ('name', 'units')

View File

@@ -22,8 +22,8 @@ from InvenTree.api import (APIDownloadMixin, AttachmentMixin,
from InvenTree.filters import (ORDER_FILTER, SEARCH_ORDER_FILTER,
SEARCH_ORDER_FILTER_ALIAS, InvenTreeDateFilter,
InvenTreeSearchFilter)
from InvenTree.helpers import (DownloadFile, increment_serial_number, isNull,
str2bool, str2int)
from InvenTree.helpers import (DownloadFile, increment_serial_number, is_ajax,
isNull, str2bool, str2int)
from InvenTree.mixins import (CreateAPI, CustomRetrieveUpdateDestroyAPI,
ListAPI, ListCreateAPI, RetrieveAPI,
RetrieveUpdateAPI, RetrieveUpdateDestroyAPI,
@@ -1069,7 +1069,7 @@ class PartList(PartMixin, APIDownloadMixin, ListCreateAPI):
"""
if page is not None:
return self.get_paginated_response(data)
elif request.is_ajax():
elif is_ajax(request):
return JsonResponse(data, safe=False)
return Response(data)
@@ -1740,7 +1740,7 @@ class BomList(BomMixin, ListCreateDestroyAPIView):
"""
if page is not None:
return self.get_paginated_response(data)
elif request.is_ajax():
elif is_ajax(request):
return JsonResponse(data, safe=False)
return Response(data)

View File

@@ -5,8 +5,7 @@ import logging
from django.apps import AppConfig
from django.db.utils import OperationalError, ProgrammingError
from InvenTree.ready import (canAppAccessDatabase, isImportingData,
isInMainThread, isPluginRegistryLoaded)
import InvenTree.ready
logger = logging.getLogger("inventree")
@@ -18,10 +17,13 @@ class PartConfig(AppConfig):
def ready(self):
"""This function is called whenever the Part app is loaded."""
# skip loading if plugin registry is not loaded or we run in a background thread
if not isPluginRegistryLoaded() or not isInMainThread():
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
return
if canAppAccessDatabase():
if InvenTree.ready.isRunningMigrations():
return
if InvenTree.ready.canAppAccessDatabase():
self.update_trackable_status()
self.reset_part_pricing_flags()
@@ -51,7 +53,7 @@ class PartConfig(AppConfig):
"""
from .models import PartPricing
if isImportingData():
if InvenTree.ready.isImportingData():
return
try:

View File

@@ -3346,7 +3346,10 @@ class PartParameterTemplate(MetadataMixin, models.Model):
})
# Check that 'choices' are in fact valid
self.choices = self.choices.strip()
if self.choices is None:
self.choices = ''
else:
self.choices = str(self.choices).strip()
if self.choices:
choice_set = set()

View File

@@ -539,8 +539,11 @@ def authorized_owners(group):
@register.simple_tag()
def object_link(url_name, pk, ref):
"""Return highlighted link to object."""
ref_url = reverse(url_name, kwargs={'pk': pk})
return mark_safe(f'<b><a href="{ref_url}">{ref}</a></b>')
try:
ref_url = reverse(url_name, kwargs={'pk': pk})
return mark_safe(f'<b><a href="{ref_url}">{ref}</a></b>')
except NoReverseMatch:
return None
@register.simple_tag()

View File

@@ -1,58 +1,32 @@
"""This module provides template tags pertaining to SSO functionality"""
import logging
from django import template
from common.models import InvenTreeSetting
from InvenTree.helpers import str2bool
import InvenTree.sso
register = template.Library()
logger = logging.getLogger('inventree')
@register.simple_tag()
def sso_login_enabled():
"""Return True if single-sign-on is enabled"""
return str2bool(InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO'))
return InvenTree.sso.login_enabled()
@register.simple_tag()
def sso_reg_enabled():
"""Return True if single-sign-on is enabled for self-registration"""
return str2bool(InvenTreeSetting.get_setting('LOGIN_ENABLE_SSO_REG'))
return InvenTree.sso.registration_enabled()
@register.simple_tag()
def sso_auto_enabled():
"""Return True if single-sign-on is enabled for auto-registration"""
return str2bool(InvenTreeSetting.get_setting('LOGIN_SIGNUP_SSO_AUTO'))
return InvenTree.sso.auto_registration_enabled()
@register.simple_tag()
def sso_check_provider(provider):
"""Return True if the given provider is correctly configured"""
import allauth.app_settings
from allauth.socialaccount.models import SocialApp
# First, check that the provider is enabled
apps = SocialApp.objects.filter(provider__iexact=provider.id)
if not apps.exists():
logging.error(
"SSO SocialApp %s does not exist (known providers: %s)",
provider.id, [obj.provider for obj in SocialApp.objects.all()]
)
return False
# Next, check that the provider is correctly configured
app = apps.first()
if allauth.app_settings.SITES_ENABLED:
# At least one matching site must be specified
if not app.sites.exists():
logger.error("SocialApp %s has no sites configured", app)
return False
# At this point, we assume that the provider is correctly configured
return True
return InvenTree.sso.check_provider(provider)

View File

@@ -528,7 +528,7 @@ report_api_urls = [
path(r'<int:pk>/', include([
re_path(r'print/?', BuildReportPrint.as_view(), name='api-build-report-print'),
re_path(r'metadata/', MetadataView.as_view(), {'model': BuildReport}, name='api-build-report-metadata'),
re_path(r'^.$', BuildReportDetail.as_view(), name='api-build-report-detail'),
re_path(r'^.*$', BuildReportDetail.as_view(), name='api-build-report-detail'),
])),
# List view

View File

@@ -20,11 +20,13 @@ class ReportConfig(AppConfig):
def ready(self):
"""This function is called whenever the report app is loaded."""
from InvenTree.ready import (canAppAccessDatabase, isImportingData,
isInMainThread, isPluginRegistryLoaded)
import InvenTree.ready
# skip loading if plugin registry is not loaded or we run in a background thread
if not isPluginRegistryLoaded() or not isInMainThread():
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
return
if InvenTree.ready.isRunningMigrations():
return
# Configure logging for PDF generation (disable "info" messages)
@@ -32,7 +34,7 @@ class ReportConfig(AppConfig):
logging.getLogger('weasyprint').setLevel(logging.WARNING)
# Create entries for default report templates
if canAppAccessDatabase(allow_test=False) and not isImportingData():
if InvenTree.ready.canAppAccessDatabase(allow_test=False) and not InvenTree.ready.isImportingData():
try:
self.create_default_test_reports()

View File

@@ -27,8 +27,8 @@ from InvenTree.api import (APIDownloadMixin, AttachmentMixin,
ListCreateDestroyAPIView, MetadataView)
from InvenTree.filters import (ORDER_FILTER, SEARCH_ORDER_FILTER,
SEARCH_ORDER_FILTER_ALIAS, InvenTreeDateFilter)
from InvenTree.helpers import (DownloadFile, extract_serial_numbers, isNull,
str2bool, str2int)
from InvenTree.helpers import (DownloadFile, extract_serial_numbers, is_ajax,
isNull, str2bool, str2int)
from InvenTree.mixins import (CreateAPI, CustomRetrieveUpdateDestroyAPI,
ListAPI, ListCreateAPI, RetrieveAPI,
RetrieveUpdateDestroyAPI)
@@ -963,7 +963,7 @@ class StockList(APIDownloadMixin, ListCreateDestroyAPIView):
if page is not None:
return self.get_paginated_response(data)
elif request.is_ajax():
elif is_ajax(request):
return JsonResponse(data, safe=False)
return Response(data)
@@ -1346,7 +1346,7 @@ class StockTrackingList(ListAPI):
if page is not None:
return self.get_paginated_response(data)
if request.is_ajax():
if is_ajax(request):
return JsonResponse(data, safe=False)
return Response(data)

View File

@@ -1,4 +1,4 @@
{% extends "socialaccount/base.html" %}
{% extends "account/base.html" %}
{% load i18n %}

View File

@@ -1,4 +1,4 @@
{% extends "socialaccount/base.html" %}
{% extends "account/base.html" %}
{% load i18n %}
{% load sso %}

View File

@@ -1,4 +1,4 @@
{% extends "socialaccount/base.html" %}
{% extends "account/base.html" %}
{% load i18n crispy_forms_tags inventree_extras %}

View File

@@ -5,8 +5,7 @@ import logging
from django.apps import AppConfig
from django.db.utils import OperationalError, ProgrammingError
from InvenTree.ready import (canAppAccessDatabase, isInMainThread,
isPluginRegistryLoaded)
import InvenTree.ready
logger = logging.getLogger('inventree')
@@ -19,10 +18,14 @@ class UsersConfig(AppConfig):
def ready(self):
"""Called when the 'users' app is loaded at runtime"""
# skip loading if plugin registry is not loaded or we run in a background thread
if not isPluginRegistryLoaded() or not isInMainThread():
if not InvenTree.ready.isPluginRegistryLoaded() or not InvenTree.ready.isInMainThread():
return
if canAppAccessDatabase(allow_test=True):
# Skip if running migrations
if InvenTree.ready.isRunningMigrations():
return
if InvenTree.ready.canAppAccessDatabase(allow_test=True):
try:
self.assign_permissions()

View File

@@ -236,7 +236,7 @@ function update_or_install() {
# Run update as app user
echo "# Updating InvenTree"
sudo -u ${APP_USER} --preserve-env=$SETUP_ENVS bash -c "cd ${APP_HOME} && pip install wheel"
sudo -u ${APP_USER} --preserve-env=$SETUP_ENVS bash -c "cd ${APP_HOME} && invoke update --no-frontend | sed -e 's/^/# inv update| /;'"
sudo -u ${APP_USER} --preserve-env=$SETUP_ENVS bash -c "cd ${APP_HOME} && invoke update | sed -e 's/^/# inv update| /;'"
# Make sure permissions are correct again
echo "# Set permissions for data dir and media: ${DATA_DIR}"

View File

@@ -9,6 +9,9 @@ InvenTree provides the possibility to use 3rd party services to authenticate use
!!! tip "Provider Documentation"
There are a lot of technical considerations when configuring a particular SSO provider. A good starting point is the [django-allauth documentation](https://django-allauth.readthedocs.io/en/latest/socialaccount/providers/index.html)
!!! warning "Advanced Users"
The SSO functionality provided by django-allauth is powerful, but can prove challenging to configure. Please ensure that you understand the implications of enabling SSO for your InvenTree instance. Specific technical details of each available SSO provider are beyond the scope of this documentation - please refer to the [django-allauth documentation](https://django-allauth.readthedocs.io/en/latest/socialaccount/providers/index.html) for more information.
## SSO Configuration
The basic requirements for configuring SSO are outlined below:
@@ -131,3 +134,7 @@ Make sure all users with admin privileges have sufficient passwords - they can r
!!! warning "It's a secret!"
Never share the secret key associated with your InvenTree install!
## Error Handling
If you encounter an error during the SSO process, the error should be logged in the InvenTree database. You can view the [error log](./logs.md) in the [admin interface](./admin.md) to see the details of the error.

View File

@@ -2,7 +2,7 @@
Django>=3.2.14,<4 # Django package
coreapi # API documentation for djangorestframework
cryptography>=40.0.0,!=40.0.2 # Core cryptographic functionality
django-allauth<0.55.0 # SSO for external providers via OpenID # FIXED 2023-09-06 due to https://github.com/iMerica/dj-rest-auth/issues/534
django-allauth # SSO for external providers via OpenID
django-allauth-2fa # MFA / 2FA
django-cleanup # Automated deletion of old / unused uploaded files
django-cors-headers # CORS headers extension for DRF

View File

@@ -45,7 +45,7 @@ defusedxml==0.7.1
# python3-openid
diff-match-patch==20230430
# via django-import-export
dj-rest-auth==5.0.1
dj-rest-auth==5.0.2
# via -r requirements.in
django==3.2.23
# via
@@ -81,7 +81,7 @@ django==3.2.23
# djangorestframework
# djangorestframework-simplejwt
# drf-spectacular
django-allauth==0.54.0
django-allauth==0.59.0
# via
# -r requirements.in
# django-allauth-2fa

View File

@@ -347,9 +347,10 @@ def migrate(c):
help={
'skip_backup': 'Skip database backup step (advanced users)',
'frontend': 'Force frontend compilation/download step (ignores INVENTREE_DOCKER)',
'no_frontend': 'Skip frontend compilation/download step'
}
)
def update(c, skip_backup=False, frontend: bool = False):
def update(c, skip_backup=False, frontend: bool = False, no_frontend: bool = False):
"""Update InvenTree installation.
This command should be invoked after source code has been updated,
@@ -378,8 +379,7 @@ def update(c, skip_backup=False, frontend: bool = False):
# If:
# - INVENTREE_DOCKER is set (by the docker image eg.) and not overridden by `--frontend` flag
# - `--no-frontend` flag is set
# if (os.environ.get('INVENTREE_DOCKER', False) and not frontend) or no_frontend:
if not frontend:
if (os.environ.get('INVENTREE_DOCKER', False) and not frontend) or no_frontend:
return
# Decide if we should compile the frontend or try to download it