code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def validate_part_parameter(self, parameter, data):
"""Validate part parameter data.
These examples are silly, but serve to demonstrate how the feature could be used
"""
if parameter.template.name.lower() in ['length', 'width']:
d = int(data)
if d >= 100:
... | Validate part parameter data.
These examples are silly, but serve to demonstrate how the feature could be used
| validate_part_parameter | python | inventree/InvenTree | src/backend/InvenTree/plugin/samples/integration/validation_sample.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/integration/validation_sample.py | MIT |
def validate_serial_number(self, serial: str, part, stock_item=None):
"""Validate serial number for a given StockItem.
These examples are silly, but serve to demonstrate how the feature could be used
"""
if self.get_setting('SERIAL_MUST_BE_PALINDROME'):
if serial != serial[:... | Validate serial number for a given StockItem.
These examples are silly, but serve to demonstrate how the feature could be used
| validate_serial_number | python | inventree/InvenTree | src/backend/InvenTree/plugin/samples/integration/validation_sample.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/integration/validation_sample.py | MIT |
def increment_serial_number(self, serial: str, part=None, **kwargs):
"""Increment a serial number.
These examples are silly, but serve to demonstrate how the feature could be used
"""
try:
sn = int(serial)
sn += 1
# Skip any serial number which is a ... | Increment a serial number.
These examples are silly, but serve to demonstrate how the feature could be used
| increment_serial_number | python | inventree/InvenTree | src/backend/InvenTree/plugin/samples/integration/validation_sample.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/integration/validation_sample.py | MIT |
def validate_batch_code(self, batch_code: str, item):
"""Ensure that a particular batch code meets specification.
These examples are silly, but serve to demonstrate how the feature could be used
"""
prefix = self.get_setting('BATCH_CODE_PREFIX')
if len(batch_code) > 0 and prefi... | Ensure that a particular batch code meets specification.
These examples are silly, but serve to demonstrate how the feature could be used
| validate_batch_code | python | inventree/InvenTree | src/backend/InvenTree/plugin/samples/integration/validation_sample.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/integration/validation_sample.py | MIT |
def locate_stock_item(self, item_pk):
"""Locate a StockItem.
Args:
item_pk: primary key for item
"""
from stock.models import StockItem
logger.info('SampleLocatePlugin attempting to locate item ID %s', item_pk)
try:
item = StockItem.objects.get(... | Locate a StockItem.
Args:
item_pk: primary key for item
| locate_stock_item | python | inventree/InvenTree | src/backend/InvenTree/plugin/samples/locate/locate_sample.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/locate/locate_sample.py | MIT |
def locate_stock_location(self, location_pk):
"""Locate a StockLocation.
Args:
location_pk: primary key for location
"""
from stock.models import StockLocation
logger.info(
'SampleLocatePlugin attempting to locate location ID %s', location_pk
)
... | Locate a StockLocation.
Args:
location_pk: primary key for location
| locate_stock_location | python | inventree/InvenTree | src/backend/InvenTree/plugin/samples/locate/locate_sample.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/locate/locate_sample.py | MIT |
def safe_url(view_name, *args, **kwargs):
"""Safe lookup fnc for URLs.
Returns None if not found
"""
try:
return reverse(view_name, args=args, kwargs=kwargs)
except Exception:
return None | Safe lookup fnc for URLs.
Returns None if not found
| safe_url | python | inventree/InvenTree | src/backend/InvenTree/plugin/templatetags/plugin_extras.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/templatetags/plugin_extras.py | MIT |
def filter_items(self, queryset, name, values):
"""Filter against a comma-separated list of provided items.
Note: This filter is only applied if the 'model_type' is also provided.
"""
model_type = self.data.get('model_type', None)
values = values.strip().split(',')
if m... | Filter against a comma-separated list of provided items.
Note: This filter is only applied if the 'model_type' is also provided.
| filter_items | python | inventree/InvenTree | src/backend/InvenTree/report/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/api.py | MIT |
def get_plugin_class(self, plugin_slug: str, raise_error=False):
"""Return the plugin class for the given plugin key."""
from plugin.models import PluginConfig
if not plugin_slug:
# Use the default label printing plugin
plugin_slug = InvenTreeLabelPlugin.NAME.lower()
... | Return the plugin class for the given plugin key. | get_plugin_class | python | inventree/InvenTree | src/backend/InvenTree/report/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/api.py | MIT |
def get_plugin_serializer(self, plugin):
"""Return the serializer for the given plugin."""
if plugin and hasattr(plugin, 'get_printing_options_serializer'):
return plugin.get_printing_options_serializer(
self.request,
data=self.request.data,
co... | Return the serializer for the given plugin. | get_plugin_serializer | python | inventree/InvenTree | src/backend/InvenTree/report/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/api.py | MIT |
def get_serializer(self, *args, **kwargs):
"""Return serializer information for the label print endpoint."""
plugin = None
# Plugin information provided?
if self.request:
plugin_key = self.request.data.get('plugin', '')
# Legacy url based lookup
if no... | Return serializer information for the label print endpoint. | get_serializer | python | inventree/InvenTree | src/backend/InvenTree/report/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/api.py | MIT |
def print(self, template, items_to_print, plugin, request):
"""Print this label template against a number of provided items."""
import report.tasks
from InvenTree.tasks import offload_task
if plugin_serializer := plugin.get_printing_options_serializer(
request, data=request.... | Print this label template against a number of provided items. | print | python | inventree/InvenTree | src/backend/InvenTree/report/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/api.py | MIT |
def print(self, template, items_to_print, request):
"""Print this report template against a number of provided items.
This functionality is offloaded to the background worker process,
which will update the status of the DataOutput object as it progresses.
"""
import report.tasks... | Print this report template against a number of provided items.
This functionality is offloaded to the background worker process,
which will update the status of the DataOutput object as it progresses.
| print | python | inventree/InvenTree | src/backend/InvenTree/report/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/api.py | MIT |
def ready(self):
"""This function is called whenever the app is loaded."""
# Configure logging for PDF generation (disable "info" messages)
# Reduce log output for fontTools and weasyprint
for name, log_manager in logging.root.manager.loggerDict.items():
if name.lower().star... | This function is called whenever the app is loaded. | ready | python | inventree/InvenTree | src/backend/InvenTree/report/apps.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/apps.py | MIT |
def cleanup(self):
"""Cleanup old label and report outputs."""
try:
from report.tasks import cleanup_old_report_outputs
cleanup_old_report_outputs()
except Exception:
pass | Cleanup old label and report outputs. | cleanup | python | inventree/InvenTree | src/backend/InvenTree/report/apps.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/apps.py | MIT |
def file_from_template(self, dir_name: str, file_name: str) -> ContentFile:
"""Construct a new ContentFile from a template file.
Args:
dir_name (str): The name of the directory containing the template
file_name (str): The name of the template file
Returns:
Co... | Construct a new ContentFile from a template file.
Args:
dir_name (str): The name of the directory containing the template
file_name (str): The name of the template file
Returns:
ContentFile: The ContentFile object containing the template
| file_from_template | python | inventree/InvenTree | src/backend/InvenTree/report/apps.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/apps.py | MIT |
def report_model_types():
"""Return a list of database models for which reports can be generated."""
from InvenTree.helpers_model import getModelsWithMixin
from report.mixins import InvenTreeReportMixin
return list(getModelsWithMixin(InvenTreeReportMixin)) | Return a list of database models for which reports can be generated. | report_model_types | python | inventree/InvenTree | src/backend/InvenTree/report/helpers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/helpers.py | MIT |
def report_model_from_name(model_name: str):
"""Returns the internal model class from the provided name."""
if not model_name:
return None
for model in report_model_types():
if model.__name__.lower() == model_name:
return model | Returns the internal model class from the provided name. | report_model_from_name | python | inventree/InvenTree | src/backend/InvenTree/report/helpers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/helpers.py | MIT |
def report_model_options():
"""Return a list of options for models which support report printing."""
return [
(model.__name__.lower(), model._meta.verbose_name)
for model in report_model_types()
] | Return a list of options for models which support report printing. | report_model_options | python | inventree/InvenTree | src/backend/InvenTree/report/helpers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/helpers.py | MIT |
def report_page_size_options():
"""Returns a list of page size options for PDF reports."""
return [
('A4', _('A4')),
('A3', _('A3')),
('Legal', _('Legal')),
('Letter', _('Letter')),
] | Returns a list of page size options for PDF reports. | report_page_size_options | python | inventree/InvenTree | src/backend/InvenTree/report/helpers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/helpers.py | MIT |
def page_sizes():
"""Returns a dict of page sizes for PDF reports."""
return {
'A4': (210, 297),
'A3': (297, 420),
'Legal': (215.9, 355.6),
'Letter': (215.9, 279.4),
} | Returns a dict of page sizes for PDF reports. | page_sizes | python | inventree/InvenTree | src/backend/InvenTree/report/helpers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/helpers.py | MIT |
def page_size(page_code):
"""Return the page size associated with a particular page code."""
if page_code in page_sizes():
return page_sizes()[page_code]
# Default to A4
logger.warning("Unknown page size code '%s' - defaulting to A4", page_code)
return page_sizes()['A4'] | Return the page size associated with a particular page code. | page_size | python | inventree/InvenTree | src/backend/InvenTree/report/helpers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/helpers.py | MIT |
def report_page_size_default():
"""Returns the default page size for PDF reports."""
try:
page_size = get_global_setting('REPORT_DEFAULT_PAGE_SIZE', 'A4', create=False)
except Exception as exc:
logger.exception('Error getting default page size: %s', str(exc))
page_size = 'A4'
re... | Returns the default page size for PDF reports. | report_page_size_default | python | inventree/InvenTree | src/backend/InvenTree/report/helpers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/helpers.py | MIT |
def encode_image_base64(image, img_format: str = 'PNG') -> str:
"""Return a base-64 encoded image which can be rendered in an <img> tag.
Arguments:
image: {Image} -- Image to encode
img_format: {str} -- Image format (default = 'PNG')
Returns:
str -- Base64 encoded image data e.g. '... | Return a base-64 encoded image which can be rendered in an <img> tag.
Arguments:
image: {Image} -- Image to encode
img_format: {str} -- Image format (default = 'PNG')
Returns:
str -- Base64 encoded image data e.g. 'data:image/png;base64,xxxxxxxxx'
| encode_image_base64 | python | inventree/InvenTree | src/backend/InvenTree/report/helpers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/helpers.py | MIT |
def rename_template(instance, filename):
"""Function to rename a report template once uploaded.
- Retains the original uploaded filename
- Checks for duplicate filenames across instance class
"""
path = instance.get_upload_path(filename)
# Throw error if any other model instances reference thi... | Function to rename a report template once uploaded.
- Retains the original uploaded filename
- Checks for duplicate filenames across instance class
| rename_template | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def template_name(self):
"""Return the filename of the template associated with this model class."""
template = getattr(self, self.TEMPLATE_FIELD).name
template = template.replace('/', os.path.sep)
template = template.replace('\\', os.path.sep)
template = settings.MEDIA_ROOT.joi... | Return the filename of the template associated with this model class. | template_name | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def get_upload_path(self, filename):
"""Generate an upload path for the given filename."""
fn = os.path.basename(filename)
return os.path.join('report', self.SUBDIR, fn) | Generate an upload path for the given filename. | get_upload_path | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def check_existing_file(self, path, raise_error=False):
"""Check if a file already exists with the given filename."""
filters = {self.TEMPLATE_FIELD: self.get_upload_path(path)}
exists = self.__class__.objects.filter(**filters).exclude(pk=self.pk).exists()
if exists and raise_error:
... | Check if a file already exists with the given filename. | check_existing_file | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def validate_unique(self, exclude=None):
"""Validate that this template is unique."""
proposed_path = self.get_upload_path(self.template_name)
self.check_existing_file(proposed_path, raise_error=True)
return super().validate_unique(exclude) | Validate that this template is unique. | validate_unique | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def save(self, *args, **kwargs):
"""Perform additional actions when the report is saved."""
# Increment revision number
self.revision += 1
super().save() | Perform additional actions when the report is saved. | save | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def render_as_string(self, instance, request=None, **kwargs) -> str:
"""Render the report to a HTML string.
Arguments:
instance: The model instance to render against
request: A HTTPRequest object (optional)
Returns:
str: HTML string
"""
conte... | Render the report to a HTML string.
Arguments:
instance: The model instance to render against
request: A HTTPRequest object (optional)
Returns:
str: HTML string
| render_as_string | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def render(self, instance, request=None, **kwargs) -> bytes:
"""Render the template to a PDF file.
Arguments:
instance: The model instance to render against
request: A HTTPRequest object (optional)
Returns:
bytes: PDF data
"""
html = self.ren... | Render the template to a PDF file.
Arguments:
instance: The model instance to render against
request: A HTTPRequest object (optional)
Returns:
bytes: PDF data
| render | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def clean(self):
"""Clean model instance, and ensure validity."""
super().clean()
model = self.get_model()
filters = self.filters
if model and filters:
report.validators.validate_filters(filters, model=model) | Clean model instance, and ensure validity. | clean | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def base_context(self, request=None) -> BaseContextExtension:
"""Return base context data (available to all templates)."""
return {
'base_url': get_base_url(request=request),
'date': InvenTree.helpers.current_date(),
'datetime': InvenTree.helpers.current_time(),
... | Return base context data (available to all templates). | base_context | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def get_context(self, instance, request=None, **kwargs):
"""Supply context data to the generic template for rendering.
Arguments:
instance: The model instance we are printing against
request: The request object (optional)
"""
# Provide base context information to... | Supply context data to the generic template for rendering.
Arguments:
instance: The model instance we are printing against
request: The request object (optional)
| get_context | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def get_report_size(self) -> str:
"""Return the printable page size for this report."""
try:
page_size_default = cast(
str, get_global_setting('REPORT_DEFAULT_PAGE_SIZE', 'A4', create=False)
)
except Exception:
page_size_default = 'A4'
... | Return the printable page size for this report. | get_report_size | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def get_context(self, instance, request=None, **kwargs):
"""Supply context data to the report template for rendering."""
base_context = super().get_context(instance, request)
report_context: ReportContextExtension = {
'page_size': self.get_report_size(),
'landscape': self... | Supply context data to the report template for rendering. | get_context | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def print(self, items: list, request=None, output=None, **kwargs) -> DataOutput:
"""Print reports for a list of items against this template.
Arguments:
items: A list of items to print reports for (model instance)
output: The DataOutput object to use (if provided)
req... | Print reports for a list of items against this template.
Arguments:
items: A list of items to print reports for (model instance)
output: The DataOutput object to use (if provided)
request: The request object (optional)
Returns:
output: The DataOutput obj... | print | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def generate_page_style(self, **kwargs):
"""Generate @page style for the label template.
This is inserted at the top of the style block for a given label
"""
width = kwargs.get('width', self.width)
height = kwargs.get('height', self.height)
margin = kwargs.get('margin', ... | Generate @page style for the label template.
This is inserted at the top of the style block for a given label
| generate_page_style | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def get_context(self, instance, request=None, **kwargs):
"""Supply context data to the label template for rendering."""
base_context = super().get_context(instance, request, **kwargs)
label_context: LabelContextExtension = {
'width': self.width,
'height': self.height,
... | Supply context data to the label template for rendering. | get_context | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def print(
self,
items: list,
plugin: InvenTreePlugin,
output=None,
options=None,
request=None,
**kwargs,
) -> DataOutput:
"""Print labels for a list of items against this template.
Arguments:
items: A list of items to print labels... | Print labels for a list of items against this template.
Arguments:
items: A list of items to print labels for (model instance)
plugin: The plugin to use for label rendering
output: The DataOutput object to use (if provided)
options: Additional options for the lab... | print | python | inventree/InvenTree | src/backend/InvenTree/report/models.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/models.py | MIT |
def __init__(self, *args, **kwargs):
"""Override the constructor for the ReportSerializerBase.
The primary goal here is to ensure that the 'choices' attribute
is set correctly for the 'model_type' field.
"""
super().__init__(*args, **kwargs)
if len(self.fields['model_ty... | Override the constructor for the ReportSerializerBase.
The primary goal here is to ensure that the 'choices' attribute
is set correctly for the 'model_type' field.
| __init__ | python | inventree/InvenTree | src/backend/InvenTree/report/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/serializers.py | MIT |
def __init__(self, *args, **kwargs):
"""Override the constructor to add the extra plugin fields."""
# Reset to a known state
self.Meta.fields = ['template', 'items', 'plugin']
if plugin_serializer := kwargs.pop('plugin_serializer', None):
for key, field in plugin_serializer.... | Override the constructor to add the extra plugin fields. | __init__ | python | inventree/InvenTree | src/backend/InvenTree/report/serializers.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/serializers.py | MIT |
def print_reports(template_id: int, item_ids: list[int], output_id: int, **kwargs):
"""Print multiple reports against the provided template.
Arguments:
template_id: The ID of the ReportTemplate to use
item_ids: List of item IDs to generate the report against
output_id: The ID of the Dat... | Print multiple reports against the provided template.
Arguments:
template_id: The ID of the ReportTemplate to use
item_ids: List of item IDs to generate the report against
output_id: The ID of the DataOutput to use (if provided)
This function is intended to be called by the background ... | print_reports | python | inventree/InvenTree | src/backend/InvenTree/report/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tasks.py | MIT |
def print_labels(
template_id: int, item_ids: list[int], output_id: int, plugin_slug: str, **kwargs
):
"""Print multiple labels against the provided template.
Arguments:
template_id: The ID of the LabelTemplate to use
item_ids: List of item IDs to generate the labels against
output_... | Print multiple labels against the provided template.
Arguments:
template_id: The ID of the LabelTemplate to use
item_ids: List of item IDs to generate the labels against
output_id: The ID of the DataOutput to use (if provided)
plugin_slug: The ID of the LabelPlugin to use (if provid... | print_labels | python | inventree/InvenTree | src/backend/InvenTree/report/tasks.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tasks.py | MIT |
def setUp(self):
"""Ensure cache is cleared as part of test setup."""
cache.clear()
apps.get_app_config('report').create_default_reports()
return super().setUp() | Ensure cache is cleared as part of test setup. | setUp | python | inventree/InvenTree | src/backend/InvenTree/report/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tests.py | MIT |
def test_list_endpoint(self):
"""Test that the LIST endpoint works for each report."""
url = reverse('api-report-template-list')
response = self.get(url)
self.assertEqual(response.status_code, 200)
reports = ReportTemplate.objects.all()
n = len(reports)
# API e... | Test that the LIST endpoint works for each report. | test_list_endpoint | python | inventree/InvenTree | src/backend/InvenTree/report/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tests.py | MIT |
def test_create_endpoint(self):
"""Test that creating a new report works for each report."""
url = reverse('api-report-template-list')
# Create a new report
# Django REST API "APITestCase" does not work like requests - to send a file without it existing on disk,
# create it as a... | Test that creating a new report works for each report. | test_create_endpoint | python | inventree/InvenTree | src/backend/InvenTree/report/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tests.py | MIT |
def test_detail_endpoint(self):
"""Test that the DETAIL endpoint works for each report."""
reports = ReportTemplate.objects.all()
n = len(reports)
# Make sure at least one report defined
self.assertGreaterEqual(n, 1)
# Check detail page for first report
respons... | Test that the DETAIL endpoint works for each report. | test_detail_endpoint | python | inventree/InvenTree | src/backend/InvenTree/report/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tests.py | MIT |
def test_print(self):
"""Test that we can print a report manually."""
# Find a suitable report template
template = ReportTemplate.objects.filter(
enabled=True, model_type='stockitem'
).first()
# Gather some items
items = StockItem.objects.all()[0:5]
... | Test that we can print a report manually. | test_print | python | inventree/InvenTree | src/backend/InvenTree/report/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tests.py | MIT |
def test_print(self):
"""Test manual printing of label templates."""
# Find a suitable label template
template = LabelTemplate.objects.filter(enabled=True, model_type='part').first()
# Gather some items
parts = Part.objects.all()[0:10]
# Find the label plugin (render to... | Test manual printing of label templates. | test_print | python | inventree/InvenTree | src/backend/InvenTree/report/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tests.py | MIT |
def run_print_test(self, qs, model_type, label: bool = True):
"""Run tests on single and multiple page printing.
Args:
qs: class of the base queryset
model_type: the model type of the queryset
label: whether the model is a label or report
"""
mdl = La... | Run tests on single and multiple page printing.
Args:
qs: class of the base queryset
model_type: the model type of the queryset
label: whether the model is a label or report
| run_print_test | python | inventree/InvenTree | src/backend/InvenTree/report/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tests.py | MIT |
def setUp(self):
"""Setup function for the stock item TestReport."""
apps.get_app_config('report').create_default_reports()
self.do_activate_plugin()
return super().setUp() | Setup function for the stock item TestReport. | setUp | python | inventree/InvenTree | src/backend/InvenTree/report/tests.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/tests.py | MIT |
def test_getindex(self):
"""Tests for the 'getindex' template tag."""
fn = report_tags.getindex
data = [1, 2, 3, 4, 5, 6]
# Out of bounds or invalid
self.assertEqual(fn(data, -1), None)
self.assertEqual(fn(data, 99), None)
self.assertEqual(fn(data, 'xx'), None)
... | Tests for the 'getindex' template tag. | test_getindex | python | inventree/InvenTree | src/backend/InvenTree/report/test_tags.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/test_tags.py | MIT |
def test_getkey(self):
"""Tests for the 'getkey' template tag."""
data = {'hello': 'world', 'foo': 'bar', 'with spaces': 'withoutspaces', 1: 2}
# Valid case
for k, v in data.items():
self.assertEqual(report_tags.getkey(data, k), v)
# Error case
self.assertEq... | Tests for the 'getkey' template tag. | test_getkey | python | inventree/InvenTree | src/backend/InvenTree/report/test_tags.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/test_tags.py | MIT |
def test_maths_tags(self):
"""Simple tests for mathematical operator tags."""
self.assertEqual(report_tags.add(1, 2), 3)
self.assertEqual(report_tags.subtract(10, 4.2), 5.8)
self.assertEqual(report_tags.multiply(2.3, 4), 9.2)
self.assertEqual(report_tags.divide(100, 5), 20) | Simple tests for mathematical operator tags. | test_maths_tags | python | inventree/InvenTree | src/backend/InvenTree/report/test_tags.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/test_tags.py | MIT |
def test_number_tags(self):
"""Simple tests for number formatting tags."""
fn = report_tags.format_number
self.assertEqual(fn(1234), '1234')
self.assertEqual(fn(1234.5678, decimal_places=2), '1234.57')
self.assertEqual(fn(1234.5678, decimal_places=3), '1234.568')
self.as... | Simple tests for number formatting tags. | test_number_tags | python | inventree/InvenTree | src/backend/InvenTree/report/test_tags.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/test_tags.py | MIT |
def test_date_tags(self):
"""Test for date formatting tags.
- Source timezone is Australia/Sydney
- Server timezone is America/New York
"""
time = timezone.datetime(
year=2024,
month=3,
day=13,
hour=12,
minute=30,
... | Test for date formatting tags.
- Source timezone is Australia/Sydney
- Server timezone is America/New York
| test_date_tags | python | inventree/InvenTree | src/backend/InvenTree/report/test_tags.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/test_tags.py | MIT |
def validate_report_model_type(value):
"""Ensure that the selected model type is valid."""
model_options = [el[0] for el in report.helpers.report_model_options()]
if value not in model_options:
raise ValidationError('Not a valid model type') | Ensure that the selected model type is valid. | validate_report_model_type | python | inventree/InvenTree | src/backend/InvenTree/report/validators.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/validators.py | MIT |
def validate_filters(value, model=None):
"""Validate that the provided model filters are valid."""
from InvenTree.helpers import validateFilterString
return validateFilterString(value, model=model) | Validate that the provided model filters are valid. | validate_filters | python | inventree/InvenTree | src/backend/InvenTree/report/validators.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/validators.py | MIT |
def forward(apps, schema_editor):
"""Run forwards migration.
- Create a new ReportTemplate instance for each existing report
"""
# New 'generic' report template model
ReportTemplate = apps.get_model('report', 'reporttemplate')
count = 0
for model_type, report_model in report_model_m... | Run forwards migration.
- Create a new ReportTemplate instance for each existing report
| forward | python | inventree/InvenTree | src/backend/InvenTree/report/migrations/0023_auto_20240421_0455.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/migrations/0023_auto_20240421_0455.py | MIT |
def reverse(apps, schema_editor):
"""Run reverse migration.
- Delete any ReportTemplate instances in the database
"""
ReportTemplate = apps.get_model('report', 'reporttemplate')
n = ReportTemplate.objects.count()
if n > 0:
for item in ReportTemplate.objects.all():
item.tem... | Run reverse migration.
- Delete any ReportTemplate instances in the database
| reverse | python | inventree/InvenTree | src/backend/InvenTree/report/migrations/0023_auto_20240421_0455.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/migrations/0023_auto_20240421_0455.py | MIT |
def label_model_map():
"""Map legacy label template models to model_type values."""
return {
"stockitemlabel": "stockitem",
"stocklocationlabel": "stocklocation",
"partlabel": "part",
"buildlinelabel": "buildline",
} | Map legacy label template models to model_type values. | label_model_map | python | inventree/InvenTree | src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py | MIT |
def convert_legacy_labels(table_name, model_name, template_model):
"""Map labels from an existing table to a new model type
Arguments:
table_name: The name of the existing table
model_name: The name of the new model type
template_model: The model class for the new template model
... | Map labels from an existing table to a new model type
Arguments:
table_name: The name of the existing table
model_name: The name of the new model type
template_model: The model class for the new template model
Note: We use raw SQL queries here, as the original 'label' app has b... | convert_legacy_labels | python | inventree/InvenTree | src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py | MIT |
def forward(apps, schema_editor):
"""Run forwards migrations.
- Create a new LabelTemplate instance for each existing legacy label template.
"""
LabelTemplate = apps.get_model('report', 'labeltemplate')
count = 0
for template_class, model_type in label_model_map().items():
table... | Run forwards migrations.
- Create a new LabelTemplate instance for each existing legacy label template.
| forward | python | inventree/InvenTree | src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py | MIT |
def reverse(apps, schema_editor):
"""Run reverse migrations.
- Delete any LabelTemplate instances in the database
"""
LabelTemplate = apps.get_model('report', 'labeltemplate')
n = LabelTemplate.objects.count()
if n > 0:
for item in LabelTemplate.objects.all():
item.t... | Run reverse migrations.
- Delete any LabelTemplate instances in the database
| reverse | python | inventree/InvenTree | src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py | MIT |
def clean_barcode(data):
"""Return a 'cleaned' string for encoding into a barcode / qrcode.
- This function runs the data through bleach, and removes any malicious HTML content.
- Used to render raw barcode data into the rendered HTML templates
"""
from InvenTree.helpers import strip_html_tags
... | Return a 'cleaned' string for encoding into a barcode / qrcode.
- This function runs the data through bleach, and removes any malicious HTML content.
- Used to render raw barcode data into the rendered HTML templates
| clean_barcode | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/barcode.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/barcode.py | MIT |
def qrcode(data: str, **kwargs) -> str:
"""Return a byte-encoded QR code image.
Arguments:
data: Data to encode
Keyword Arguments:
version (int): QR code version, (None to auto detect) (default = None)
error_correction (str): Error correction level (L: 7%, M: 15%, Q: 25%, H: 30%) (... | Return a byte-encoded QR code image.
Arguments:
data: Data to encode
Keyword Arguments:
version (int): QR code version, (None to auto detect) (default = None)
error_correction (str): Error correction level (L: 7%, M: 15%, Q: 25%, H: 30%) (default = 'M')
box_size (int): pixel di... | qrcode | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/barcode.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/barcode.py | MIT |
def barcode(data: str, barcode_class='code128', **kwargs) -> str:
"""Render a 1D barcode.
Arguments:
data: Data to encode
barcode_class (str): The type of barcode to generate (default = 'code128')
Keyword Arguments:
format (str): Image format (default = 'PNG')
fill_color (s... | Render a 1D barcode.
Arguments:
data: Data to encode
barcode_class (str): The type of barcode to generate (default = 'code128')
Keyword Arguments:
format (str): Image format (default = 'PNG')
fill_color (str): Foreground color (default = 'black')
back_color (str): Backg... | barcode | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/barcode.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/barcode.py | MIT |
def datamatrix(data: str, **kwargs) -> str:
"""Render a DataMatrix barcode.
Arguments:
data: Data to encode
Keyword Arguments:
fill_color (str): Foreground color (default = 'black')
back_color (str): Background color (default = 'white')
scale (float): Matrix scaling factor ... | Render a DataMatrix barcode.
Arguments:
data: Data to encode
Keyword Arguments:
fill_color (str): Foreground color (default = 'black')
back_color (str): Background color (default = 'white')
scale (float): Matrix scaling factor (default = 1)
border (int): Border width (d... | datamatrix | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/barcode.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/barcode.py | MIT |
def filter_queryset(queryset: QuerySet, **kwargs) -> QuerySet:
"""Filter a database queryset based on the provided keyword arguments.
Arguments:
queryset: The queryset to filter
Keyword Arguments:
field (any): Filter the queryset based on the provided field
Example:
{% filter_... | Filter a database queryset based on the provided keyword arguments.
Arguments:
queryset: The queryset to filter
Keyword Arguments:
field (any): Filter the queryset based on the provided field
Example:
{% filter_queryset companies is_supplier=True as suppliers %}
| filter_queryset | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def filter_db_model(model_name: str, **kwargs) -> QuerySet:
"""Filter a database model based on the provided keyword arguments.
Arguments:
model_name: The name of the Django model - including app name (e.g. 'part.partcategory')
Keyword Arguments:
field (any): Filter the queryset based on t... | Filter a database model based on the provided keyword arguments.
Arguments:
model_name: The name of the Django model - including app name (e.g. 'part.partcategory')
Keyword Arguments:
field (any): Filter the queryset based on the provided field
Example:
{% filter_db_model 'part.pa... | filter_db_model | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def asset(filename):
"""Return fully-qualified path for an upload report asset file.
Arguments:
filename: Asset filename (relative to the 'assets' media directory)
Raises:
FileNotFoundError: If file does not exist
"""
if type(filename) is SafeString:
# Prepend an empty stri... | Return fully-qualified path for an upload report asset file.
Arguments:
filename: Asset filename (relative to the 'assets' media directory)
Raises:
FileNotFoundError: If file does not exist
| asset | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def uploaded_image(
filename: str,
replace_missing: bool = True,
replacement_file: str = 'blank_image.png',
validate: bool = True,
width: Optional[int] = None,
height: Optional[int] = None,
rotate: Optional[float] = None,
**kwargs,
) -> str:
"""Return raw image data from an 'uploaded... | Return raw image data from an 'uploaded' image.
Arguments:
filename: The filename of the image relative to the MEDIA_ROOT directory
replace_missing: Optionally return a placeholder image if the provided filename does not exist (default = True)
replacement_file: The filename of the placehold... | uploaded_image | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def encode_svg_image(filename: str) -> str:
"""Return a base64-encoded svg image data string."""
if type(filename) is SafeString:
# Prepend an empty string to enforce 'stringiness'
filename = '' + filename
# Check if the file exists
if not filename:
exists = False
else:
... | Return a base64-encoded svg image data string. | encode_svg_image | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def part_image(part: Part, preview: bool = False, thumbnail: bool = False, **kwargs):
"""Return a fully-qualified path for a part image.
Arguments:
part: A Part model instance
preview: Return the preview image (default = False)
thumbnail: Return the thumbnail image (default = False)
... | Return a fully-qualified path for a part image.
Arguments:
part: A Part model instance
preview: Return the preview image (default = False)
thumbnail: Return the thumbnail image (default = False)
Raises:
TypeError: If provided part is not a Part instance
| part_image | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def part_parameter(part: Part, parameter_name: str) -> str:
"""Return a PartParameter object for the given part and parameter name.
Arguments:
part: A Part object
parameter_name: The name of the parameter to retrieve
Returns:
A PartParameter object, or None if not found
"""
... | Return a PartParameter object for the given part and parameter name.
Arguments:
part: A Part object
parameter_name: The name of the parameter to retrieve
Returns:
A PartParameter object, or None if not found
| part_parameter | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def company_image(
company: Company, preview: bool = False, thumbnail: bool = False, **kwargs
) -> str:
"""Return a fully-qualified path for a company image.
Arguments:
company: A Company model instance
preview: Return the preview image (default = False)
thumbnail: Return the thumbn... | Return a fully-qualified path for a company image.
Arguments:
company: A Company model instance
preview: Return the preview image (default = False)
thumbnail: Return the thumbnail image (default = False)
Raises:
TypeError: If provided company is not a Company instance
| company_image | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def logo_image(**kwargs) -> str:
"""Return a fully-qualified path for the logo image.
- If a custom logo has been provided, return a path to that logo
- Otherwise, return a path to the default InvenTree logo
"""
# If in debug mode, return URL to the image, not a local file
debug_mode = get_glob... | Return a fully-qualified path for the logo image.
- If a custom logo has been provided, return a path to that logo
- Otherwise, return a path to the default InvenTree logo
| logo_image | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def internal_link(link, text) -> str:
"""Make a <a></a> href which points to an InvenTree URL.
Uses the InvenTree.helpers_model.construct_absolute_url function to build the URL.
"""
text = str(text)
try:
url = InvenTree.helpers_model.construct_absolute_url(link)
except Exception:
... | Make a <a></a> href which points to an InvenTree URL.
Uses the InvenTree.helpers_model.construct_absolute_url function to build the URL.
| internal_link | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def render_html_text(text: str, **kwargs):
"""Render a text item with some simple html tags.
kwargs:
bold: Boolean, whether bold (or not)
italic: Boolean, whether italic (or not)
heading: str, heading level e.g. 'h3'
"""
tags = []
if kwargs.get('bold'):
tags.append(... | Render a text item with some simple html tags.
kwargs:
bold: Boolean, whether bold (or not)
italic: Boolean, whether italic (or not)
heading: str, heading level e.g. 'h3'
| render_html_text | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def format_number(
number: Union[int, float, Decimal],
decimal_places: Optional[int] = None,
integer: bool = False,
leading: int = 0,
separator: Optional[str] = None,
) -> str:
"""Render a number with optional formatting options.
Arguments:
number: The number to be formatted
... | Render a number with optional formatting options.
Arguments:
number: The number to be formatted
decimal_places: Number of decimal places to render
integer: Boolean, whether to render the number as an integer
leading: Number of leading zeros (default = 0)
separator: Character... | format_number | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def format_datetime(
dt: datetime, timezone: Optional[str] = None, fmt: Optional[str] = None
):
"""Format a datetime object for display.
Arguments:
dt: The datetime object to format
timezone: The timezone to use for the date (defaults to the server timezone)
fmt: The format string t... | Format a datetime object for display.
Arguments:
dt: The datetime object to format
timezone: The timezone to use for the date (defaults to the server timezone)
fmt: The format string to use (defaults to ISO formatting)
| format_datetime | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def format_date(dt: date, timezone: Optional[str] = None, fmt: Optional[str] = None):
"""Format a date object for display.
Arguments:
dt: The date to format
timezone: The timezone to use for the date (defaults to the server timezone)
fmt: The format string to use (defaults to ISO format... | Format a date object for display.
Arguments:
dt: The date to format
timezone: The timezone to use for the date (defaults to the server timezone)
fmt: The format string to use (defaults to ISO formatting)
| format_date | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def icon(name, **kwargs):
"""Render an icon from the icon packs.
Arguments:
name: The name of the icon to render
Keyword Arguments:
class: Optional class name(s) to apply to the icon element
"""
if not name:
return ''
try:
pack, icon, variant = common.icons.val... | Render an icon from the icon packs.
Arguments:
name: The name of the icon to render
Keyword Arguments:
class: Optional class name(s) to apply to the icon element
| icon | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def include_icon_fonts(ttf: bool = False, woff: bool = False):
"""Return the CSS font-face rule for the icon fonts used on the current page (or all)."""
fonts = []
if not ttf and not woff:
ttf = woff = True
for font in common.icons.get_icon_packs().values():
# generate the font src str... | Return the CSS font-face rule for the icon fonts used on the current page (or all). | include_icon_fonts | python | inventree/InvenTree | src/backend/InvenTree/report/templatetags/report.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templatetags/report.py | MIT |
def get_queryset(self, request):
"""Annotate queryset to fetch location count."""
return (
super()
.get_queryset(request)
.annotate(location_count=Count('stock_locations'))
) | Annotate queryset to fetch location count. | get_queryset | python | inventree/InvenTree | src/backend/InvenTree/stock/admin.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/admin.py | MIT |
def filter_has_location_type(self, queryset, name, value):
"""Filter by whether or not the location has a location type."""
if str2bool(value):
return queryset.exclude(location_type=None)
return queryset.filter(location_type=None) | Filter by whether or not the location has a location type. | filter_has_location_type | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def filter_cascade(self, queryset, name, value):
"""Filter by whether to include sub-locations in the filtered results.
Note: If the "parent" filter is provided, we offload the logic to that method.
"""
parent = self.data.get('parent', None)
top_level = str2bool(self.data.get('t... | Filter by whether to include sub-locations in the filtered results.
Note: If the "parent" filter is provided, we offload the logic to that method.
| filter_cascade | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def filter_parent(self, queryset, name, value):
"""Filter by parent location.
Note that the filtering behavior here varies,
depending on whether the 'cascade' value is set.
So, we have to check the "cascade" value here.
"""
parent = value
depth = self.data.get('... | Filter by parent location.
Note that the filtering behavior here varies,
depending on whether the 'cascade' value is set.
So, we have to check the "cascade" value here.
| filter_parent | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def get_queryset(self, *args, **kwargs):
"""Return annotated queryset for the StockLocationList endpoint."""
queryset = super().get_queryset(*args, **kwargs)
queryset = StockSerializers.LocationSerializer.annotate_queryset(queryset)
return queryset | Return annotated queryset for the StockLocationList endpoint. | get_queryset | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def destroy(self, request, *args, **kwargs):
"""Delete a Stock location instance via the API."""
delete_stock_items = str(request.data.get('delete_stock_items', 0)) == '1'
delete_sub_locations = str(request.data.get('delete_sub_locations', 0)) == '1'
return super().destroy(
... | Delete a Stock location instance via the API. | destroy | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def get_queryset(self, *args, **kwargs):
"""Return annotated queryset for the StockLocationTree endpoint."""
queryset = super().get_queryset(*args, **kwargs)
queryset = StockSerializers.LocationTreeSerializer.annotate_queryset(queryset)
return queryset | Return annotated queryset for the StockLocationTree endpoint. | get_queryset | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def get_queryset(self):
"""Override the queryset method to include location count."""
queryset = super().get_queryset()
queryset = StockSerializers.StockLocationTypeSerializer.annotate_queryset(
queryset
)
return queryset | Override the queryset method to include location count. | get_queryset | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def filter_part(self, queryset, name, part):
"""Filter StockItem list by provided Part instance.
Note:
- If "part" is a variant, include all variants of the selected part
- Otherwise, filter by the selected part
"""
include_variants = str2bool(self.data.get('include_vari... | Filter StockItem list by provided Part instance.
Note:
- If "part" is a variant, include all variants of the selected part
- Otherwise, filter by the selected part
| filter_part | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def filter_allocated(self, queryset, name, value):
"""Filter by whether or not the stock item is 'allocated'."""
if str2bool(value):
# Filter StockItem with either build allocations or sales order allocations
return queryset.filter(
Q(sales_order_allocations__isnu... | Filter by whether or not the stock item is 'allocated'. | filter_allocated | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def filter_expired(self, queryset, name, value):
"""Filter by whether or not the stock item has expired."""
if not common.settings.stock_expiry_enabled():
return queryset
if str2bool(value):
return queryset.filter(StockItem.EXPIRED_FILTER)
return queryset.exclude... | Filter by whether or not the stock item has expired. | filter_expired | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def filter_external(self, queryset, name, value):
"""Filter by whether or not the stock item is located in an external location."""
if str2bool(value):
return queryset.filter(location__external=True)
return queryset.exclude(location__external=True) | Filter by whether or not the stock item is located in an external location. | filter_external | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def filter_in_stock(self, queryset, name, value):
"""Filter by if item is in stock."""
if str2bool(value):
return queryset.filter(StockItem.IN_STOCK_FILTER)
return queryset.exclude(StockItem.IN_STOCK_FILTER) | Filter by if item is in stock. | filter_in_stock | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
def filter_available(self, queryset, name, value):
"""Filter by whether the StockItem is "available" or not.
Here, "available" means that the allocated quantity is less than the total quantity
"""
if str2bool(value):
# The 'quantity' field is greater than the calculated 'all... | Filter by whether the StockItem is "available" or not.
Here, "available" means that the allocated quantity is less than the total quantity
| filter_available | python | inventree/InvenTree | src/backend/InvenTree/stock/api.py | https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/stock/api.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.