mirror of
https://github.com/inventree/InvenTree.git
synced 2026-11-18 06:04:44 +00:00
refactor: use generic model insights for frontend features (#13072)
* feat:generic model insights inspired by https://github.com/inventree/InvenTree/pull/13069 this adds a more general approach to generic features like attachments, notes some tests and functions written with assistance of AI * lazy load panels * add pr version * fix snapshot issue * move history panel to new generic mechanism * Update api_version.py * move to generic * remove duplicate * clean up import * fix test * add ignore for broken contract in test
This commit is contained in:
1 parent
016f965ac8
commit
a87489ca44
32 files changed
+533
-477
No files matched your search
@@ -232,6 +232,7 @@ ignore_imports = [
|
||||
"generic.states.test_transition -> order.status_codes",
|
||||
"generic.states.api_helpers -> users.permissions",
|
||||
"generic.states.test_transition -> users.models",
|
||||
"generic.modelfeatures.tests -> part.models",
|
||||
]
|
||||
|
||||
[[tool.importlinter.contracts]]
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
"""InvenTree API version information."""
|
||||
|
||||
# InvenTree API version
|
||||
INVENTREE_API_VERSION = 579
|
||||
INVENTREE_API_VERSION = 580
|
||||
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
|
||||
|
||||
INVENTREE_API_TEXT = """
|
||||
|
||||
v580 -> 2026-11-14 : https://github.com/inventree/InvenTree/pull/13072
|
||||
- Adds feature info to contenttype endpoint
|
||||
|
||||
v579 -> 2026-11-14 : https://github.com/inventree/InvenTree/pull/13271
|
||||
- The "consumed" field on the BuildLine API is now read-only - stock must be consumed via the build order endpoints
|
||||
- The "received_date" field on the ReturnOrderLineItem API is now read-only - line items must be received via the return order "receive" endpoint
|
||||
|
||||
@@ -17,6 +17,7 @@ from allauth.socialaccount.signals import social_account_updated
|
||||
import InvenTree.conversion
|
||||
import InvenTree.ready
|
||||
import InvenTree.tasks
|
||||
from generic.modelfeatures import build_model_features_cache
|
||||
from InvenTree.config import get_setting
|
||||
from InvenTree.ready import ignore_ready_warning
|
||||
|
||||
@@ -102,6 +103,7 @@ class InvenTreeConfig(AppConfig):
|
||||
|
||||
self.update_site_url()
|
||||
self.load_unit_registry()
|
||||
build_model_features_cache()
|
||||
|
||||
if InvenTree.ready.canAppAccessDatabase() or settings.TESTING_ENV:
|
||||
self.add_user_on_startup()
|
||||
|
||||
@@ -35,6 +35,7 @@ import InvenTree.helpers
|
||||
import InvenTree.helpers_model
|
||||
import InvenTree.sentry
|
||||
import report.mixins
|
||||
from generic.modelfeatures import ModelFeatureMixin
|
||||
|
||||
logger = structlog.get_logger('inventree')
|
||||
|
||||
@@ -532,7 +533,7 @@ class InvenTreePermissionCheckMixin:
|
||||
return user.has_perm(perm)
|
||||
|
||||
|
||||
class InvenTreeAuditMixin:
|
||||
class InvenTreeAuditMixin(ModelFeatureMixin):
|
||||
"""Opt a model in to the audit log (field-level change history).
|
||||
|
||||
Any concrete model which inherits from this mixin is registered with django-auditlog
|
||||
@@ -551,6 +552,8 @@ class InvenTreeAuditMixin:
|
||||
(e.g. StockHistoryCode) - see audit.helpers.audit_event
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.history'
|
||||
|
||||
AUDIT_INCLUDE_FIELDS: tuple[str, ...] = ()
|
||||
AUDIT_EXCLUDE_FIELDS: tuple[str, ...] = ()
|
||||
AUDIT_MASK_FIELDS: tuple[str, ...] = ()
|
||||
@@ -622,13 +625,17 @@ class InvenTreeAuditMixin:
|
||||
return False
|
||||
|
||||
|
||||
class InvenTreeParameterMixin(InvenTreePermissionCheckMixin, models.Model):
|
||||
class InvenTreeParameterMixin(
|
||||
ModelFeatureMixin, InvenTreePermissionCheckMixin, models.Model
|
||||
):
|
||||
"""Provides an abstracted class for managing parameters.
|
||||
|
||||
Links the implementing model to the common.models.Parameter table,
|
||||
and provides the following methods:
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.parameters'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for InvenTreeParameterMixin."""
|
||||
|
||||
@@ -774,13 +781,17 @@ class InvenTreeParameterMixin(InvenTreePermissionCheckMixin, models.Model):
|
||||
return True
|
||||
|
||||
|
||||
class InvenTreeNoteMixin(InvenTreePermissionCheckMixin, models.Model):
|
||||
class InvenTreeNoteMixin(
|
||||
ModelFeatureMixin, InvenTreePermissionCheckMixin, models.Model
|
||||
):
|
||||
"""Provides an abstracted class for managing notes.
|
||||
|
||||
Links the implementing model to the common.models.Note table,
|
||||
and provides multiple accessor / helper methods.
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.notes'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for InvenTreeNoteMixin."""
|
||||
|
||||
@@ -927,7 +938,7 @@ class InvenTreeNoteMixin(InvenTreePermissionCheckMixin, models.Model):
|
||||
return True
|
||||
|
||||
|
||||
class InvenTreeAttachmentMixin(InvenTreePermissionCheckMixin):
|
||||
class InvenTreeAttachmentMixin(ModelFeatureMixin, InvenTreePermissionCheckMixin):
|
||||
"""Provides an abstracted class for managing file attachments.
|
||||
|
||||
Links the implementing model to the common.models.Attachment table,
|
||||
@@ -936,6 +947,8 @@ class InvenTreeAttachmentMixin(InvenTreePermissionCheckMixin):
|
||||
- attachments: Return a queryset containing all attachments for this model
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.attachments'
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
"""Handle the deletion of a model instance.
|
||||
|
||||
@@ -1571,7 +1584,7 @@ class PathStringMixin(models.Model):
|
||||
]
|
||||
|
||||
|
||||
class InvenTreeTagsMixin(models.Model):
|
||||
class InvenTreeTagsMixin(ModelFeatureMixin, models.Model):
|
||||
"""A mixin class for adding tag functionality to a model class.
|
||||
|
||||
The following fields are added to any model which implements this mixin:
|
||||
@@ -1579,6 +1592,8 @@ class InvenTreeTagsMixin(models.Model):
|
||||
- tags : A text field for storing comma-separated tags
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.tags'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for this mixin.
|
||||
|
||||
@@ -1590,7 +1605,7 @@ class InvenTreeTagsMixin(models.Model):
|
||||
tags = TaggableManager(blank=True)
|
||||
|
||||
|
||||
class InvenTreeBarcodeMixin(models.Model):
|
||||
class InvenTreeBarcodeMixin(ModelFeatureMixin, models.Model):
|
||||
"""A mixin class for adding barcode functionality to a model class.
|
||||
|
||||
Two types of barcodes are supported:
|
||||
@@ -1606,6 +1621,8 @@ class InvenTreeBarcodeMixin(models.Model):
|
||||
The barcode_model_type_code() classmethod must be implemented in the model class.
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.barcode'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for this mixin.
|
||||
|
||||
@@ -1862,7 +1879,7 @@ def after_error_logged(sender, instance: Error, created: bool, **kwargs):
|
||||
)
|
||||
|
||||
|
||||
class InvenTreeImageMixin(models.Model):
|
||||
class InvenTreeImageMixin(ModelFeatureMixin, models.Model):
|
||||
"""A mixin class for adding image functionality to a model class.
|
||||
|
||||
The following fields are added to any model which implements this mixin:
|
||||
@@ -1870,6 +1887,8 @@ class InvenTreeImageMixin(models.Model):
|
||||
- image : An image field for storing an image
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.image'
|
||||
|
||||
IMAGE_RENAME: Callable | None = None
|
||||
|
||||
class Meta:
|
||||
|
||||
@@ -21,6 +21,7 @@ import common.filters
|
||||
import common.models as common_models
|
||||
import common.validators
|
||||
import generic.states.custom
|
||||
from generic.modelfeatures import get_model_features
|
||||
from importer.registry import register_importer
|
||||
from InvenTree.apps import DEFAULT_OIDC_APP_ID
|
||||
from InvenTree.helpers import get_objectreference
|
||||
@@ -554,7 +555,7 @@ class FlagSerializer(serializers.Serializer):
|
||||
return data
|
||||
|
||||
|
||||
class ContentTypeSerializer(serializers.Serializer):
|
||||
class ContentTypeSerializer(FilterableSerializerMixin, serializers.ModelSerializer):
|
||||
"""Serializer for ContentType models."""
|
||||
|
||||
pk = serializers.IntegerField(read_only=True)
|
||||
@@ -563,16 +564,34 @@ class ContentTypeSerializer(serializers.Serializer):
|
||||
app_labeled_name = serializers.CharField(read_only=True)
|
||||
is_plugin = serializers.SerializerMethodField('get_is_plugin', read_only=True)
|
||||
|
||||
features = OptionalField(
|
||||
serializer_class=serializers.SerializerMethodField,
|
||||
serializer_kwargs={'read_only': True},
|
||||
default_include=False,
|
||||
filter_name='features',
|
||||
)
|
||||
|
||||
class Meta:
|
||||
"""Meta options for ContentTypeSerializer."""
|
||||
|
||||
model = ContentType
|
||||
fields = ['pk', 'app_label', 'model', 'app_labeled_name', 'is_plugin']
|
||||
fields = [
|
||||
'pk',
|
||||
'app_label',
|
||||
'model',
|
||||
'app_labeled_name',
|
||||
'is_plugin',
|
||||
'features',
|
||||
]
|
||||
|
||||
def get_is_plugin(self, obj) -> bool:
|
||||
"""Return True if the model is a plugin model."""
|
||||
return obj.app_label in plugin_registry.installed_apps
|
||||
|
||||
def get_features(self, obj) -> list[str]:
|
||||
"""Return the list of generic features supported by this model type."""
|
||||
return get_model_features(obj.model_class())
|
||||
|
||||
|
||||
@register_importer()
|
||||
class CustomUnitSerializer(DataImportExportSerializerMixin, InvenTreeModelSerializer):
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Generic model features package."""
|
||||
|
||||
from .func import (
|
||||
ModelFeatureMixin,
|
||||
build_model_features_cache,
|
||||
clear_model_features_cache,
|
||||
get_model_features,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'ModelFeatureMixin',
|
||||
'build_model_features_cache',
|
||||
'clear_model_features_cache',
|
||||
'get_model_features',
|
||||
]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Generic model features, declared by model mixin classes."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from django.apps import apps
|
||||
|
||||
import structlog
|
||||
|
||||
logger = structlog.get_logger('inventree')
|
||||
|
||||
|
||||
class ModelFeatureMixin:
|
||||
"""Base class for mixins which provide a generic 'feature' to a model.
|
||||
|
||||
Identified with the MODEL_FEATURE attribute. Builtin start with 'org.inventree.i.modelfeatures.', do not use that space in a plugin.
|
||||
|
||||
Example:
|
||||
class MyPluginMixin(ModelFeatureMixin, models.Model):
|
||||
MODEL_FEATURE = 'com.example.myplugin.my_feature'
|
||||
"""
|
||||
|
||||
MODEL_FEATURE: Optional[str] = None
|
||||
|
||||
|
||||
_model_features_cache: Optional[dict[str, list[str]]] = None
|
||||
|
||||
|
||||
def collect_model_features(model_class):
|
||||
"""Collect the generic features declared in the class hierarchy of a model."""
|
||||
features = []
|
||||
|
||||
for base in model_class.__mro__:
|
||||
feature = base.__dict__.get('MODEL_FEATURE')
|
||||
if feature and feature not in features:
|
||||
features.append(feature)
|
||||
|
||||
return features
|
||||
|
||||
|
||||
def build_model_features_cache():
|
||||
"""Build cache of features for all registered models."""
|
||||
global _model_features_cache
|
||||
|
||||
_model_features_cache = {
|
||||
model._meta.label_lower: collect_model_features(model)
|
||||
for model in apps.get_models()
|
||||
if issubclass(model, ModelFeatureMixin)
|
||||
}
|
||||
logger.debug('Built model feature cache for %s models', len(_model_features_cache))
|
||||
return _model_features_cache
|
||||
|
||||
|
||||
def clear_model_features_cache():
|
||||
"""Clear feature cache."""
|
||||
global _model_features_cache
|
||||
_model_features_cache = None
|
||||
|
||||
|
||||
def get_model_features(model_class) -> list[str]:
|
||||
"""Return the features supported by model class."""
|
||||
if model_class is None or not issubclass(model_class, ModelFeatureMixin):
|
||||
return []
|
||||
|
||||
cache = _model_features_cache
|
||||
if cache is None:
|
||||
cache = build_model_features_cache()
|
||||
|
||||
meta = getattr(model_class, '_meta', None)
|
||||
features = cache.get(meta.label_lower) if meta else None
|
||||
|
||||
if features is None:
|
||||
# Not a registered model - e.g. an abstract class
|
||||
return collect_model_features(model_class)
|
||||
return features
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Tests for the model features functionality."""
|
||||
|
||||
from django.urls import reverse
|
||||
|
||||
from taggit.models import Tag
|
||||
|
||||
import InvenTree.models
|
||||
from InvenTree.unit_test import InvenTreeAPITestCase
|
||||
from part.models import Part
|
||||
|
||||
from . import func
|
||||
from .func import ModelFeatureMixin, clear_model_features_cache, get_model_features
|
||||
|
||||
|
||||
class ContentTypeFeatureAPITests(InvenTreeAPITestCase):
|
||||
"""Tests for the 'features' field on the ContentType API."""
|
||||
|
||||
def test_features(self):
|
||||
"""Test that the list endpoint reports features per model type."""
|
||||
url = reverse('api-contenttype-list')
|
||||
|
||||
# The 'features' field is not included by default
|
||||
data = self.get(url, expected_code=200).data
|
||||
self.assertNotIn('features', data[0])
|
||||
|
||||
data = self.get(url, {'features': True}, expected_code=200).data
|
||||
features = {item['model']: item['features'] for item in data}
|
||||
for f in ['attachments', 'notes', 'parameters', 'barcode']:
|
||||
self.assertIn(f'org.inventree.i.modelfeatures.{f}', features['part'])
|
||||
|
||||
self.assertIn(
|
||||
'org.inventree.i.modelfeatures.attachments', features['salesorder']
|
||||
)
|
||||
self.assertIn('org.inventree.i.modelfeatures.notes', features['stockitem'])
|
||||
self.assertEqual(features['contenttype'], [])
|
||||
|
||||
def test_model_features(self):
|
||||
"""Test that features are declared by the model mixins, and cached per application."""
|
||||
clear_model_features_cache()
|
||||
|
||||
features = get_model_features(Part)
|
||||
|
||||
self.assertIn('org.inventree.i.modelfeatures.attachments', features)
|
||||
self.assertIn('org.inventree.i.modelfeatures.report', features)
|
||||
|
||||
# The cache is built for all models on first access, and reused afterwards
|
||||
self.assertIsNotNone(func._model_features_cache)
|
||||
self.assertIs(features, get_model_features(Part))
|
||||
|
||||
# Clearing the cache (e.g. after a plugin reload) rebuilds it
|
||||
clear_model_features_cache()
|
||||
self.assertIsNone(func._model_features_cache)
|
||||
self.assertEqual(features, get_model_features(Part))
|
||||
self.assertIsNotNone(func._model_features_cache)
|
||||
|
||||
self.assertEqual(get_model_features(None), [])
|
||||
self.assertEqual(get_model_features(Tag), [])
|
||||
|
||||
# A custom mixin (e.g. provided by a plugin) can declare a new feature
|
||||
class CustomFeatureMixin(ModelFeatureMixin):
|
||||
MODEL_FEATURE = 'custom'
|
||||
|
||||
class CustomModel(CustomFeatureMixin, InvenTree.models.InvenTreeNoteMixin):
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
self.assertEqual(
|
||||
get_model_features(CustomModel),
|
||||
['custom', 'org.inventree.i.modelfeatures.notes'],
|
||||
)
|
||||
self.assertNotIn('custom', get_model_features(Part))
|
||||
@@ -30,6 +30,7 @@ import structlog
|
||||
import InvenTree.cache
|
||||
import InvenTree.ready
|
||||
from common.settings import get_global_setting, set_global_setting
|
||||
from generic.modelfeatures import clear_model_features_cache
|
||||
from InvenTree.config import get_plugin_dir
|
||||
from InvenTree.exceptions import log_error
|
||||
|
||||
@@ -1170,6 +1171,8 @@ class PluginsRegistry:
|
||||
else:
|
||||
self._try_reload(apps.set_installed_apps, loadable_apps)
|
||||
|
||||
clear_model_features_cache()
|
||||
|
||||
def _clean_installed_apps(self):
|
||||
for plugin in self.installed_apps:
|
||||
if plugin in settings.INSTALLED_APPS:
|
||||
|
||||
@@ -5,6 +5,8 @@ from typing import Generic, Optional, TypedDict, TypeVar
|
||||
|
||||
from django.db import models
|
||||
|
||||
from generic.modelfeatures import ModelFeatureMixin
|
||||
|
||||
_Model = TypeVar('_Model', bound=models.Model, covariant=True)
|
||||
|
||||
REPORT_ATTRIBUTE_MARKER = '_report_attribute_description'
|
||||
@@ -54,13 +56,15 @@ class BaseReportContext(TypedDict):
|
||||
"""Base context for a report model."""
|
||||
|
||||
|
||||
class InvenTreeReportMixin(models.Model):
|
||||
class InvenTreeReportMixin(ModelFeatureMixin, models.Model):
|
||||
"""A mixin class for adding report generation functionality to a model class.
|
||||
|
||||
In addition to exposing the model to the report generation interface,
|
||||
this mixin provides a hook for providing extra context information to the reports.
|
||||
"""
|
||||
|
||||
MODEL_FEATURE = 'org.inventree.i.modelfeatures.report'
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options for this mixin."""
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* Enumeration of builtin model features (as reported by the server)
|
||||
*/
|
||||
export enum ModelFeature {
|
||||
attachments = 'org.inventree.i.modelfeatures.attachments',
|
||||
notes = 'org.inventree.i.modelfeatures.notes',
|
||||
parameters = 'org.inventree.i.modelfeatures.parameters',
|
||||
barcode = 'org.inventree.i.modelfeatures.barcode',
|
||||
tags = 'org.inventree.i.modelfeatures.tags',
|
||||
image = 'org.inventree.i.modelfeatures.image',
|
||||
report = 'org.inventree.i.modelfeatures.report',
|
||||
history = 'org.inventree.i.modelfeatures.history'
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { SettingsStateProps } from './Settings';
|
||||
|
||||
// The type of indicator dot to be shown against a panel
|
||||
export type PanelIndicatorType = 'info' | 'warning' | 'danger' | null;
|
||||
@@ -20,6 +21,28 @@ export type PanelType = {
|
||||
hotkey?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Properties passed to a factory function which builds a panel for a generic model feature
|
||||
*
|
||||
* @param model - The model type (e.g. 'part', or a plugin defined model)
|
||||
* @param id - The primary key of the model instance
|
||||
* @param instanceInfo - Aggregated counts for the instance (e.g. attachment_count)
|
||||
*/
|
||||
export type ModelFeaturePanelProps = {
|
||||
model: string;
|
||||
id: number;
|
||||
instanceInfo: Record<string, number | undefined>;
|
||||
userSettings: SettingsStateProps;
|
||||
globalSettings: SettingsStateProps;
|
||||
};
|
||||
|
||||
/**
|
||||
* Factory function which builds a panel for a generic model feature (e.g. 'attachments')
|
||||
*/
|
||||
export type ModelFeaturePanelFactory = (
|
||||
props: Readonly<ModelFeaturePanelProps>
|
||||
) => PanelType | Promise<PanelType>;
|
||||
|
||||
/**
|
||||
* Type used to specify a group of panels
|
||||
*/
|
||||
|
||||
@@ -1,39 +1,13 @@
|
||||
import { t } from '@lingui/core/macro';
|
||||
import { Skeleton } from '@mantine/core';
|
||||
import { IconHistory } from '@tabler/icons-react';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import type { ModelType } from '@lib/enums/ModelType';
|
||||
import type { PanelType } from '@lib/types/Panel';
|
||||
import {
|
||||
useGlobalSettingsState,
|
||||
useUserSettingsState
|
||||
} from '../../states/SettingsStates';
|
||||
import { AuditLogTable } from '../../tables/general/AuditLogTable';
|
||||
|
||||
/**
|
||||
* Determine whether the history panel should be displayed on detail pages:
|
||||
* - The audit log must be enabled
|
||||
* - Must be enabled via the 'DISPLAY_HISTORY_TAB' user setting
|
||||
*
|
||||
* Note: The displayed entries are filtered by the permissions of the user
|
||||
*/
|
||||
export function useShowHistoryPanel(): boolean {
|
||||
const userSettings = useUserSettingsState();
|
||||
const globalSettings = useGlobalSettingsState();
|
||||
|
||||
return useMemo(
|
||||
() =>
|
||||
globalSettings.isSet('AUDIT_LOG_ENABLED') &&
|
||||
userSettings.isSet('DISPLAY_HISTORY_TAB', false),
|
||||
[userSettings, globalSettings]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Panel displaying the audit log (change history) for a model instance.
|
||||
* Only add this panel to detail pages for models which are audited,
|
||||
* and pass the result of useShowHistoryPanel() as 'visible'.
|
||||
*/
|
||||
export default function HistoryPanel({
|
||||
model_type,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { ModelFeature } from '@lib/enums/ModelFeature';
|
||||
import type { ModelType } from '@lib/enums/ModelType';
|
||||
import type { ModelFeaturePanelFactory } from '@lib/types/Panel';
|
||||
|
||||
/**
|
||||
* Lookup of panels for generic model features (as reported by the server).
|
||||
*
|
||||
* The order of entries defines the order in which the panels are displayed.
|
||||
*/
|
||||
export const ModelFeaturePanelLookup: Record<string, ModelFeaturePanelFactory> =
|
||||
{
|
||||
[ModelFeature.parameters]: async ({ model, id, instanceInfo }) => {
|
||||
const { default: ParametersPanel } = await import('./ParametersPanel');
|
||||
return ParametersPanel({
|
||||
model_type: model as ModelType,
|
||||
model_id: id,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
});
|
||||
},
|
||||
[ModelFeature.attachments]: async ({ model, id, instanceInfo }) => {
|
||||
const { default: AttachmentPanel } = await import('./AttachmentPanel');
|
||||
return AttachmentPanel({
|
||||
model_type: model as ModelType,
|
||||
model_id: id,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
});
|
||||
},
|
||||
[ModelFeature.notes]: async ({ model, id, instanceInfo }) => {
|
||||
const { default: NotesPanel } = await import('./NotesPanel');
|
||||
return NotesPanel({
|
||||
model_type: model as ModelType,
|
||||
model_id: id,
|
||||
note_count: instanceInfo.note_count
|
||||
});
|
||||
},
|
||||
[ModelFeature.history]: async ({
|
||||
model,
|
||||
id,
|
||||
userSettings,
|
||||
globalSettings
|
||||
}) => {
|
||||
const { default: HistoryPanel } = await import('./HistoryPanel');
|
||||
const visible =
|
||||
globalSettings.isSet('AUDIT_LOG_ENABLED') &&
|
||||
userSettings.isSet('DISPLAY_HISTORY_TAB', false);
|
||||
return HistoryPanel({
|
||||
model_type: model as ModelType,
|
||||
model_id: id,
|
||||
visible
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -57,6 +57,7 @@ import { useDocumentVisibility, useWindowEvent } from '@mantine/hooks';
|
||||
import { modals } from '@mantine/modals';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { useModelPanels } from '../../hooks/UseModelPanels';
|
||||
import { usePluginPanels } from '../../hooks/UsePluginPanels';
|
||||
import { useLocalState } from '../../states/LocalState';
|
||||
import { vars } from '../../theme';
|
||||
@@ -559,10 +560,22 @@ function IndexPanelComponent({
|
||||
* @param collapsible - If true, the panel group can be collapsed (defaults to true)
|
||||
*/
|
||||
export function PanelGroup(props: Readonly<PanelProps>) {
|
||||
const panels = useModelPanels({
|
||||
model: props.model,
|
||||
id: props.id,
|
||||
panels: props.panels
|
||||
});
|
||||
|
||||
return (
|
||||
<Routes>
|
||||
<Route index element={<IndexPanelComponent {...props} />} />
|
||||
<Route path='/:panel/*' element={<BasePanelGroup {...props} />} />
|
||||
<Route
|
||||
index
|
||||
element={<IndexPanelComponent {...props} panels={panels} />}
|
||||
/>
|
||||
<Route
|
||||
path='/:panel/*'
|
||||
element={<BasePanelGroup {...props} panels={panels} />}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
@@ -40,6 +40,8 @@ export function useInstanceInfo({
|
||||
// dots themselves - a stale value for a few minutes is an acceptable
|
||||
// trade-off against refetching on every page navigation/remount.
|
||||
staleTime: 5 * 60 * 1000,
|
||||
placeholderData: (previousData, previousQuery) =>
|
||||
previousQuery?.queryKey[1] === modelType ? previousData : undefined,
|
||||
queryFn: async () => {
|
||||
return api
|
||||
.get(apiUrl(ApiEndpoints.instance_info), {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { ModelType } from '@lib/enums/ModelType';
|
||||
import type { PanelType } from '@lib/types/Panel';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { ModelFeaturePanelLookup } from '../components/panels/ModelFeaturePanels';
|
||||
import { useModelFeatures } from '../states/ModelFeatureState';
|
||||
import {
|
||||
useGlobalSettingsState,
|
||||
useUserSettingsState
|
||||
} from '../states/SettingsStates';
|
||||
import { useInstanceInfo } from './UseInstanceInfo';
|
||||
|
||||
/**
|
||||
* Append panels for generic model features (e.g. parameters, attachments, notes)
|
||||
* to a set of panels, based on the features which the target model supports on the server.
|
||||
*
|
||||
* Works for any model type known to the server, including plugin defined models.
|
||||
* Panels which are already defined (by name) in the provided list are not replaced.
|
||||
*/
|
||||
export function useModelPanels({
|
||||
model,
|
||||
id,
|
||||
panels
|
||||
}: {
|
||||
model?: ModelType | string;
|
||||
id?: number | null;
|
||||
panels: PanelType[];
|
||||
}): PanelType[] {
|
||||
const features = useModelFeatures(model);
|
||||
const featureFactories = useMemo(
|
||||
() =>
|
||||
Object.entries(ModelFeaturePanelLookup)
|
||||
.filter(([feature]) => features.includes(feature))
|
||||
.map(([, factory]) => factory),
|
||||
[features]
|
||||
);
|
||||
const [loadedPanels, setLoadedPanels] = useState<{
|
||||
model: string;
|
||||
id: number;
|
||||
panels: PanelType[];
|
||||
}>();
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: featureFactories.length > 0 ? (model as ModelType) : undefined,
|
||||
modelId: id ?? undefined
|
||||
});
|
||||
const userSettings = useUserSettingsState();
|
||||
const globalSettings = useGlobalSettingsState();
|
||||
|
||||
// lazy load feature panels
|
||||
useEffect(() => {
|
||||
if (!model || !id || featureFactories.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
Promise.all(
|
||||
featureFactories.map((factory) =>
|
||||
factory({
|
||||
model,
|
||||
id,
|
||||
instanceInfo: { ...instanceInfo },
|
||||
userSettings,
|
||||
globalSettings
|
||||
})
|
||||
)
|
||||
)
|
||||
.then((panels) => {
|
||||
if (!cancelled) {
|
||||
setLoadedPanels({ model, id, panels });
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.error('ERR: Error loading model feature panels', error);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [model, id, featureFactories, instanceInfo, userSettings, globalSettings]);
|
||||
|
||||
return useMemo(() => {
|
||||
if (
|
||||
!model ||
|
||||
!id ||
|
||||
loadedPanels?.model !== model ||
|
||||
loadedPanels.id !== id
|
||||
) {
|
||||
return panels;
|
||||
}
|
||||
|
||||
const existing = new Set(panels.map((panel) => panel.name));
|
||||
const featurePanels = loadedPanels.panels.filter(
|
||||
(panel) => !existing.has(panel.name)
|
||||
);
|
||||
|
||||
return [...panels, ...featurePanels];
|
||||
}, [model, id, panels, loadedPanels]);
|
||||
}
|
||||
@@ -37,13 +37,7 @@ import {
|
||||
} from '../../components/items/ActionDropdown';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import { StatusRenderer } from '../../components/render/StatusRenderer';
|
||||
import { RenderStockLocation } from '../../components/render/Stock';
|
||||
import { useBuildOrderFields } from '../../forms/BuildForms';
|
||||
@@ -52,7 +46,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import useStatusCodes from '../../hooks/UseStatusCodes';
|
||||
import { useGlobalSettingsState } from '../../states/SettingsStates';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
@@ -235,13 +228,6 @@ export default function BuildDetail() {
|
||||
refetchOnMount: true
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.build,
|
||||
modelId: build?.pk
|
||||
});
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const buildPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -365,41 +351,18 @@ export default function BuildDetail() {
|
||||
) : (
|
||||
<Skeleton />
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.build,
|
||||
model_id: build.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.build,
|
||||
model_id: build.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.build,
|
||||
model_id: build.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.build,
|
||||
model_id: build.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [
|
||||
build,
|
||||
id,
|
||||
user,
|
||||
instanceInfo,
|
||||
|
||||
buildStatus,
|
||||
globalSettings,
|
||||
showChildBuilds,
|
||||
buildLineQuery.isFetching,
|
||||
buildLineQuery.isLoading,
|
||||
buildLineData,
|
||||
showHistory
|
||||
buildLineData
|
||||
]);
|
||||
|
||||
const editBuildOrderFields = useBuildOrderFields({
|
||||
|
||||
@@ -30,13 +30,7 @@ import {
|
||||
import type { Breadcrumb } from '../../components/nav/BreadcrumbList';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import { companyFields } from '../../forms/CompanyForms';
|
||||
import {
|
||||
useCreateApiFormModal,
|
||||
@@ -44,7 +38,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
import { AddressTable } from '../../tables/company/AddressTable';
|
||||
import { ContactTable } from '../../tables/company/ContactTable';
|
||||
@@ -84,11 +77,6 @@ export default function CompanyDetail(props: Readonly<CompanyDetailProps>) {
|
||||
refetchOnMount: true
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.company,
|
||||
modelId: company?.pk
|
||||
});
|
||||
|
||||
const detailsPanel = instanceQuery.isFetching ? (
|
||||
<Skeleton />
|
||||
) : (
|
||||
@@ -99,8 +87,6 @@ export default function CompanyDetail(props: Readonly<CompanyDetailProps>) {
|
||||
/>
|
||||
);
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const companyPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -201,29 +187,9 @@ export default function CompanyDetail(props: Readonly<CompanyDetailProps>) {
|
||||
label: t`Addresses`,
|
||||
icon: <IconMap2 />,
|
||||
content: company?.pk && <AddressTable companyId={company.pk} />
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.company,
|
||||
model_id: company?.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.company,
|
||||
model_id: company.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.company,
|
||||
model_id: company.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.company,
|
||||
model_id: company.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [id, company, user, instanceInfo, showHistory]);
|
||||
}, [id, company, user]);
|
||||
|
||||
const editCompany = useEditApiFormModal({
|
||||
url: ApiEndpoints.company_list,
|
||||
|
||||
@@ -22,13 +22,7 @@ import {
|
||||
} from '../../components/items/ActionDropdown';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import { useManufacturerPartFields } from '../../forms/CompanyForms';
|
||||
import {
|
||||
useCreateApiFormModal,
|
||||
@@ -36,7 +30,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
import { SupplierPartTable } from '../../tables/purchasing/SupplierPartTable';
|
||||
import { StockItemTable } from '../../tables/stock/StockItemTable';
|
||||
@@ -62,13 +55,6 @@ export default function ManufacturerPartDetail() {
|
||||
}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.manufacturerpart,
|
||||
modelId: manufacturerPart?.pk
|
||||
});
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const panels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -110,29 +96,9 @@ export default function ManufacturerPartDetail() {
|
||||
) : (
|
||||
<Skeleton />
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.manufacturerpart,
|
||||
model_id: manufacturerPart?.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.manufacturerpart,
|
||||
model_id: manufacturerPart?.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.manufacturerpart,
|
||||
model_id: manufacturerPart?.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.manufacturerpart,
|
||||
model_id: manufacturerPart?.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [user, manufacturerPart, instanceInfo, showHistory]);
|
||||
}, [user, manufacturerPart]);
|
||||
|
||||
const editManufacturerPartFields = useManufacturerPartFields();
|
||||
|
||||
|
||||
@@ -26,13 +26,7 @@ import {
|
||||
} from '../../components/items/ActionDropdown';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import { useSupplierPartFields } from '../../forms/CompanyForms';
|
||||
import {
|
||||
useCreateApiFormModal,
|
||||
@@ -40,7 +34,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
import { PurchaseOrderTable } from '../../tables/purchasing/PurchaseOrderTable';
|
||||
import SupplierPriceBreakTable from '../../tables/purchasing/SupplierPriceBreakTable';
|
||||
@@ -70,13 +63,6 @@ export default function SupplierPartDetail() {
|
||||
}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.supplierpart,
|
||||
modelId: supplierPart?.pk
|
||||
});
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const panels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -127,29 +113,9 @@ export default function SupplierPartDetail() {
|
||||
) : (
|
||||
<Skeleton />
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.supplierpart,
|
||||
model_id: supplierPart?.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.supplierpart,
|
||||
model_id: supplierPart?.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.supplierpart,
|
||||
model_id: supplierPart?.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.supplierpart,
|
||||
model_id: supplierPart?.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [supplierPart, instanceInfo, showHistory]);
|
||||
}, [supplierPart]);
|
||||
|
||||
const supplierPartActions = useMemo(() => {
|
||||
return [
|
||||
|
||||
@@ -30,11 +30,7 @@ import { ApiIcon } from '../../components/items/ApiIcon';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import NavigationTree from '../../components/nav/NavigationTree';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import SegmentedControlPanel from '../../components/panels/SegmentedControlPanel';
|
||||
import { partCategoryFields } from '../../forms/PartForms';
|
||||
import {
|
||||
@@ -42,7 +38,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import { useStockAdjustActions } from '../../hooks/UseStockAdjustActions';
|
||||
import { useUserSettingsState } from '../../states/SettingsStates';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
@@ -84,11 +79,6 @@ export default function CategoryDetail() {
|
||||
}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.partcategory,
|
||||
modelId: category?.pk
|
||||
});
|
||||
|
||||
const stockOperationProps: StockOperationProps = useMemo(() => {
|
||||
return {
|
||||
refresh: refreshInstance,
|
||||
@@ -201,8 +191,6 @@ export default function CategoryDetail() {
|
||||
defaultValue: 'table'
|
||||
});
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const panels: PanelType[] = useMemo(
|
||||
() => [
|
||||
{
|
||||
@@ -262,27 +250,15 @@ export default function CategoryDetail() {
|
||||
/>
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.partcategory,
|
||||
model_id: category?.pk,
|
||||
hidden: !id || !category.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
{
|
||||
name: 'category_parameters',
|
||||
label: t`Parameter Templates`,
|
||||
icon: <IconListCheck />,
|
||||
hidden: !id || !category.pk,
|
||||
content: <PartCategoryTemplateTable categoryId={category?.pk} />
|
||||
},
|
||||
HistoryPanel({
|
||||
model_type: ModelType.partcategory,
|
||||
model_id: category?.pk,
|
||||
// Not shown for the top-level (root) category view
|
||||
visible: showHistory && !!id && !!category?.pk
|
||||
})
|
||||
}
|
||||
],
|
||||
[category, id, partsView, instanceInfo, showHistory]
|
||||
[category, id, partsView]
|
||||
);
|
||||
|
||||
const breadcrumbs = useMemo(
|
||||
|
||||
@@ -63,11 +63,6 @@ import {
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import NavigationTree from '../../components/nav/NavigationTree';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import { RenderPart } from '../../components/render/Part';
|
||||
import OrderPartsWizard from '../../components/wizards/OrderPartsWizard';
|
||||
@@ -287,8 +282,6 @@ export default function PartDetail() {
|
||||
}, [enableRevisionSelection, part, partRevisionOptions]);
|
||||
|
||||
// Part data panels (recalculate when part data changes)
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const partPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -489,6 +482,7 @@ export default function PartDetail() {
|
||||
icon: <IconLayersLinked />,
|
||||
content: <RelatedPartTable partId={part.pk} />
|
||||
},
|
||||
// TODO: remove this panel once generic model locking is available
|
||||
{
|
||||
name: 'parameters',
|
||||
label: t`Parameters`,
|
||||
@@ -513,22 +507,7 @@ export default function PartDetail() {
|
||||
/>
|
||||
</>
|
||||
)
|
||||
},
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.part,
|
||||
model_id: part?.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.part,
|
||||
model_id: part?.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.part,
|
||||
model_id: part?.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [
|
||||
id,
|
||||
@@ -539,8 +518,7 @@ export default function PartDetail() {
|
||||
bomInformation,
|
||||
revisionSelector,
|
||||
refreshInstance,
|
||||
instanceInfo,
|
||||
showHistory
|
||||
instanceInfo
|
||||
]);
|
||||
|
||||
const breadcrumbs = useMemo(() => {
|
||||
|
||||
@@ -23,13 +23,7 @@ import {
|
||||
} from '../../components/items/ActionDropdown';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import { StatusRenderer } from '../../components/render/StatusRenderer';
|
||||
import { usePurchaseOrderFields } from '../../forms/PurchaseOrderForms';
|
||||
import {
|
||||
@@ -37,7 +31,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import useStatusCodes from '../../hooks/UseStatusCodes';
|
||||
import { useGlobalSettingsState } from '../../states/SettingsStates';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
@@ -69,11 +62,6 @@ export default function PurchaseOrderDetail() {
|
||||
refetchOnMount: true
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.purchaseorder,
|
||||
modelId: order?.pk
|
||||
});
|
||||
|
||||
const orderCurrency = useMemo(
|
||||
() =>
|
||||
order.order_currency ||
|
||||
@@ -135,8 +123,6 @@ export default function PurchaseOrderDetail() {
|
||||
modelType: ModelType.purchaseorder
|
||||
});
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const orderPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -206,35 +192,9 @@ export default function PurchaseOrderDetail() {
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.purchaseorder,
|
||||
model_id: order.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.purchaseorder,
|
||||
model_id: order.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.purchaseorder,
|
||||
model_id: order.pk,
|
||||
note_count: instanceInfo.note_count,
|
||||
// TODO @matmair - change API to include a "locked" attribute that we can check here
|
||||
editable:
|
||||
order.status == poStatus.COMPLETE &&
|
||||
!globalSettings.isSet('PURCHASEORDER_EDIT_COMPLETED_ORDERS')
|
||||
? false
|
||||
: undefined
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.purchaseorder,
|
||||
model_id: order.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [order, id, user, instanceInfo, showHistory]);
|
||||
}, [order, id, user]);
|
||||
|
||||
const issueOrder = useCreateApiFormModal({
|
||||
url: apiUrl(ApiEndpoints.purchase_order_issue, order.pk),
|
||||
|
||||
@@ -23,13 +23,7 @@ import {
|
||||
} from '../../components/items/ActionDropdown';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import { StatusRenderer } from '../../components/render/StatusRenderer';
|
||||
import { useReturnOrderFields } from '../../forms/ReturnOrderForms';
|
||||
import {
|
||||
@@ -37,7 +31,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import useStatusCodes from '../../hooks/UseStatusCodes';
|
||||
import { useGlobalSettingsState } from '../../states/SettingsStates';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
@@ -68,11 +61,6 @@ export default function ReturnOrderDetail() {
|
||||
}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.returnorder,
|
||||
modelId: order?.pk
|
||||
});
|
||||
|
||||
const roStatus = useStatusCodes({ modelType: ModelType.returnorder });
|
||||
|
||||
const orderOpen = useMemo(() => {
|
||||
@@ -100,8 +88,6 @@ export default function ReturnOrderDetail() {
|
||||
);
|
||||
}, [order, globalSettings]);
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const orderPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -158,29 +144,9 @@ export default function ReturnOrderDetail() {
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.returnorder,
|
||||
model_id: order.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.returnorder,
|
||||
model_id: order.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.returnorder,
|
||||
model_id: order.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.returnorder,
|
||||
model_id: order.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [order, id, user, instanceInfo, showHistory]);
|
||||
}, [order, id, user]);
|
||||
|
||||
const orderBadges: ReactNode[] = useMemo(() => {
|
||||
return instanceQuery.isLoading
|
||||
|
||||
@@ -29,13 +29,7 @@ import {
|
||||
} from '../../components/items/ActionDropdown';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import { StatusRenderer } from '../../components/render/StatusRenderer';
|
||||
import { useSalesOrderFields } from '../../forms/SalesOrderForms';
|
||||
import {
|
||||
@@ -43,7 +37,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import useStatusCodes from '../../hooks/UseStatusCodes';
|
||||
import { useGlobalSettingsState } from '../../states/SettingsStates';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
@@ -77,11 +70,6 @@ export default function SalesOrderDetail() {
|
||||
}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.salesorder,
|
||||
modelId: order?.pk
|
||||
});
|
||||
|
||||
const orderCurrency = useMemo(() => {
|
||||
return (
|
||||
order.order_currency ||
|
||||
@@ -137,8 +125,6 @@ export default function SalesOrderDetail() {
|
||||
modelType: ModelType.salesorder
|
||||
});
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const orderPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -230,35 +216,9 @@ export default function SalesOrderDetail() {
|
||||
) : (
|
||||
<Skeleton />
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.salesorder,
|
||||
model_id: order.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.salesorder,
|
||||
model_id: order.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.salesorder,
|
||||
model_id: order.pk,
|
||||
note_count: instanceInfo.note_count,
|
||||
// TODO @matmair - change API to include a "locked" attribute that we can check here
|
||||
editable:
|
||||
order.status == soStatus.COMPLETE &&
|
||||
!globalSettings.isSet('SALESORDER_EDIT_COMPLETED_ORDERS')
|
||||
? false
|
||||
: undefined
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.salesorder,
|
||||
model_id: order.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [order, id, user, soStatus, instanceInfo, showHistory]);
|
||||
}, [order, id, user, soStatus]);
|
||||
|
||||
const issueOrder = useCreateApiFormModal({
|
||||
url: apiUrl(ApiEndpoints.sales_order_issue, order.pk),
|
||||
|
||||
@@ -26,13 +26,7 @@ import {
|
||||
} from '../../components/items/ActionDropdown';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import {
|
||||
useCheckShipmentForm,
|
||||
useCompleteShipmentForm,
|
||||
@@ -44,7 +38,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
import SalesOrderAllocationTable from '../../tables/sales/SalesOrderAllocationTable';
|
||||
import { SalesOrderShipmentDetailsPanel } from './SalesOrderShipmentDetailsPanel';
|
||||
@@ -69,16 +62,9 @@ export default function SalesOrderShipmentDetail() {
|
||||
}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.salesordershipment,
|
||||
modelId: shipment?.pk
|
||||
});
|
||||
|
||||
const isPending = useMemo(() => !shipment.shipment_date, [shipment]);
|
||||
const isChecked = useMemo(() => !!shipment.checked_by, [shipment]);
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const shipmentPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -106,29 +92,9 @@ export default function SalesOrderShipmentDetail() {
|
||||
modelTarget={ModelType.stockitem}
|
||||
/>
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.salesordershipment,
|
||||
model_id: shipment.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.salesordershipment,
|
||||
model_id: shipment.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.salesordershipment,
|
||||
model_id: shipment.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.salesordershipment,
|
||||
model_id: shipment.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [isPending, shipment, instanceInfo, showHistory]);
|
||||
}, [isPending, shipment]);
|
||||
|
||||
const editShipmentFields = useSalesOrderShipmentFields({
|
||||
pending: isPending,
|
||||
|
||||
@@ -35,7 +35,6 @@ import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import NavigationTree from '../../components/nav/NavigationTree';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import SegmentedControlPanel from '../../components/panels/SegmentedControlPanel';
|
||||
import LocateItemButton from '../../components/plugins/LocateItemButton';
|
||||
import { useStockLocationFields } from '../../forms/StockForms';
|
||||
@@ -45,7 +44,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import { useStockAdjustActions } from '../../hooks/UseStockAdjustActions';
|
||||
import { useUserSettingsState } from '../../states/SettingsStates';
|
||||
import { useGlobalSettingsState } from '../../states/SettingsStates';
|
||||
@@ -102,11 +100,6 @@ export default function Stock() {
|
||||
}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.stocklocation,
|
||||
modelId: location?.pk
|
||||
});
|
||||
|
||||
const detailsPanel =
|
||||
id && instanceQuery.isFetching ? (
|
||||
<Skeleton />
|
||||
@@ -208,15 +201,9 @@ export default function Stock() {
|
||||
}}
|
||||
/>
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.stocklocation,
|
||||
model_id: location.pk,
|
||||
hidden: !location.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [sublocationView, transferOrderView, location, id, instanceInfo]);
|
||||
}, [sublocationView, transferOrderView, location, id]);
|
||||
|
||||
const editLocation = useEditApiFormModal({
|
||||
url: ApiEndpoints.stock_location_list,
|
||||
|
||||
@@ -39,11 +39,6 @@ import {
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import NavigationTree from '../../components/nav/NavigationTree';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import LocateItemButton from '../../components/plugins/LocateItemButton';
|
||||
import { StatusRenderer } from '../../components/render/StatusRenderer';
|
||||
@@ -62,7 +57,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import { useStockAdjustActions } from '../../hooks/UseStockAdjustActions';
|
||||
import { useGlobalSettingsState } from '../../states/SettingsStates';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
@@ -114,11 +108,6 @@ export default function StockDetail() {
|
||||
defaultValue: {}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.stockitem,
|
||||
modelId: stockitem?.pk
|
||||
});
|
||||
|
||||
const showBuildAllocations: boolean = useMemo(() => {
|
||||
// Determine if "build allocations" should be shown for this stock item
|
||||
return (
|
||||
@@ -183,8 +172,6 @@ export default function StockDetail() {
|
||||
return stockitem?.part_detail?.assembly;
|
||||
}, [trackedBomItemQuery, stockitem]);
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const stockPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -305,32 +292,15 @@ export default function StockDetail() {
|
||||
) : (
|
||||
<Skeleton />
|
||||
)
|
||||
},
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.stockitem,
|
||||
model_id: stockitem.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.stockitem,
|
||||
model_id: stockitem.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.stockitem,
|
||||
model_id: stockitem.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [
|
||||
showHistory,
|
||||
showSalesAllocations,
|
||||
showBuildAllocations,
|
||||
showInstalledItems,
|
||||
stockitem,
|
||||
id,
|
||||
user,
|
||||
instanceInfo
|
||||
user
|
||||
]);
|
||||
|
||||
const breadcrumbs = useMemo(
|
||||
|
||||
@@ -26,13 +26,7 @@ import {
|
||||
} from '../../components/items/ActionDropdown';
|
||||
import InstanceDetail from '../../components/nav/InstanceDetail';
|
||||
import { PageDetail } from '../../components/nav/PageDetail';
|
||||
import AttachmentPanel from '../../components/panels/AttachmentPanel';
|
||||
import HistoryPanel, {
|
||||
useShowHistoryPanel
|
||||
} from '../../components/panels/HistoryPanel';
|
||||
import NotesPanel from '../../components/panels/NotesPanel';
|
||||
import { PanelGroup } from '../../components/panels/PanelGroup';
|
||||
import ParametersPanel from '../../components/panels/ParametersPanel';
|
||||
import { StatusRenderer } from '../../components/render/StatusRenderer';
|
||||
import { useTransferOrderFields } from '../../forms/TransferOrderForms';
|
||||
import {
|
||||
@@ -40,7 +34,6 @@ import {
|
||||
useEditApiFormModal
|
||||
} from '../../hooks/UseForm';
|
||||
import { useInstance } from '../../hooks/UseInstance';
|
||||
import { useInstanceInfo } from '../../hooks/UseInstanceInfo';
|
||||
import useStatusCodes from '../../hooks/UseStatusCodes';
|
||||
import { useGlobalSettingsState } from '../../states/SettingsStates';
|
||||
import { useUserState } from '../../states/UserState';
|
||||
@@ -67,11 +60,6 @@ export default function TransferOrderDetail() {
|
||||
}
|
||||
});
|
||||
|
||||
const { instanceInfo } = useInstanceInfo({
|
||||
modelType: ModelType.transferorder,
|
||||
modelId: order?.pk
|
||||
});
|
||||
|
||||
const toStatus = useStatusCodes({ modelType: ModelType.transferorder });
|
||||
|
||||
const lineItemsEditable: boolean = useMemo(() => {
|
||||
@@ -102,8 +90,6 @@ export default function TransferOrderDetail() {
|
||||
<TransferOrderDetailsPanel instance={order} />
|
||||
);
|
||||
|
||||
const showHistory = useShowHistoryPanel();
|
||||
|
||||
const orderPanels: PanelType[] = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
@@ -182,29 +168,9 @@ export default function TransferOrderDetail() {
|
||||
modelTarget={ModelType.stockitem}
|
||||
/>
|
||||
)
|
||||
},
|
||||
ParametersPanel({
|
||||
model_type: ModelType.transferorder,
|
||||
model_id: order.pk,
|
||||
parameter_count: instanceInfo.parameter_count
|
||||
}),
|
||||
AttachmentPanel({
|
||||
model_type: ModelType.transferorder,
|
||||
model_id: order.pk,
|
||||
attachment_count: instanceInfo.attachment_count
|
||||
}),
|
||||
NotesPanel({
|
||||
model_type: ModelType.transferorder,
|
||||
model_id: order.pk,
|
||||
note_count: instanceInfo.note_count
|
||||
}),
|
||||
HistoryPanel({
|
||||
model_type: ModelType.transferorder,
|
||||
model_id: order.pk,
|
||||
visible: showHistory
|
||||
})
|
||||
}
|
||||
];
|
||||
}, [order, id, user, instanceInfo, showHistory]);
|
||||
}, [order, id, user]);
|
||||
|
||||
const orderBadges: ReactNode[] = useMemo(() => {
|
||||
return instanceQuery.isLoading
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { create } from 'zustand';
|
||||
import { createJSONStorage, persist } from 'zustand/middleware';
|
||||
|
||||
import { ApiEndpoints } from '@lib/enums/ApiEndpoints';
|
||||
import type { ModelFeature } from '@lib/enums/ModelFeature';
|
||||
import type { ModelType } from '@lib/enums/ModelType';
|
||||
import { apiUrl } from '@lib/functions/Api';
|
||||
import { api } from '../App';
|
||||
import { useUserState } from './UserState';
|
||||
|
||||
export type ModelFeatureLookup = Record<ModelType | string, ModelFeatureRef[]>;
|
||||
export type ModelFeatureRef = ModelFeature | (string & {});
|
||||
|
||||
interface ModelFeatureStateProps {
|
||||
features?: ModelFeatureLookup;
|
||||
fetchFeatures: () => Promise<void>;
|
||||
hasFeature: (model: ModelType | string, feature: ModelFeatureRef) => boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* State for tracking which generic features each model type supports.
|
||||
* This is static per server instance, so is fetched once with the global states.
|
||||
*/
|
||||
export const useModelFeatureState = create<ModelFeatureStateProps>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
features: undefined,
|
||||
fetchFeatures: async () => {
|
||||
const { isLoggedIn } = useUserState.getState();
|
||||
|
||||
if (!isLoggedIn()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Feature information is provided by the content type API
|
||||
await api
|
||||
.get(apiUrl(ApiEndpoints.content_type_list), {
|
||||
params: { features: true }
|
||||
})
|
||||
.then((response) => {
|
||||
const lookup: ModelFeatureLookup = {};
|
||||
|
||||
for (const contentType of response.data ?? []) {
|
||||
lookup[contentType.model] = contentType.features ?? [];
|
||||
}
|
||||
|
||||
set({ features: lookup });
|
||||
})
|
||||
.catch(() => {
|
||||
console.error('ERR: Error fetching model feature information');
|
||||
});
|
||||
},
|
||||
hasFeature: (model: ModelType | string, feature: ModelFeatureRef) => {
|
||||
return get().features?.[model]?.includes(feature) ?? false;
|
||||
}
|
||||
}),
|
||||
{
|
||||
name: 'model-feature-state',
|
||||
version: 1,
|
||||
storage: createJSONStorage(() => sessionStorage),
|
||||
partialize: (state) => ({ features: state.features })
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const EMPTY_FEATURES: ModelFeatureRef[] = [];
|
||||
|
||||
/**
|
||||
* Hook to get list of features for given model type.
|
||||
* Returns an empty list if the model is unknown, or the information is not (yet) loaded.
|
||||
*/
|
||||
export function useModelFeatures(
|
||||
model: ModelType | string | undefined
|
||||
): ModelFeatureRef[] {
|
||||
return useModelFeatureState(
|
||||
(state) => (model ? state.features?.[model] : undefined) ?? EMPTY_FEATURES
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { PluginProps } from '@lib/types/Plugins';
|
||||
import { removeTraceId, setApiDefaults, setTraceId } from '../App';
|
||||
import { useGlobalStatusState } from './GlobalStatusState';
|
||||
import { useIconState } from './IconState';
|
||||
import { useModelFeatureState } from './ModelFeatureState';
|
||||
import { useServerApiState } from './ServerApiState';
|
||||
import { useGlobalSettingsState, useUserSettingsState } from './SettingsStates';
|
||||
import { useUserState } from './UserState';
|
||||
@@ -84,7 +85,8 @@ export async function fetchGlobalStates(force = false) {
|
||||
useUserSettingsState.getState().fetchSettings(),
|
||||
useGlobalSettingsState.getState().fetchSettings(),
|
||||
useGlobalStatusState.getState().fetchStatus(),
|
||||
useIconState.getState().fetchIcons()
|
||||
useIconState.getState().fetchIcons(),
|
||||
useModelFeatureState.getState().fetchFeatures()
|
||||
]);
|
||||
removeTraceId(traceId);
|
||||
globalStatesFetched = true;
|
||||
|
||||
Reference in new issue
Block a user