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 generate_schema_file(key: str) -> None: """Generate a schema file for the provided key.""" description = SPECIAL_PATHS.get(key, 'General API Endpoints') output = f""" --- title: {description} --- The *{description}* section of the InvenTree API schema is documented below. [OAD(./d...
Generate a schema file for the provided key.
generate_schema_file
python
inventree/InvenTree
docs/extract_schema.py
https://github.com/inventree/InvenTree/blob/master/docs/extract_schema.py
MIT
def generate_index_file(version: str): """Generate the index file for the API schema.""" output = f""" --- title: InvenTree API Schema --- The InvenTree API is implemented using the [Django REST framework](https://www.django-rest-framework.org). The API schema as documented below is generat...
Generate the index file for the API schema.
generate_index_file
python
inventree/InvenTree
docs/extract_schema.py
https://github.com/inventree/InvenTree/blob/master/docs/extract_schema.py
MIT
def extract_refs(data: dict, components: dict) -> dict: """Extract a dict of refs from the provided paths dict. The refs are located like so: <path>:<method>:responses:<status>:content:application/json:schema:$ref Also, the referenced components might reference *sub* components, so we need to do t...
Extract a dict of refs from the provided paths dict. The refs are located like so: <path>:<method>:responses:<status>:content:application/json:schema:$ref Also, the referenced components might reference *sub* components, so we need to do this step recursively.
extract_refs
python
inventree/InvenTree
docs/extract_schema.py
https://github.com/inventree/InvenTree/blob/master/docs/extract_schema.py
MIT
def parse_api_file(filename: str): """Parse the input API file, and split into smaller sections. The intent is to make the API schema easier to peruse on the documentation. """ with open(filename, encoding='utf-8') as f: data = yaml.safe_load(f) paths = data['paths'] top_level_paths =...
Parse the input API file, and split into smaller sections. The intent is to make the API schema easier to peruse on the documentation.
parse_api_file
python
inventree/InvenTree
docs/extract_schema.py
https://github.com/inventree/InvenTree/blob/master/docs/extract_schema.py
MIT
def get_repo_url(raw=False): """Return the repository URL for the current project.""" mkdocs_yml = here.joinpath('mkdocs.yml') with open(mkdocs_yml, encoding='utf-8') as f: mkdocs_config = yaml.safe_load(f) repo_name = mkdocs_config['repo_name'] if raw: return f'https://raw.git...
Return the repository URL for the current project.
get_repo_url
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def check_link(url) -> bool: """Check that a provided URL is valid. We allow a number attempts and a lengthy timeout, as we do not want false negatives. """ CACHE_FILE = gen_base.joinpath('url_cache.txt') # Keep a local cache file of URLs we have already checked if CACHE_FILE.exists(): ...
Check that a provided URL is valid. We allow a number attempts and a lengthy timeout, as we do not want false negatives.
check_link
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def get_build_environment() -> str: """Returns the branch we are currently building on, based on the environment variables of the various CI platforms.""" # Check if we are in ReadTheDocs if os.environ.get('READTHEDOCS') == 'True': for var in ['READTHEDOCS_GIT_COMMIT_HASH', 'READTHEDOCS_GIT_IDENTIFI...
Returns the branch we are currently building on, based on the environment variables of the various CI platforms.
get_build_environment
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def define_env(env): """Define custom environment variables for the documentation build process.""" config = env.config assets_dir = config.get('assets_dir', None) if assets_dir is None: # Construct the assets directory based on the current build environment rtd_version = os.environ.get...
Define custom environment variables for the documentation build process.
define_env
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def sourcedir(dirname: str, branch=None): """Return a link to a directory within the source code repository. Arguments: dirname: The name of the directory to link to (relative to the top-level directory) branch: The branch of the repository to link to (defaults to the current bu...
Return a link to a directory within the source code repository. Arguments: dirname: The name of the directory to link to (relative to the top-level directory) branch: The branch of the repository to link to (defaults to the current build environment) Returns: A full...
sourcedir
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def sourcefile(filename, branch=None, raw=False): """Return a link to a file within the source code repository. Arguments: filename: The name of the file to link to (relative to the top-level directory) branch: The branch of the repository to link to (defaults to the current bui...
Return a link to a file within the source code repository. Arguments: filename: The name of the file to link to (relative to the top-level directory) branch: The branch of the repository to link to (defaults to the current build environment) raw: If True, return the raw URL ...
sourcefile
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def invoke_commands(): """Provides an output of the available commands.""" tasks = here.parent.joinpath('tasks.py') output = gen_base.joinpath('invoke-commands.txt') command = f'invoke -f {tasks} --list > {output}' assert subprocess.call(command, shell=True) == 0 with ...
Provides an output of the available commands.
invoke_commands
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def listimages(subdir): """Return a listing of all asset files in the provided subdir.""" directory = here.joinpath('docs', 'assets', 'images', subdir) assets = [] allowed = ['.png', '.jpg'] for asset in directory.iterdir(): if any(str(asset).endswith(x) for x in a...
Return a listing of all asset files in the provided subdir.
listimages
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def includefile(filename: str, title: str, fmt: str = ''): """Include a file in the documentation, in a 'collapse' block. Arguments: filename: The name of the file to include (relative to the top-level directory) title: The title of the collapse block in the documentation ...
Include a file in the documentation, in a 'collapse' block. Arguments: filename: The name of the file to include (relative to the top-level directory) title: The title of the collapse block in the documentation fmt: The format of the included file (e.g., 'python', 'html', et...
includefile
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def templatefile(filename): """Include code for a provided template file.""" base = Path(filename).name fn = Path('src', 'backend', 'InvenTree', 'report', 'templates', filename) return includefile(fn, f'Template: {base}', fmt='html')
Include code for a provided template file.
templatefile
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def observe_setting(key: str, group: str): """Record that a particular setting has been observed. This is used to ensure that all settings are documented in the generated documentation. Arguments: key: The name of the setting to observe group: The group of the setting (...
Record that a particular setting has been observed. This is used to ensure that all settings are documented in the generated documentation. Arguments: key: The name of the setting to observe group: The group of the setting (e.g. 'global', 'user')
observe_setting
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def rendersetting(key: str, setting: dict): """Render a provided setting object into a table row.""" name = setting['name'] description = setting['description'] default = setting.get('default') units = setting.get('units') default = f'`{default}`' if default else '' ...
Render a provided setting object into a table row.
rendersetting
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def globalsetting(key: str): """Extract information on a particular global setting. Arguments: key: The name of the global setting to extract information for. """ global GLOBAL_SETTINGS setting = GLOBAL_SETTINGS[key] observe_setting(key, 'global') r...
Extract information on a particular global setting. Arguments: key: The name of the global setting to extract information for.
globalsetting
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def usersetting(key: str): """Extract information on a particular user setting. Arguments: key: The name of the user setting to extract information for. """ global USER_SETTINGS setting = USER_SETTINGS[key] observe_setting(key, 'user') return render...
Extract information on a particular user setting. Arguments: key: The name of the user setting to extract information for.
usersetting
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def tags_and_filters(): """Return a list of all tags and filters.""" global TAGS global FILTERS ret_data = '' for ref in [['Tags', TAGS], ['Filters', FILTERS]]: ret_data += f'### {ref[0]}\n\n| Namespace | Name | Description |\n| --- | --- | --- |\n' for v...
Return a list of all tags and filters.
tags_and_filters
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def report_context(type_: Literal['models', 'base'], model: str): """Extract information on a particular report context.""" global REPORT_CONTEXT context = REPORT_CONTEXT.get(type_).get(model) ret_data = '| Variable | Type | Description |\n| --- | --- | --- |\n' for k, v in con...
Extract information on a particular report context.
report_context
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def icon( source: str, size: str = '20px', color: Optional[str] = None, title: Optional[str] = None, ): """Return a tabler icon for a given source. Arguments: source: The name of the icon to display (e.g. 'check', 'cross', etc.) size: The size...
Return a tabler icon for a given source. Arguments: source: The name of the icon to display (e.g. 'check', 'cross', etc.) size: The size of the icon (default: 20px) color: The color of the icon (default: None) title: The title of the icon (default: None) ...
icon
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def image( source: str, title: Optional[str] = '', iid: Optional[str] = '', alt: Optional[str] = '', base: Optional[str] = '', maxwidth: Optional[str] = '', maxheight: Optional[str] = '', ): """Render an image within the documentation. Argumen...
Render an image within the documentation. Arguments: title: The title of the image (default: '') source: The name of the image to display (e.g. 'check', 'cross', etc.) iid: The ID of the image (default: '') alt: The alt text for the image (default: '') ...
image
python
inventree/InvenTree
docs/main.py
https://github.com/inventree/InvenTree/blob/master/docs/main.py
MIT
def fetch_rtd_versions(): """Get a list of RTD docs versions to build the version selector.""" print('Fetching documentation versions from ReadTheDocs') versions = [] def make_request(url, headers): """Make a single request to the RTD API.""" response = requests.get(url, headers=header...
Get a list of RTD docs versions to build the version selector.
fetch_rtd_versions
python
inventree/InvenTree
docs/docs/hooks.py
https://github.com/inventree/InvenTree/blob/master/docs/docs/hooks.py
MIT
def make_request(url, headers): """Make a single request to the RTD API.""" response = requests.get(url, headers=headers) if response.status_code != 200: print(f'Error fetching RTD versions: {response.status_code}') return data = json.loads(response.text) ...
Make a single request to the RTD API.
make_request
python
inventree/InvenTree
docs/docs/hooks.py
https://github.com/inventree/InvenTree/blob/master/docs/docs/hooks.py
MIT
def get_release_data(): """Return InvenTree release information. - First look to see if 'releases.json' file exists - If data does not exist in this file, request via the github API """ json_file = here.parent.joinpath('generated', 'releases.json') releases = [] if json_file.exists(): ...
Return InvenTree release information. - First look to see if 'releases.json' file exists - If data does not exist in this file, request via the github API
get_release_data
python
inventree/InvenTree
docs/docs/hooks.py
https://github.com/inventree/InvenTree/blob/master/docs/docs/hooks.py
MIT
def on_config(config, *args, **kwargs): """Run when the mkdocs config is loaded. We want to be able to provide a *dynamic* config.site_url parameter to mkdocs, which tells it the base url, e.g. - https://readthedocs.io/en/latest - https://readthedocs.io/de/0.5.1 Further, we need to know if we...
Run when the mkdocs config is loaded. We want to be able to provide a *dynamic* config.site_url parameter to mkdocs, which tells it the base url, e.g. - https://readthedocs.io/en/latest - https://readthedocs.io/de/0.5.1 Further, we need to know if we are building on readthedocs at all! readt...
on_config
python
inventree/InvenTree
docs/docs/hooks.py
https://github.com/inventree/InvenTree/blob/master/docs/docs/hooks.py
MIT
def on_post_build(*args, **kwargs): """Run after the build is complete. Here we check that all global settings and user settings are documented. """ here = Path(__file__).parent gen_base = here.parent.joinpath('generated') expected_settings_file = gen_base.joinpath('inventree_settings.json') ...
Run after the build is complete. Here we check that all global settings and user settings are documented.
on_post_build
python
inventree/InvenTree
docs/docs/hooks.py
https://github.com/inventree/InvenTree/blob/master/docs/docs/hooks.py
MIT
def filter_status(self, queryset, name, value): """Filter by integer status code. Note: Also account for the possibility of a custom status code """ q1 = Q(status=value, status_custom_key__isnull=True) q2 = Q(status_custom_key=value) return queryset.filter(q1 | q2).dist...
Filter by integer status code. Note: Also account for the possibility of a custom status code
filter_status
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_active(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are active.""" if str2bool(value): return queryset.filter(status__in=BuildStatusGroups.ACTIVE_CODES) return queryset.exclude(status__in=BuildStatusGroups.ACTIVE_CODES)
Filter the queryset to either include or exclude orders which are active.
filter_active
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_part(self, queryset, name, part): """Filter by 'part' which is being built. Note: - If "include_variants" is True, include all variants of the selected part. - Otherwise, just filter by the selected part. """ include_variants = str2bool(self.data.get('include_...
Filter by 'part' which is being built. Note: - If "include_variants" is True, include all variants of the selected part. - Otherwise, just filter by the selected part.
filter_part
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_overdue(self, queryset, name, value): """Filter the queryset to either include or exclude orders which are overdue.""" if str2bool(value): return queryset.filter(Build.OVERDUE_FILTER) return queryset.exclude(Build.OVERDUE_FILTER)
Filter the queryset to either include or exclude orders which are overdue.
filter_overdue
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_assigned_to_me(self, queryset, name, value): """Filter by orders which are assigned to the current user.""" value = str2bool(value) # Work out who "me" is! owners = Owner.get_owners_matching_user(self.request.user) if value: return queryset.filter(respons...
Filter by orders which are assigned to the current user.
filter_assigned_to_me
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_issued_by(self, queryset, name, owner): """Filter by 'owner' which issued the order.""" if owner.label() == 'user': user = User.objects.get(pk=owner.owner_id) return queryset.filter(issued_by=user) elif owner.label() == 'group': group = User.objects...
Filter by 'owner' which issued the order.
filter_issued_by
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_responsible(self, queryset, name, owner): """Filter by orders which are assigned to the specified owner.""" owners = list(Owner.objects.filter(pk=owner)) # if we query by a user, also find all ownerships through group memberships if len(owners) > 0 and owners[0].label() == 'u...
Filter by orders which are assigned to the specified owner.
filter_responsible
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_has_project_code(self, queryset, name, value): """Filter by whether or not the order has a project code.""" if str2bool(value): return queryset.exclude(project_code=None) return queryset.filter(project_code=None)
Filter by whether or not the order has a project code.
filter_has_project_code
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_min_date(self, queryset, name, value): """Filter the queryset to include orders *after* a specified date. This filter is used in combination with filter_max_date, to provide a queryset which matches a particular range of dates. In particular, this is used in the UI for the c...
Filter the queryset to include orders *after* a specified date. This filter is used in combination with filter_max_date, to provide a queryset which matches a particular range of dates. In particular, this is used in the UI for the calendar view. So, we are interested in orders which ...
filter_min_date
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_max_date(self, queryset, name, value): """Filter the queryset to include orders *before* a specified date. This filter is used in combination with filter_min_date, to provide a queryset which matches a particular range of dates. In particular, this is used in the UI for the ...
Filter the queryset to include orders *before* a specified date. This filter is used in combination with filter_min_date, to provide a queryset which matches a particular range of dates. In particular, this is used in the UI for the calendar view. So, we are interested in orders which...
filter_max_date
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_exclude_tree(self, queryset, name, value): """Filter by excluding a tree of Build objects.""" queryset = queryset.exclude( pk__in=[bld.pk for bld in value.get_descendants(include_self=True)] ) return queryset
Filter by excluding a tree of Build objects.
filter_exclude_tree
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_queryset(self): """Return the queryset for the Build API endpoints.""" queryset = super().get_queryset() queryset = queryset.prefetch_related( 'responsible', 'issued_by', 'build_lines', 'build_lines__bom_item', 'build_lines__bu...
Return the queryset for the Build API endpoints.
get_queryset
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_queryset(self): """Override the queryset filtering, as some of the fields don't natively play nicely with DRF.""" queryset = super().get_queryset().select_related('part') queryset = build.serializers.BuildSerializer.annotate_queryset(queryset) return queryset
Override the queryset filtering, as some of the fields don't natively play nicely with DRF.
get_queryset
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_serializer(self, *args, **kwargs): """Add extra context information to the endpoint serializer.""" try: part_detail = str2bool(self.request.GET.get('part_detail', True)) except AttributeError: part_detail = True kwargs['part_detail'] = part_detail ...
Add extra context information to the endpoint serializer.
get_serializer
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def destroy(self, request, *args, **kwargs): """Only allow deletion of a BuildOrder if the build status is CANCELLED.""" build = self.get_object() if build.status != BuildStatus.CANCELLED: raise ValidationError({ 'non_field_errors': [ _('Build mus...
Only allow deletion of a BuildOrder if the build status is CANCELLED.
destroy
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_order_outstanding(self, queryset, name, value): """Filter by whether the associated BuildOrder is 'outstanding'.""" if str2bool(value): return queryset.filter(build__status__in=BuildStatusGroups.ACTIVE_CODES) return queryset.exclude(build__status__in=BuildStatusGroups.ACTI...
Filter by whether the associated BuildOrder is 'outstanding'.
filter_order_outstanding
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_allocated(self, queryset, name, value): """Filter by whether each BuildLine is fully allocated.""" if str2bool(value): return queryset.filter(allocated__gte=F('quantity')) return queryset.filter(allocated__lt=F('quantity'))
Filter by whether each BuildLine is fully allocated.
filter_allocated
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_available(self, queryset, name, value): """Filter by whether there is sufficient stock available for each BuildLine. To determine this, we need to know: - The quantity required for each BuildLine - The quantity available for each BuildLine (including variants and substitutes...
Filter by whether there is sufficient stock available for each BuildLine. To determine this, we need to know: - The quantity required for each BuildLine - The quantity available for each BuildLine (including variants and substitutes) - The quantity allocated for each BuildLine
filter_available
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_serializer(self, *args, **kwargs): """Return the serializer instance for this endpoint.""" kwargs['context'] = self.get_serializer_context() try: params = self.request.query_params kwargs['part_detail'] = str2bool(params.get('part_detail', True)) kwa...
Return the serializer instance for this endpoint.
get_serializer
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_source_build(self) -> Build: """Return the source Build object for the BuildLine queryset. This source build is used to filter the available stock for each BuildLine. - If this is a "detail" view, use the build associated with the line - If this is a "list" view, use the build ...
Return the source Build object for the BuildLine queryset. This source build is used to filter the available stock for each BuildLine. - If this is a "detail" view, use the build associated with the line - If this is a "list" view, use the build associated with the request
get_source_build
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_queryset(self): """Override queryset to select-related and annotate.""" queryset = super().get_queryset() if not hasattr(self, 'source_build'): self.source_build = self.get_source_build() source_build = self.source_build return build.serializers.BuildLineSe...
Override queryset to select-related and annotate.
get_queryset
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_source_build(self) -> Build | None: """Return the target build for the BuildLine queryset.""" source_build = None try: build_id = self.request.query_params.get('build', None) if build_id: source_build = Build.objects.filter(pk=build_id).first() ...
Return the target build for the BuildLine queryset.
get_source_build
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_queryset(self): """Return the queryset for the BuildFinish API endpoint.""" queryset = super().get_queryset() queryset = queryset.prefetch_related('build_lines', 'build_lines__allocations') return queryset
Return the queryset for the BuildFinish API endpoint.
get_queryset
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_tracked(self, queryset, name, value): """Filter the queryset based on whether build items are tracked.""" if str2bool(value): return queryset.exclude(install_into=None) return queryset.filter(install_into=None)
Filter the queryset based on whether build items are tracked.
filter_tracked
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_serializer(self, *args, **kwargs): """Returns a BuildItemSerializer instance based on the request.""" try: params = self.request.query_params for key in [ 'part_detail', 'location_detail', 'stock_detail', 'b...
Returns a BuildItemSerializer instance based on the request.
get_serializer
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def get_queryset(self): """Override the queryset method, to perform custom prefetch.""" queryset = super().get_queryset() queryset = queryset.select_related( 'build_line', 'build_line__build', 'build_line__bom_item', 'build_line__bom_item__part', ...
Override the queryset method, to perform custom prefetch.
get_queryset
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def filter_queryset(self, queryset): """Custom query filtering for the BuildItem list.""" queryset = super().filter_queryset(queryset) params = self.request.query_params # Filter by output target output = params.get('output', None) if output: if isNull(outp...
Custom query filtering for the BuildItem list.
filter_queryset
python
inventree/InvenTree
src/backend/InvenTree/build/api.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/api.py
MIT
def annotate_allocated_quantity(queryset: Q) -> Q: """Annotate the 'allocated' quantity for each build item in the queryset. Arguments: queryset: The BuildLine queryset to annotate """ queryset = queryset.prefetch_related('allocations') return queryset.annotate( allocated=Coalesce...
Annotate the 'allocated' quantity for each build item in the queryset. Arguments: queryset: The BuildLine queryset to annotate
annotate_allocated_quantity
python
inventree/InvenTree
src/backend/InvenTree/build/filters.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/filters.py
MIT
def api_defaults(cls, request=None): """Return default values for this model when issuing an API OPTIONS request.""" defaults = {'reference': generate_next_build_reference()} if request and request.user: defaults['issued_by'] = request.user.pk return defaults
Return default values for this model when issuing an API OPTIONS request.
api_defaults
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def save(self, *args, **kwargs): """Custom save method for the BuildOrder model.""" self.reference_int = self.validate_reference_field(self.reference) # Check part when initially creating the build order if not self.pk or self.has_field_changed('part'): if get_global_setting...
Custom save method for the BuildOrder model.
save
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def sub_builds(self, cascade=True): """Return all Build Order objects under this one.""" if cascade: return self.get_descendants(include_self=False) else: return self.get_children()
Return all Build Order objects under this one.
sub_builds
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def is_overdue(self): """Returns true if this build is "overdue". Makes use of the OVERDUE_FILTER to avoid code duplication Returns: bool: Is the build overdue """ query = Build.objects.filter(pk=self.pk) query = query.filter(Build.OVERDUE_FILTER) r...
Returns true if this build is "overdue". Makes use of the OVERDUE_FILTER to avoid code duplication Returns: bool: Is the build overdue
is_overdue
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def get_build_outputs(self, **kwargs): """Return a list of build outputs. kwargs: complete = (True / False) - If supplied, filter by completed status in_stock = (True / False) - If supplied, filter by 'in-stock' status """ outputs = self.build_outputs.all() ...
Return a list of build outputs. kwargs: complete = (True / False) - If supplied, filter by completed status in_stock = (True / False) - If supplied, filter by 'in-stock' status
get_build_outputs
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def complete_count(self): """Return the total quantity of completed outputs.""" quantity = 0 for output in self.complete_outputs: quantity += output.quantity return quantity
Return the total quantity of completed outputs.
complete_count
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def incomplete_count(self): """Return the total number of "incomplete" outputs.""" quantity = 0 for output in self.incomplete_outputs: quantity += output.quantity return quantity
Return the total number of "incomplete" outputs.
incomplete_count
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def getNextBuildNumber(cls): """Try to predict the next Build Order reference.""" if cls.objects.count() == 0: return None # Extract the "most recent" build order reference builds = cls.objects.exclude(reference=None) if not builds.exists(): return None ...
Try to predict the next Build Order reference.
getNextBuildNumber
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def can_complete(self): """Returns True if this BuildOrder is ready to be completed. - Must not have any outstanding build outputs - Completed count must meet the required quantity - Untracked parts must be allocated """ if ( get_global_setting('BUILDORDER_RE...
Returns True if this BuildOrder is ready to be completed. - Must not have any outstanding build outputs - Completed count must meet the required quantity - Untracked parts must be allocated
can_complete
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def complete_allocations(self, user): """Complete all stock allocations for this build order. - This function is called when a build order is completed """ # Remove untracked allocated stock self.subtract_allocated_stock(user) # Ensure that there are no longer any Build...
Complete all stock allocations for this build order. - This function is called when a build order is completed
complete_allocations
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def complete_build(self, user: User, trim_allocated_stock: bool = False): """Mark this build as complete. Arguments: user: The user who is completing the build trim_allocated_stock: If True, trim any allocated stock """ return self.handle_transition( ...
Mark this build as complete. Arguments: user: The user who is completing the build trim_allocated_stock: If True, trim any allocated stock
complete_build
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def _action_complete(self, *args, **kwargs): """Action to be taken when a build is completed.""" import build.tasks trim_allocated_stock = kwargs.pop('trim_allocated_stock', False) user = kwargs.pop('user', None) # Prevent completion if there are open child builds if ( ...
Action to be taken when a build is completed.
_action_complete
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def issue_build(self): """Mark the Build as IN PRODUCTION. Args: user: The user who is issuing the build """ return self.handle_transition( self.status, BuildStatus.PENDING.value, self, self._action_issue )
Mark the Build as IN PRODUCTION. Args: user: The user who is issuing the build
issue_build
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def _action_issue(self, *args, **kwargs): """Perform the action to mark this order as PRODUCTION.""" if self.can_issue: self.status = BuildStatus.PRODUCTION.value self.save() trigger_event(BuildEvents.ISSUED, id=self.pk)
Perform the action to mark this order as PRODUCTION.
_action_issue
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def hold_build(self): """Mark the Build as ON HOLD.""" return self.handle_transition( self.status, BuildStatus.ON_HOLD.value, self, self._action_hold )
Mark the Build as ON HOLD.
hold_build
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def _action_hold(self, *args, **kwargs): """Action to be taken when a build is placed on hold.""" if self.can_hold: self.status = BuildStatus.ON_HOLD.value self.save() trigger_event(BuildEvents.HOLD, id=self.pk)
Action to be taken when a build is placed on hold.
_action_hold
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def cancel_build(self, user, **kwargs): """Mark the Build as CANCELLED. - Delete any pending BuildItem objects (but do not remove items from stock) - Set build status to CANCELLED - Save the Build object """ return self.handle_transition( self.status, ...
Mark the Build as CANCELLED. - Delete any pending BuildItem objects (but do not remove items from stock) - Set build status to CANCELLED - Save the Build object
cancel_build
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def _action_cancel(self, *args, **kwargs): """Action to be taken when a build is cancelled.""" import build.tasks user = kwargs.pop('user', None) remove_allocated_stock = kwargs.get('remove_allocated_stock', False) remove_incomplete_outputs = kwargs.get('remove_incomplete_outpu...
Action to be taken when a build is cancelled.
_action_cancel
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def deallocate_stock(self, build_line=None, output=None): """Deallocate stock from this Build. Args: build_line: Specify a particular BuildLine instance to un-allocate stock against output: Specify a particular StockItem (output) to un-allocate stock against """ ...
Deallocate stock from this Build. Args: build_line: Specify a particular BuildLine instance to un-allocate stock against output: Specify a particular StockItem (output) to un-allocate stock against
deallocate_stock
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def create_build_output(self, quantity, **kwargs): """Create a new build output against this BuildOrder. Args: quantity: The quantity of the item to produce Kwargs: batch: Override batch code serials: Serial numbers location: Override location ...
Create a new build output against this BuildOrder. Args: quantity: The quantity of the item to produce Kwargs: batch: Override batch code serials: Serial numbers location: Override location auto_allocate: Automatically allocate stock with mat...
create_build_output
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def delete_output(self, output): """Remove a build output from the database. Executes: - Deallocate any build items against the output - Delete the output StockItem """ if not output: raise ValidationError(_('No build output specified')) if not outpu...
Remove a build output from the database. Executes: - Deallocate any build items against the output - Delete the output StockItem
delete_output
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def trim_allocated_stock(self): """Called after save to reduce allocated stock if the build order is now overallocated.""" # Only need to worry about untracked stock here items_to_save = [] items_to_delete = [] lines = self.untracked_line_items.all() lines = lines.exclu...
Called after save to reduce allocated stock if the build order is now overallocated.
trim_allocated_stock
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def subtract_allocated_stock(self, user): """Called when the Build is marked as "complete", this function removes the allocated untracked items from stock.""" # Find all BuildItem objects which point to this build items = self.allocated_stock.filter( build_line__bom_item__sub_part__t...
Called when the Build is marked as "complete", this function removes the allocated untracked items from stock.
subtract_allocated_stock
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def scrap_build_output(self, output, quantity, location, **kwargs): """Mark a particular build output as scrapped / rejected. - Mark the output as "complete" - *Do Not* update the "completed" count for this order - Set the item status to "scrapped" - Add a transaction entry to t...
Mark a particular build output as scrapped / rejected. - Mark the output as "complete" - *Do Not* update the "completed" count for this order - Set the item status to "scrapped" - Add a transaction entry to the stock item history
scrap_build_output
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def complete_build_output(self, output, user, **kwargs): """Complete a particular build output. - Remove allocated StockItems - Mark the output as complete """ # Select the location for the build output location = kwargs.get('location', self.destination) status =...
Complete a particular build output. - Remove allocated StockItems - Mark the output as complete
complete_build_output
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def auto_allocate_stock(self, **kwargs): """Automatically allocate stock items against this build order. Following a number of 'guidelines': - Only "untracked" BOM items are considered (tracked BOM items must be manually allocated) - If a particular BOM item is already fully allocated, ...
Automatically allocate stock items against this build order. Following a number of 'guidelines': - Only "untracked" BOM items are considered (tracked BOM items must be manually allocated) - If a particular BOM item is already fully allocated, it is skipped - Extract all available stock ...
auto_allocate_stock
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def unallocated_lines(self, tracked=None): """Returns a list of BuildLine objects which have not been fully allocated.""" lines = self.build_lines.all() # Remove any 'consumable' line items lines = lines.exclude(bom_item__consumable=True) if tracked is True: lines =...
Returns a list of BuildLine objects which have not been fully allocated.
unallocated_lines
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def is_output_fully_allocated(self, output): """Determine if the specified output (StockItem) has been fully allocated for this build. Args: output: StockItem object (the "in production" output to test against) To determine if the output has been fully allocated, we need to...
Determine if the specified output (StockItem) has been fully allocated for this build. Args: output: StockItem object (the "in production" output to test against) To determine if the output has been fully allocated, we need to test all "trackable" BuildLine objects
is_output_fully_allocated
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def is_overallocated(self): """Test if the BuildOrder has been over-allocated. Returns: True if any BuildLine has been over-allocated. """ lines = self.build_lines.all().exclude(bom_item__consumable=True) lines = annotate_allocated_quantity(lines) # Find any...
Test if the BuildOrder has been over-allocated. Returns: True if any BuildLine has been over-allocated.
is_overallocated
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def create_build_line_items(self, prevent_duplicates=True): """Create BuildLine objects for each BOM line in this BuildOrder.""" lines = [] bom_items = self.part.get_bom_items() logger.info( 'Creating BuildLine objects for BuildOrder %s (%s items)', self.pk, ...
Create BuildLine objects for each BOM line in this BuildOrder.
create_build_line_items
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def update_build_line_items(self): """Rebuild required quantity field for each BuildLine object.""" lines_to_update = [] for line in self.build_lines.all(): line.quantity = line.bom_item.get_required_quantity(self.quantity) lines_to_update.append(line) BuildLine...
Rebuild required quantity field for each BuildLine object.
update_build_line_items
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def after_save_build(sender, instance: Build, created: bool, **kwargs): """Callback function to be executed after a Build instance is saved.""" # Escape if we are importing data if InvenTree.ready.isImportingData() or not InvenTree.ready.canAppAccessDatabase( allow_test=True ): return ...
Callback function to be executed after a Build instance is saved.
after_save_build
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def report_context(self) -> BuildLineReportContext: """Generate custom report context for this BuildLine object.""" return { 'allocated_quantity': self.allocated_quantity, 'allocations': self.allocations, 'bom_item': self.bom_item, 'build': self.build, ...
Generate custom report context for this BuildLine object.
report_context
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def allocated_quantity(self): """Calculate the total allocated quantity for this BuildLine.""" # Queryset containing all BuildItem objects allocated against this BuildLine allocations = self.allocations.all() allocated = allocations.aggregate( q=Coalesce(Sum('quantity'), 0, ...
Calculate the total allocated quantity for this BuildLine.
allocated_quantity
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def is_fully_allocated(self): """Return True if this BuildLine is fully allocated.""" if self.bom_item.consumable: return True return self.allocated_quantity() >= self.quantity
Return True if this BuildLine is fully allocated.
is_fully_allocated
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def clean(self): """Check validity of this BuildItem instance. The following checks are performed: - StockItem.part must be in the BOM of the Part object referenced by Build - Allocation quantity cannot exceed available quantity """ self.validate_unique() super(...
Check validity of this BuildItem instance. The following checks are performed: - StockItem.part must be in the BOM of the Part object referenced by Build - Allocation quantity cannot exceed available quantity
clean
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def complete_allocation(self, user, notes=''): """Complete the allocation of this BuildItem into the output stock item. - If the referenced part is trackable, the stock item will be *installed* into the build output - If the referenced part is *not* trackable, the stock item will be *consumed* ...
Complete the allocation of this BuildItem into the output stock item. - If the referenced part is trackable, the stock item will be *installed* into the build output - If the referenced part is *not* trackable, the stock item will be *consumed* by the build order TODO: This is quite expensive ...
complete_allocation
python
inventree/InvenTree
src/backend/InvenTree/build/models.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/models.py
MIT
def annotate_queryset(queryset): """Add custom annotations to the BuildSerializer queryset, performing database queries as efficiently as possible. The following annotated fields are added: - overdue: True if the build is outstanding *and* the completion date has past """ # Ann...
Add custom annotations to the BuildSerializer queryset, performing database queries as efficiently as possible. The following annotated fields are added: - overdue: True if the build is outstanding *and* the completion date has past
annotate_queryset
python
inventree/InvenTree
src/backend/InvenTree/build/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/serializers.py
MIT
def __init__(self, *args, **kwargs): """Determine if extra serializer fields are required.""" part_detail = kwargs.pop('part_detail', True) create = kwargs.pop('create', False) super().__init__(*args, **kwargs) if isGeneratingSchema(): return if not create:...
Determine if extra serializer fields are required.
__init__
python
inventree/InvenTree
src/backend/InvenTree/build/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/serializers.py
MIT
def validate_reference(self, reference): """Custom validation for the Build reference field.""" # Ensure the reference matches the required pattern Build.validate_reference_field(reference) return reference
Custom validation for the Build reference field.
validate_reference
python
inventree/InvenTree
src/backend/InvenTree/build/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/serializers.py
MIT
def validate_output(self, output): """Perform validation for the output (StockItem) provided to the serializer.""" build = self.context['build'] # As this serializer can be used in multiple contexts, we need to work out why we are here to_complete = self.context.get('to_complete', False...
Perform validation for the output (StockItem) provided to the serializer.
validate_output
python
inventree/InvenTree
src/backend/InvenTree/build/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/serializers.py
MIT
def validate(self, data): """Perform data validation for this serializer.""" data = super().validate(data) outputs = data.get('outputs', []) if len(outputs) == 0: raise ValidationError(_('A list of build outputs must be provided')) return data
Perform data validation for this serializer.
validate
python
inventree/InvenTree
src/backend/InvenTree/build/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/serializers.py
MIT
def save(self): """'save' the serializer to delete the build outputs.""" data = self.validated_data outputs = data.get('outputs', []) build = self.context['build'] with transaction.atomic(): for item in outputs: output = item['output'] ...
'save' the serializer to delete the build outputs.
save
python
inventree/InvenTree
src/backend/InvenTree/build/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/serializers.py
MIT
def validate(self, data): """Perform validation on the serializer data.""" super().validate(data) outputs = data.get('outputs', []) if len(outputs) == 0: raise ValidationError(_('A list of build outputs must be provided')) return data
Perform validation on the serializer data.
validate
python
inventree/InvenTree
src/backend/InvenTree/build/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/serializers.py
MIT
def save(self): """Save the serializer to scrap the build outputs.""" build = self.context['build'] request = self.context.get('request') data = self.validated_data outputs = data.get('outputs', []) # Scrap the build outputs with transaction.atomic(): ...
Save the serializer to scrap the build outputs.
save
python
inventree/InvenTree
src/backend/InvenTree/build/serializers.py
https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/build/serializers.py
MIT