diff --git a/.gitignore b/.gitignore index 8c119f2ab22c..4bc362f65320 100644 --- a/.gitignore +++ b/.gitignore @@ -108,5 +108,6 @@ src/backend/InvenTree/web/static InvenTree/web/static # Generated docs files +docs/schema.yml docs/docs/api/*.yml docs/docs/api/schema/*.yml diff --git a/docs/docs/assets/images/report/add_report_template.png b/docs/docs/assets/images/report/add_report_template.png deleted file mode 100644 index 3268a7ab26ee..000000000000 Binary files a/docs/docs/assets/images/report/add_report_template.png and /dev/null differ diff --git a/docs/docs/assets/images/report/report_template_admin.png b/docs/docs/assets/images/report/report_template_admin.png new file mode 100644 index 000000000000..58512fb5e7e9 Binary files /dev/null and b/docs/docs/assets/images/report/report_template_admin.png differ diff --git a/docs/docs/extend/plugins/action.md b/docs/docs/extend/plugins/action.md index e38bed7dc0fe..afb630aeeee7 100644 --- a/docs/docs/extend/plugins/action.md +++ b/docs/docs/extend/plugins/action.md @@ -15,4 +15,14 @@ POST { } ``` -For an example of a very simple action plugin, refer to `/src/backend/InvenTree/plugin/samples/integratoni/simpleactionplugin.py` +### Sample Plugin + +A sample action plugin is provided in the `InvenTree` source code, which can be used as a template for creating custom action plugins: + +::: plugin.samples.integration.simpleactionplugin.SimpleActionPlugin + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] diff --git a/docs/docs/extend/plugins/api.md b/docs/docs/extend/plugins/api.md index 1b9638cb62af..e478acbc0677 100644 --- a/docs/docs/extend/plugins/api.md +++ b/docs/docs/extend/plugins/api.md @@ -5,3 +5,15 @@ title: Schedule Mixin ## APICallMixin The APICallMixin class provides basic functionality for integration with an external API. + +### Sample Plugin + +The following example demonstrates how to use the `APICallMixin` class to make a simple API call: + +::: plugin.samples.integration.api_caller.SampleApiCallerPlugin + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] diff --git a/docs/docs/extend/plugins/barcode.md b/docs/docs/extend/plugins/barcode.md index 70bf6715bbe7..51f953b0cde9 100644 --- a/docs/docs/extend/plugins/barcode.md +++ b/docs/docs/extend/plugins/barcode.md @@ -2,7 +2,7 @@ title: Barcode Mixin --- -### Barcode Plugins +## Barcode Plugins InvenTree supports decoding of arbitrary barcode data via a **Barcode Plugin** interface. Barcode data POSTed to the `/api/barcode/` endpoint will be supplied to all loaded barcode plugins, and the first plugin to successfully interpret the barcode data will return a response to the client. @@ -24,7 +24,21 @@ POST { } ``` -### Example +### Builtin Plugin + +The InvenTree server includes a builtin barcode plugin which can decode QR codes generated by the server. This plugin is enabled by default. + +::: plugin.builtin.barcodes.inventree_barcode.InvenTreeInternalBarcodePlugin + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] + + +### Example Plugin + Please find below a very simple example that is executed each time a barcode is scanned. ```python diff --git a/docs/docs/extend/plugins/currency.md b/docs/docs/extend/plugins/currency.md index b96178379d9c..0237c7cddfc4 100644 --- a/docs/docs/extend/plugins/currency.md +++ b/docs/docs/extend/plugins/currency.md @@ -6,7 +6,24 @@ title: Currency Exchange Mixin The `CurrencyExchangeMixin` class enabled plugins to provide custom backends for updating currency exchange rate information. -Any implementing classes must provide the `update_exchange_rates` method. A simple example is shown below (with fake data). +Any implementing classes must provide the `update_exchange_rates` method. + +### Builtin Plugin + +The default builtin plugin for handling currency exchange rates is the `InvenTreeCurrencyExchangePlugin` class. + +::: plugin.builtin.integration.currency_exchange.InvenTreeCurrencyExchange + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] + + +### Sample Plugin + +A simple example is shown below (with fake data). ```python diff --git a/docs/docs/extend/plugins/event.md b/docs/docs/extend/plugins/event.md index 4fba5aa95610..96a41ca3c5a0 100644 --- a/docs/docs/extend/plugins/event.md +++ b/docs/docs/extend/plugins/event.md @@ -15,56 +15,34 @@ When a certain (server-side) event occurs, the background worker passes the even {% include 'img.html' %} {% endwith %} -### Example (all events) +### Sample Plugin - All events Implementing classes must at least provide a `process_event` function: -```python -class EventPlugin(EventMixin, InvenTreePlugin): - """ - A simple example plugin which responds to events on the InvenTree server. +::: plugin.samples.event.event_sample.EventPluginSample + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] - This example simply prints out the event information. - A more complex plugin could respond to specific events however it wanted. - """ - - NAME = "EventPlugin" - SLUG = "event" - TITLE = "Triggered Events" - - def process_event(self, event, *args, **kwargs): - print(f"Processing triggered event: '{event}'") -``` - -### Example (specific events) +### Sample Plugin - Specific Events If you want to process just some specific events, you can also implement the `wants_process_event` function to decide if you want to process this event or not. This function will be executed synchronously, so be aware that it should contain simple logic. Overall this function can reduce the workload on the background workers significantly since less events are queued to be processed. -```python -class EventPlugin(EventMixin, InvenTreePlugin): - """ - A simple example plugin which responds to 'salesordershipment.completed' event on the InvenTree server. - - This example simply prints out the event information. - A more complex plugin can run enhanced logic on this event. - """ - - NAME = "EventPlugin" - SLUG = "event" - TITLE = "Triggered Events" - - def wants_process_event(self, event): - """Here you can decide if this event should be send to `process_event` or not.""" - return event == "salesordershipment.completed" +::: plugin.samples.event.filtered_event_sample.FilteredEventPluginSample + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] - def process_event(self, event, *args, **kwargs): - """Here you can run you'r specific logic.""" - print(f"Sales order was completely shipped: '{args}' '{kwargs}'") -``` -### Events +## Events Events are passed through using a string identifier, e.g. `build.completed` diff --git a/docs/docs/extend/plugins/label.md b/docs/docs/extend/plugins/label.md index 72d6579dab07..ff33d64e38bf 100644 --- a/docs/docs/extend/plugins/label.md +++ b/docs/docs/extend/plugins/label.md @@ -172,6 +172,14 @@ InvenTree supplies the `InvenTreeLabelPlugin` out of the box, which generates a The default plugin also features a *DEBUG* mode which generates a raw HTML output, rather than PDF. This can be handy for tracking down any template rendering errors in your labels. +::: plugin.builtin.labels.inventree_label.InvenTreeLabelPlugin + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] + ### Available Data The *label* data are supplied to the plugin in both `PDF` and `PNG` formats. This provides compatibility with a great range of label printers "out of the box". Conversion to other formats, if required, is left as an exercise for the plugin developer. diff --git a/docs/docs/extend/plugins/locate.md b/docs/docs/extend/plugins/locate.md index 956dbedd7f01..33c715f57f0f 100644 --- a/docs/docs/extend/plugins/locate.md +++ b/docs/docs/extend/plugins/locate.md @@ -29,3 +29,15 @@ If a locate plugin is installed and activated, the [InvenTree mobile app](../../ ### Implementation Refer to the [InvenTree source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/locate/locate_sample.py) for a simple implementation example. + +### Sample Plugin + +A simple example is provided in the InvenTree code base: + +::: plugin.samples.locate.locate_sample.SampleLocatePlugin + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] diff --git a/docs/docs/extend/plugins/panel.md b/docs/docs/extend/plugins/panel.md index 542c4b0afa58..f91c175ab121 100644 --- a/docs/docs/extend/plugins/panel.md +++ b/docs/docs/extend/plugins/panel.md @@ -52,6 +52,18 @@ Or to add a template file that will be rendered as javascript code, from the plu Note : see convention for template directory above. +## Sample Plugin + +A sample plugin is provided in the InvenTree code base: + +::: plugin.samples.integration.custom_panel_sample.CustomPanelSample + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] + ## Example Implementations Refer to the `CustomPanelSample` example class in the `./plugin/samples/integration/` directory, for a fully worked example of how custom UI panels can be implemented. diff --git a/docs/docs/extend/plugins/report.md b/docs/docs/extend/plugins/report.md index 0e2cdc671eba..282c86e4e714 100644 --- a/docs/docs/extend/plugins/report.md +++ b/docs/docs/extend/plugins/report.md @@ -14,48 +14,14 @@ A plugin which implements the ReportMixin mixin can define the `add_report_conte Additionally the `add_label_context` method, allowing custom context data to be added to a label template at time of printing. -### Example +### Sample Plugin -A sample plugin which provides additional context data to the report templates can be found [in the InvenTree source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/integration/report_plugin_sample.py): +A sample plugin which provides additional context data to the report templates is available: -```python -"""Sample plugin for extending reporting functionality""" - -import random - -from plugin import InvenTreePlugin -from plugin.mixins import ReportMixin -from report.models import PurchaseOrderReport - - -class SampleReportPlugin(ReportMixin, InvenTreePlugin): - """Sample plugin which provides extra context data to a report""" - - NAME = "Sample Report Plugin" - SLUG = "reportexample" - TITLE = "Sample Report Plugin" - DESCRIPTION = "A sample plugin which provides extra context data to a report" - VERSION = "1.0" - - def some_custom_function(self): - """Some custom function which is not required for the plugin to function""" - return random.randint(0, 100) - - def add_report_context(self, report_instance, model_instance, request, context): - - """Add example content to the report instance""" - - # We can add any extra context data we want to the report - - # Generate a random string of data - context['random_text'] = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=20)) - - # Call a custom method - context['random_int'] = self.some_custom_function() - - # We can also add extra data to the context which is specific to the report type - context['is_purchase_order'] = isinstance(report_instance, PurchaseOrderReport) - - # We can also use the 'request' object to add extra context data - context['request_method'] = request.method -``` +::: plugin.samples.integration.report_plugin_sample.SampleReportPlugin + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] diff --git a/docs/docs/extend/plugins/schedule.md b/docs/docs/extend/plugins/schedule.md index a72901b52689..d0f28de7e282 100644 --- a/docs/docs/extend/plugins/schedule.md +++ b/docs/docs/extend/plugins/schedule.md @@ -18,45 +18,14 @@ The ScheduleMixin class provides a plugin with the ability to call functions at {% include 'img.html' %} {% endwith %} -### Example +### SamplePlugin An example of a plugin which supports scheduled tasks: -```python -class ScheduledTaskPlugin(ScheduleMixin, SettingsMixin, InvenTreePlugin): - """ - Sample plugin which runs a scheduled task, and provides user configuration. - """ - - NAME = "Scheduled Tasks" - SLUG = 'schedule' - - SCHEDULED_TASKS = { - 'global': { - 'func': 'some_module.function', - 'schedule': 'H', # Run every hour - }, - 'member': { - 'func': 'foo', - 'schedule': 'I', # Minutes - 'minutes': 15, - }, - } - - SETTINGS = { - 'SECRET': { - 'name': 'A secret', - 'description': 'User configurable value', - }, - } - - def foo(self): - """ - This function runs every 15 minutes - """ - secret_value = self.get_setting('SECRET') - print(f"foo - SECRET = {secret_value}) -``` - -!!! info "More Info" - For more information on any of the methods described below, refer to the InvenTree source code. [A working example is available as a starting point](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/plugin/samples/integration/scheduled_task.py). +::: plugin.samples.integration.scheduled_task.ScheduledTaskPlugin + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] diff --git a/docs/docs/extend/plugins/settings.md b/docs/docs/extend/plugins/settings.md index 178d5b1f927d..d094e365373f 100644 --- a/docs/docs/extend/plugins/settings.md +++ b/docs/docs/extend/plugins/settings.md @@ -15,7 +15,7 @@ The dict must be formatted similar to the following sample that shows how to use Take a look at the settings defined in `InvenTree.common.models.InvenTreeSetting` for all possible parameters. -### Example +### Example Plugin Below is a simple example of how a plugin can implement settings: diff --git a/docs/docs/extend/plugins/validation.md b/docs/docs/extend/plugins/validation.md index 20e4291a200e..d0e74b33ca92 100644 --- a/docs/docs/extend/plugins/validation.md +++ b/docs/docs/extend/plugins/validation.md @@ -58,7 +58,7 @@ To indicate a *field* validation error (i.e. the validation error applies only t Note that an error can be which corresponds to multiple model instance fields. -### Example +### Example Plugin Presented below is a simple working example for a plugin which implements the `validate_model_instance` method: @@ -188,3 +188,15 @@ def increment_serial_number(self, serial: str): return val ``` + +## Sample Plugin + +A sample plugin which implements custom validation routines is provided in the InvenTree source code: + +::: plugin.samples.integration.validation_sample.SampleValidatorPlugin + options: + show_bases: False + show_root_heading: False + show_root_toc_entry: False + show_source: True + members: [] diff --git a/docs/docs/extend/themes.md b/docs/docs/extend/themes.md index 5f89252eb1b3..49e4e185eeb1 100644 --- a/docs/docs/extend/themes.md +++ b/docs/docs/extend/themes.md @@ -14,7 +14,7 @@ Navigate to the "Settings" page and click on the "Display" tab, you should see t {% include 'img.html' %} {% endwith %} -The drop-down list let's you select any other color theme found in your static folder (see next section to find out how to [add color themes](#add-color-themes)). Once selected, click on the "Apply Theme" button for the new color theme to be activated. +The drop-down list let's you select any other color theme found in your static folder (see next section to find out how to [add color themes](#add-color-theme)). Once selected, click on the "Apply Theme" button for the new color theme to be activated. !!! info "Per-user Setting" Color themes are "user specific" which means that changing the color theme in your own settings won't affect other users. diff --git a/docs/docs/order/return_order.md b/docs/docs/order/return_order.md index 335288928681..0a7df0d0690d 100644 --- a/docs/docs/order/return_order.md +++ b/docs/docs/order/return_order.md @@ -98,7 +98,7 @@ While [line items](#line-items) must reference a particular stock item, extra li ## Return Order Reports -Custom [reports](../report/return_order.md) can be generated against each Return Order. +Custom [reports](../report/templates.md) can be generated against each Return Order. ### Calendar view diff --git a/docs/docs/releases/0.1.6.md b/docs/docs/releases/0.1.6.md index 91626a34d1a7..2e550c6ca95f 100644 --- a/docs/docs/releases/0.1.6.md +++ b/docs/docs/releases/0.1.6.md @@ -24,7 +24,7 @@ Refer to the [report documentation](../report/report.md) for further information !!! warning "LaTeX Support" LaTeX report templates are no longer supported for a number of technical and ideological reasons -[#1292](https://github.com/inventree/InvenTree/pull/1292) adds support for build order / work order reports. Refer to the [build report documentation](../report/build.md) for further information. +[#1292](https://github.com/inventree/InvenTree/pull/1292) adds support for build order / work order reports. Refer to the [report documentation](../report/templates.md) for further information. ### Inherited BOM Items diff --git a/docs/docs/releases/0.2.1.md b/docs/docs/releases/0.2.1.md index c992bd7db66c..506cce8d4cbd 100644 --- a/docs/docs/releases/0.2.1.md +++ b/docs/docs/releases/0.2.1.md @@ -32,7 +32,7 @@ Details on how to create and manage manufacturer parts were added [#1462](https://github.com/inventree/InvenTree/pull/1417) adds the ability to create a QR code containing the URL of a StockItem, which can be opened directly -on a portable device using the camera or a QR code scanner. More details [here](../report/labels.md#url-style-qr-code). +on a portable device using the camera or a QR code scanner. More details [here](../report/labels.md). ## Major Bug Fixes diff --git a/docs/docs/releases/0.7.0.md b/docs/docs/releases/0.7.0.md index 80d4f7910d1e..91eafd196fe2 100644 --- a/docs/docs/releases/0.7.0.md +++ b/docs/docs/releases/0.7.0.md @@ -53,7 +53,7 @@ This release also provides a marked improvement in unit testing and code coverag [#2372](https://github.com/inventree/InvenTree/pull/2372) provides an overhaul of notifications, allowing users to view their notifications directly in the InvenTree interface. ### Why are you hiding my name? -[#2861](https://github.com/inventree/InvenTree/pull/2861) adds several changes to enable admins to remove more of InvenTrees branding. Change logo, hide the about-modal for all but superusers and add custom messages to login and main navbar. Check out [the docs](../start/config.md#customisation-options). +[#2861](https://github.com/inventree/InvenTree/pull/2861) adds several changes to enable admins to remove more of InvenTrees branding. Change logo, hide the about-modal for all but superusers and add custom messages to login and main navbar. Check out [the docs](../start/config.md#customization-options) ### Label Printing Plugin diff --git a/docs/docs/report/bom.md b/docs/docs/report/bom.md deleted file mode 100644 index c6f18a3d2fe5..000000000000 --- a/docs/docs/report/bom.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: BOM Generation ---- - -## BOM Generation - -The bill of materials is an essential part of the documentation that needs to be sent to the factory. A simple csv export is OK to be important into SMT machines. But for human readable documentation it might not be sufficient. Additional information is needed. The Inventree report system allows to generate BOM well formatted BOM reports. - -### Context variables -| Variable | Description | -| --- | --- | -| bom_items | Query set that contains all BOM items | -| bom_items...sub_part | One component of the BOM | -| bom_items...quantity | Number of parts | -| bom_items...reference | Reference designators of the part | -| bom_items...substitutes | Query set that contains substitutes of the part if any exist in the BOM | - -### Examples - -#### BOM - -The following picture shows a simple example for a PCB with just three components from two different parts. - -{% with id="report-options", url="report/bom_example.png", description="BOM example" %} {% include 'img.html' %} {% endwith %} - -This example has been created using the following html template: - -```html -{% raw %} -{% extends "report/inventree_report_base.html" %} - -{% load i18n %} -{% load report %} -{% load inventree_extras %} - -{% block page_margin %} -margin-left: 2cm; -margin-right: 1cm; -margin-top: 4cm; -{% endblock %} - -{% block bottom_left %} -content: "v{{report_revision}} - {% format_date date %}"; -{% endblock %} - -{% block bottom_center %} -content: "InvenTree v{% inventree_version %}"; -{% endblock %} - -{% block style %} -.header-left { - text-align: left; - float: left; -} -table { - border: 1px solid #eee; - border-radius: 3px; - border-collapse: collapse; - width: 100%; - font-size: 80%; -} -table td { - border: 1px solid #eee; -} -{% endblock %} - -{% block header_content %} -
-

{% trans "Bill of Materials" %}

-
-{% endblock %} - -{% block page_content %} - - - - - - -
Board{{ part.IPN }}
Description{{ part.description }}
User{{ user }}
Date{{ date }}
Number of different components (codes){{ bom_items.count }}
-
- - - - - - - - - - - - - {% for line in bom_items.all %} - - - - - - - - - {% endfor %} - -
{% trans "IPN" %}{% trans "MPN" %}{% trans "Manufacturer" %}{% trans "Quantity" %}{% trans "Reference" %}{% trans "Substitute" %}
{{ line.sub_part.IPN }}{{ line.sub_part.name }} - {% for manf in line.sub_part.manufacturer_parts.all %} - {{ manf.manufacturer.name }} - {% endfor %} - {% decimal line.quantity %}{{ line.reference }} - {% for sub in line.substitutes.all %} - {{ sub.part.IPN }}
- {% endfor %} -
- -{% endblock %} -{% endraw %} -``` - -#### Pick List - -When all material has been allocated someone has to pick all things from the warehouse. -In case you need a printed pick list you can use the following template. This it just the -table. All other info and CSS has been left out for simplicity. Please have a look at the -BOM report for details. - -{% raw %} -```html - - - - - - - - - - - {% for line in build.allocated_stock.all %} - - - {% if line.stock_item.part.IPN != line.bom_item.sub_part.IPN %} - - {% else %} - - {% endif %} - - - - {% endfor %} - -
Original IPNAllocated PartLocationPCS
{{ line.bom_item.sub_part.IPN }} {{ line.stock_item.part.IPN }} {{ line.stock_item.part.IPN }} {{ line.stock_item.location.pathstring }} {{ line.quantity }}
-``` -{% endraw %} - -Here we have a loop that runs through all allocated parts for the build. For each part -we list the original IPN from the BOM and the IPN of the allocated part. These can differ -in case you have substitutes or template/variants in the BOM. In case the parts differ -we use a different format for the table cell e.g. print bold font or red color. -For the picker we list the full path names of the stock locations and the quantity -that is needed for the build. This will result in the following printout: - -{% with id="picklist", url="report/picklist.png", description="Picklist Example" %} {% include "img.html" %} {% endwith %} - -For those of you who would like to replace the "/" by something else because it is hard -to read in some fonts use the following trick: - -{% raw %} -```html - {% for loc in line.stock_item.location.path %}{{ loc.name }}{% if not forloop.last %}-{% endif %}{% endfor %} -``` -{% endraw %} - -Here we use location.path which is a query set that contains the location path up to the -topmost parent. We use a loop to cycle through that and print the .name of the entry followed -by a "-". The foorloop.last is a Django trick that allows us to not print the "-" after -the last entry. The result looks like here: - -{% with id="picklist_with_path", url="report/picklist_with_path.png", description="Picklist Example" %} {% include "img.html" %} {% endwith %} - -Finally added a `{% raw %}|floatformat:0{% endraw %}` to the quantity that removes the trailing zeros. - -### Default Report Template - -A default *BOM Report* template is provided out of the box, which is useful for generating simple test reports. Furthermore, it may be used as a starting point for developing custom BOM reports: - -View the [source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templates/report/inventree_bill_of_materials_report.html) for the default test report template. diff --git a/docs/docs/report/build.md b/docs/docs/report/build.md deleted file mode 100644 index e249fe108b40..000000000000 --- a/docs/docs/report/build.md +++ /dev/null @@ -1,324 +0,0 @@ ---- -title: Build Order Report ---- - -## Build Order Report - -Custom build order reports may be generated against any given [Build Order](../build/build.md). For example, build order reports can be used to generate work orders. - -### Build Filters - -A build order report template may define a set of filters against which [Build Order](../build/build.md) items are sorted. - -### Context Variables - -In addition to the default report context variables, the following context variables are made available to the build order report template for rendering: - -| Variable | Description | -| --- | --- | -| build | The build object the report is being generated against | -| part | The [Part](./context_variables.md#part) object that the build references | -| line_items | A shortcut for [build.line_items](#build) | -| bom_items | A shortcut for [build.bom_items](#build) | -| build_outputs | A shortcut for [build.build_outputs](#build) | -| reference | The build order reference string | -| quantity | Build order quantity (number of assemblies being built) | - -#### build - -The following variables are accessed by build.variable - -| Variable | Description | -| --- | --- | -| active | Boolean that tells if the build is active | -| batch | Batch code transferred to build parts (optional) | -| line_items | A query set with all the build line items associated with the build | -| bom_items | A query set with all BOM items for the part being assembled | -| build_outputs | A queryset containing all build output ([Stock Item](../stock/stock.md)) objects associated with this build | -| can_complete | Boolean that tells if the build can be completed. Means: All material allocated and all parts have been build. | -| are_untracked_parts_allocated | Boolean that tells if all bom_items have allocated stock_items. | -| creation_date | Date where the build has been created | -| completion_date | Date the build was completed (or, if incomplete, the expected date of completion) | -| completed_by | The [User](./context_variables.md#user) that completed the build | -| is_overdue | Boolean that tells if the build is overdue | -| is_complete | Boolean that tells if the build is complete | -| issued_by | The [User](./context_variables.md#user) who created the build | -| link | External URL for extra information | -| notes | Text notes | -| parent | Reference to a parent build object if this is a sub build | -| part | The [Part](./context_variables.md#part) to be built (from component BOM items) | -| quantity | Build order quantity (total number of assembly outputs) | -| completed | The number out outputs which have been completed | -| reference | Build order reference (required, must be unique) | -| required_parts | A query set with all parts that are required for the build | -| responsible | Owner responsible for completing the build. This can be a user or a group. Depending on that further context variables differ | -| sales_order | References to a [Sales Order](./context_variables.md#salesorder) object for which this build is required (e.g. the output of this build will be used to fulfil a sales order) | -| status | The status of the build. 20 means 'Production' | -| sub_build_count | Number of sub builds | -| sub_builds | Query set with all sub builds | -| target_date | Date the build will be overdue | -| take_from | [StockLocation](./context_variables.md#stocklocation) to take stock from to make this build (if blank, can take from anywhere) | -| title | The full name of the build | -| description | The description of the build | -| allocated_stock.all | A query set with all allocated stock items for the build | - -As usual items in a query sets can be selected by adding a .n to the set e.g. build.required_parts.0 -will result in the first part of the list. Each query set has again its own context variables. - -#### line_items - -The `line_items` variable is a list of all build line items associated with the selected build. The following attributes are available for each individual line_item instance: - -| Attribute | Description | -| --- | --- | -| .build | A reference back to the parent build order | -| .bom_item | A reference to the BOMItem which defines this line item | -| .quantity | The required quantity which is to be allocated against this line item | -| .part | A shortcut for .bom_item.sub_part | -| .allocations | A list of BuildItem objects which allocate stock items against this line item | -| .allocated_quantity | The total stock quantity which has been allocated against this line | -| .unallocated_quantity | The remaining quantity to allocate | -| .is_fully_allocated | Boolean value, returns True if the line item has sufficient stock allocated against it | -| .is_overallocated | Boolean value, returns True if the line item has more allocated stock than is required | - -#### bom_items - -| Attribute | Description | -| --- | --- | -| .reference | The reference designators of the components | -| .quantity | The number of components required to build | -| .overage | The extra amount required to assembly | -| .consumable | Boolean field, True if this is a "consumable" part which is not tracked through builds | -| .sub_part | The part at this position | -| .substitutes.all | A query set with all allowed substitutes for that part | -| .note | Extra text field which can contain additional information | - - -#### allocated_stock.all - -| Attribute | Description | -| --- | --- | -| .bom_item | The bom item where this part belongs to | -| .stock_item | The allocated [StockItem](./context_variables.md#stockitem) | -| .quantity | The number of components needed for the build (components in BOM x parts to build) | - -### Example - -The following example will create a report with header and BOM. In the BOM table substitutes will be listed. - -{% raw %} -```html -{% extends "report/inventree_report_base.html" %} - -{% load i18n %} -{% load report %} -{% load barcode %} -{% load inventree_extras %} -{% load markdownify %} - -{% block page_margin %} -margin: 2cm; -margin-top: 4cm; -{% endblock %} - -{% block style %} - -.header-right { - text-align: right; - float: right; -} - -.logo { - height: 20mm; - vertical-align: middle; -} - -.details { - width: 100%; - border: 1px solid; - border-radius: 3px; - padding: 5px; - min-height: 42mm; -} - -.details table { - overflow-wrap: break-word; - word-wrap: break-word; - width: 65%; - table-layout: fixed; - font-size: 75%; -} -.changes table { - overflow-wrap: break-word; - word-wrap: break-word; - width: 100%; - table-layout: fixed; - font-size: 75%; - border: 1px solid; -} - -.changes-table th { - font-size: 100%; - border: 1px solid; -} - -.changes-table td { - border: 1px solid; -} - -.details table td:not(:last-child){ - white-space: nowrap; -} - -.details table td:last-child{ - width: 50%; - padding-left: 1cm; - padding-right: 1cm; -} - -.details-table td { - padding-left: 10px; - padding-top: 5px; - padding-bottom: 5px; - border-bottom: 1px solid #555; -} - -{% endblock %} - -{% block bottom_left %} -content: "v{{report_revision}} - {% format_date date %}"; -{% endblock %} - -{% block header_content %} - - - -
-

- Build Order {{ build }} -

-
-
- -
-{% endblock %} - -{% block page_content %} - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {% if build.parent %} - - - - - {% endif %} - {% if build.issued_by %} - - - - - {% endif %} - {% if build.responsible %} - - - - - {% endif %} - - - - - {% if build.sub_build_count > 0 %} - - - - - {% endif %} - - - - - - - - -
{% trans "Build Order" %}{% internal_link build.get_absolute_url build %}
{% trans "Order" %}{{ reference }}
{% trans "Part" %}{% internal_link part.get_absolute_url part.IPN %}
{% trans "Quantity" %}{{ build.quantity }}
{% trans "Description" %}{{ build.title }}
{% trans "Issued" %}{% format_date build.creation_date %}
{% trans "Target Date" %} - {% if build.target_date %} - {% format_date build.target_date %} - {% else %} - Not specified - {% endif %} -
{% trans "Required For" %}{% internal_link build.parent.get_absolute_url build.parent %}
{% trans "Issued By" %}{{ build.issued_by }}
{% trans "Responsible" %}{{ build.responsible }}
{% trans "Sub builds count" %}{{ build.sub_build_count }}
{% trans "Sub Builds" %}{{ build.sub_builds }}
{% trans "Overdue" %}{{ build.is_overdue }}
{% trans "Can complete" %}{{ build.can_complete }}
-
- -

{% trans "Notes" %}

-{% if build.notes %} -{{ build.notes|markdownify }} -{% endif %} - -

{% trans "Parts" %}

- -
- - - - - - - - - - {% for line in build.bom_items %} - - - - - - {% endfor %} - -
Original IPNReferenceReplace width IPN
{{ line.sub_part.IPN }} {{ line.reference }} {{ line.substitutes.all.0.part.IPN }}
-
-{% endblock %} -``` - -{% endraw %} - -This will result a report page like this: - -{% with id="report-options", url="build/report-61.png", description="Report Example Builds" %} {% include "img.html" %} {% endwith %} - -### Default Report Template - -A default *Build Report* template is provided out of the box, which is useful for generating simple test reports. Furthermore, it may be used as a starting point for developing custom BOM reports: - -View the [source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templates/report/inventree_build_order_base.html) for the default build report template. diff --git a/docs/docs/report/context_variables.md b/docs/docs/report/context_variables.md index 4704d1560a64..10180a05047b 100644 --- a/docs/docs/report/context_variables.md +++ b/docs/docs/report/context_variables.md @@ -2,64 +2,245 @@ title: Context Variables --- + ## Context Variables -### Report +Context variables are provided to each template when it is rendered. The available context variables depend on the model type for which the template is being rendered. -!!! info "Specific Report Context" - Specific report types may have additional context variables, see below. +### Global Context -Each report has access to a number of context variables by default. The following context variables are provided to every report template: +In addition to the model-specific context variables, the following global context variables are available to all templates: | Variable | Description | | --- | --- | +| base_url | The base URL for the InvenTree instance | | date | Current date, represented as a Python datetime.date object | | datetime | Current datetime, represented as a Python datetime object | -| page_size | The specified page size for this report, e.g. `A4` or `Letter landscape` | -| report_template | The report template model instance | -| report_name | Name of the report template | -| report_description | Description of the report template | -| report_revision | Revision of the report template | -| request | Django request object | +| request | The Django request object associated with the printing process | +| template | The report template instance which is being rendered against | +| template_description | Description of the report template | +| template_name | Name of the report template | +| template_revision | Revision of the report template | | user | User who made the request to render the template | -#### Label +::: report.models.ReportTemplateBase.base_context + options: + show_source: True + +### Report Context + +In addition to the [global context](#global-context), all *report* templates have access to the following context variables: + +| Variable | Description | +| --- | --- | +| page_size | The page size of the report | +| landscape | Boolean value, True if the report is in landscape mode | + +Note that custom plugins may also add additional context variables to the report context. + +::: report.models.ReportTemplate.get_context + options: + show_source: True + +### Label Context + +In addition to the [global context](#global-context), all *label* templates have access to the following context variables: + +| Variable | Description | +| --- | --- | +| width | The width of the label (in mm) | +| height | The height of the label (in mm) | + +Note that custom plugins may also add additional context variables to the label context. + +::: report.models.LabelTemplate.get_context + options: + show_source: True + + +## Template Types + +Templates (whether for generating [reports](./report.md) or [labels](./labels.md)) are rendered against a particular "model" type. The following model types are supported, and can have templates renderer against them: + +| Model Type | Description | +| --- | --- | +| [build](#build-order) | A [Build Order](../build/build.md) instance | +| [buildline](#build-line) | A [Build Order Line Item](../build/build.md) instance | +| [salesorder](#sales-order) | A [Sales Order](../order/sales_order.md) instance | +| [returnorder](#return-order) | A [Return Order](../order/return_order.md) instance | +| [purchaseorder](#purchase-order) | A [Purchase Order](../order/purchase_order.md) instance | +| [stockitem](#stock-item) | A [StockItem](../stock/stock.md#stock-item) instance | +| [stocklocation](#stock-location) | A [StockLocation](../stock/stock.md#stock-location) instance | +| [part](#part) | A [Part](../part/part.md) instance | + +### Build Order + +When printing a report or label against a [Build Order](../build/build.md) object, the following context variables are available: + +| Variable | Description | +| --- | --- | +| bom_items | Query set of all BuildItem objects associated with the BuildOrder | +| build | The BuildOrder instance itself | +| build_outputs | Query set of all BuildItem objects associated with the BuildOrder | +| line_items | Query set of all build line items associated with the BuildOrder | +| part | The Part object which is being assembled in the build order | +| quantity | The total quantity of the part being assembled | +| reference | The reference field of the BuildOrder | +| title | The title field of the BuildOrder | + +::: build.models.Build.report_context + options: + show_source: True + +### Build Line + +When printing a report or label against a [BuildOrderLineItem](../build/build.md) object, the following context variables are available: + +| Variable | Description | +| --- | --- | +| allocated_quantity | The quantity of the part which has been allocated to this build | +| allocations | A query set of all StockItem objects which have been allocated to this build line | +| bom_item | The BomItem associated with this line item | +| build | The BuildOrder instance associated with this line item | +| build_line | The build line instance itself | +| part | The sub-part (component) associated with the linked BomItem instance | +| quantity | The quantity required for this line item | + +::: build.models.BuildLine.report_context + options: + show_source: True + + +### Sales Order + +When printing a report or label against a [SalesOrder](../order/sales_order.md) object, the following context variables are available: + +| Variable | Description | +| --- | --- | +| customer | The customer object associated with the SalesOrder | +| description | The description field of the SalesOrder | +| extra_lines | Query set of all extra lines associated with the SalesOrder | +| lines | Query set of all line items associated with the SalesOrder | +| order | The SalesOrder instance itself | +| reference | The reference field of the SalesOrder | +| title | The title (string representation) of the SalesOrder | + +::: order.models.Order.report_context + options: + show_source: True + +### Return Order -Certain types of labels have different context variables then other labels. +When printing a report or label against a [ReturnOrder](../order/return_order.md) object, the following context variables are available: -##### Stock Item Label +| Variable | Description | +| --- | --- | +| customer | The customer object associated with the ReturnOrder | +| description | The description field of the ReturnOrder | +| extra_lines | Query set of all extra lines associated with the ReturnOrder | +| lines | Query set of all line items associated with the ReturnOrder | +| order | The ReturnOrder instance itself | +| reference | The reference field of the ReturnOrder | +| title | The title (string representation) of the ReturnOrder | + +### Purchase Order + +When printing a report or label against a [PurchaseOrder](../order/purchase_order.md) object, the following context variables are available: + +| Variable | Description | +| --- | --- | +| description | The description field of the PurchaseOrder | +| extra_lines | Query set of all extra lines associated with the PurchaseOrder | +| lines | Query set of all line items associated with the PurchaseOrder | +| order | The PurchaseOrder instance itself | +| reference | The reference field of the PurchaseOrder | +| supplier | The supplier object associated with the PurchaseOrder | +| title | The title (string representation) of the PurchaseOrder | + +### Stock Item -The following variables are made available to the StockItem label template: +When printing a report or label against a [StockItem](../stock/stock.md#stock-item) object, the following context variables are available: | Variable | Description | -| -------- | ----------- | -| item | The [StockItem](./context_variables.md#stockitem) object itself | -| part | The [Part](./context_variables.md#part) object which is referenced by the [StockItem](./context_variables.md#stockitem) object | -| name | The `name` field of the associated Part object | -| ipn | The `IPN` field of the associated Part object | -| revision | The `revision` field of the associated Part object | -| quantity | The `quantity` field of the StockItem object | -| serial | The `serial` field of the StockItem object | -| uid | The `uid` field of the StockItem object | -| tests | Dict object of TestResult data associated with the StockItem | +| --- | --- | +| barcode_data | Generated barcode data for the StockItem | +| barcode_hash | Hash of the barcode data | +| batch | The batch code for the StockItem | +| child_items | Query set of all StockItem objects which are children of this StockItem | +| ipn | The IPN (internal part number) of the associated Part | +| installed_items | Query set of all StockItem objects which are installed in this StockItem | +| item | The StockItem object itself | +| name | The name of the associated Part | +| part | The Part object which is associated with the StockItem | +| qr_data | Generated QR code data for the StockItem | +| qr_url | Generated URL for embedding in a QR code | | parameters | Dict object containing the parameters associated with the base Part | +| quantity | The quantity of the StockItem | +| result_list | FLattened list of TestResult data associated with the stock item | +| results | Dict object of TestResult data associated with the StockItem | +| serial | The serial number of the StockItem | +| stock_item | The StockItem object itself (shadow of 'item') | +| tests | Dict object of TestResult data associated with the StockItem (shadow of 'results') | +| test_keys | List of test keys associated with the StockItem | +| test_template_list | List of test templates associated with the StockItem | +| test_templates | Dict object of test templates associated with the StockItem | + +::: stock.models.StockItem.report_context + options: + show_source: True -##### Stock Location Label +### Stock Location -The following variables are made available to the StockLocation label template: +When printing a report or label against a [StockLocation](../stock/stock.md#stock-location) object, the following context variables are available: | Variable | Description | -| -------- | ----------- | -| location | The [StockLocation](./context_variables.md#stocklocation) object itself | +| --- | --- | +| location | The StockLocation object itself | +| qr_data | Formatted QR code data for the StockLocation | +| parent | The parent StockLocation object | +| stock_location | The StockLocation object itself (shadow of 'location') | +| stock_items | Query set of all StockItem objects which are located in the StockLocation | -### Parts +::: stock.models.StockLocation.report_context + options: + show_source: True + + +### Part + +When printing a report or label against a [Part](../part/part.md) object, the following context variables are available: + +| Variable | Description | +| --- | --- | +| bom_items | Query set of all BomItem objects associated with the Part | +| category | The PartCategory object associated with the Part | +| description | The description field of the Part | +| IPN | The IPN (internal part number) of the Part | +| name | The name of the Part | +| parameters | Dict object containing the parameters associated with the Part | +| part | The Part object itself | +| qr_data | Formatted QR code data for the Part | +| qr_url | Generated URL for embedding in a QR code | +| revision | The revision of the Part | +| test_template_list | List of test templates associated with the Part | +| test_templates | Dict object of test templates associated with the Part | + +::: part.models.Part.report_context + options: + show_source: True + +## Model Variables -!!! incomplete "TODO" - This section requires further work +Additional to the context variables provided directly to each template, each model type has a number of attributes and methods which can be accessedd via the template. + +For each model type, a subset of the most commonly used attributes are listed below. For a full list of attributes and methods, refer to the source code for the particular model type. + +### Parts #### Part -Each part object has access to a lot of context variables about the part. The following context variables are provided when accessing a `Part` object: + +Each part object has access to a lot of context variables about the part. The following context variables are provided when accessing a `Part` object from within the template. | Variable | Description | |----------|-------------| @@ -106,6 +287,7 @@ Each part object has access to a lot of context variables about the part. The fo #### Part Category + | Variable | Description | |----------|-------------| | name | Name of this category | @@ -117,6 +299,7 @@ Each part object has access to a lot of context variables about the part. The fo #### StockItem + | Variable | Description | |----------|-------------| | parent | Link to another [StockItem](./context_variables.md#stockitem) from which this StockItem was created | @@ -139,7 +322,7 @@ Each part object has access to a lot of context variables about the part. The fo | notes | Extra notes field | | build | Link to a Build (if this stock item was created from a build) | | is_building | Boolean field indicating if this stock item is currently being built (or is "in production") | -| purchase_order | Link to a [PurchaseOrder](./context_variables.md#purchaseorder) (if this stock item was created from a PurchaseOrder) | +| purchase_order | Link to a [PurchaseOrder](./context_variables.md#purchase-order) (if this stock item was created from a PurchaseOrder) | | infinite | If True this [StockItem](./context_variables.md#stockitem) can never be exhausted | | sales_order | Link to a [SalesOrder](./context_variables.md#salesorder) object (if the StockItem has been assigned to a SalesOrder) | | purchase_price | The unit purchase price for this [StockItem](./context_variables.md#stockitem) - this is the unit price at time of purchase (if this item was purchased from an external supplier) | @@ -164,6 +347,7 @@ Each part object has access to a lot of context variables about the part. The fo #### Company + | Variable | Description | |----------|-------------| | name | Name of the company | @@ -184,6 +368,7 @@ Each part object has access to a lot of context variables about the part. The fo #### Address + | Variable | Description | |----------|-------------| | line1 | First line of the postal address | @@ -194,9 +379,6 @@ Each part object has access to a lot of context variables about the part. The fo #### Contact -Contacts are added to companies. Actually the company has no link to the contacts. -You can search the company object of the contact. - | Variable | Description | |----------|-------------| | company | Company object where the contact belongs to | @@ -207,6 +389,7 @@ You can search the company object of the contact. #### SupplierPart + | Variable | Description | |----------|-------------| | part | Link to the master Part (Obsolete) | @@ -226,24 +409,13 @@ You can search the company object of the contact. | has_price_breaks | Whether this [SupplierPart](./context_variables.md#supplierpart) has price breaks | | manufacturer_string | Format a MPN string for this [SupplierPart](./context_variables.md#supplierpart). Concatenates manufacture name and part number. | -### Manufacturers - -!!! incomplete "TODO" - This section requires further work - -#### Manufacturer - -| Variable | Description | -|----------|-------------| - -#### ManufacturerPart - -| Variable | Description | -|----------|-------------| ### Orders -The [Purchase Order](../order/purchase_order.md) context variables are described in the [Purchase Order](./purchase_order.md) section. +#### Purchase Order + +!!! note "TODO" + This section is incomplete #### SalesOrder diff --git a/docs/docs/report/helpers.md b/docs/docs/report/helpers.md index 605d3e50cd17..fc64f5d52bdf 100644 --- a/docs/docs/report/helpers.md +++ b/docs/docs/report/helpers.md @@ -18,7 +18,7 @@ Some common functions are provided for use in custom report and label templates. When making use of helper functions within a template, it can be useful to store the result of the function to a variable, rather than immediately rendering the output. -For example, using the [render_currency](#rendering-currency) helper function, we can store the output to a variable which can be used at a later point in the template: +For example, using the [render_currency](#currency-formatting) helper function, we can store the output to a variable which can be used at a later point in the template: ```html {% raw %} @@ -272,7 +272,7 @@ A template tag is provided to load the InvenTree logo image into a report. You c ### Custom Logo -If the system administrator has enabled a [custom logo](../start/config.md#customisation-options), then this logo will be used instead of the base InvenTree logo. +If the system administrator has enabled a [custom logo](../start/config.md#customization-options) then this logo will be used instead of the base InvenTree logo. This is a useful way to get a custom company logo into your reports. @@ -287,7 +287,7 @@ If you have a custom logo, but explicitly wish to load the InvenTree logo itself ## Report Assets -[Report Assets](./report.md#report-assets) are files specifically uploaded by the user for inclusion in generated reports and labels. +[Report Assets](./templates.md#report-assets) are files specifically uploaded by the user for inclusion in generated reports and labels. You can add asset images to the reports and labels by using the `{% raw %}{% asset ... %}{% endraw %}` template tag: diff --git a/docs/docs/report/labels.md b/docs/docs/report/labels.md index 551821055993..f2f455ec36be 100644 --- a/docs/docs/report/labels.md +++ b/docs/docs/report/labels.md @@ -11,17 +11,6 @@ Custom labels can be generated using simple HTML templates, with support for QR- Simple (generic) label templates are supplied 'out of the box' with InvenTree - however support is provided for generation of extremely specific custom labels, to meet any particular requirement. -## Label Types - -The following types of labels are available - -| Label Type | Description | -| --- | --- | -| [Part Labels](./labels/part_labels.md) | Print labels for individual parts | -| [Stock Labels](./labels/stock_labels.md) | Print labels for individual stock items | -| [Location Labels](./labels/location_labels.md) | Print labels for individual stock locations -| [Build Labels](./labels/build_labels.md) | Print labels for individual build order line items | - ## Label Templates Label templates are written using a mixture of [HTML](https://www.w3schools.com/html/) and [CSS](https://www.w3schools.com/css). [Weasyprint](https://weasyprint.org/) templates support a *subset* of HTML and CSS features. In addition to supporting HTML and CSS formatting, the label templates support the Django templating engine, allowing conditional formatting of the label data. diff --git a/docs/docs/report/labels/build_labels.md b/docs/docs/report/labels/build_labels.md deleted file mode 100644 index 0a3924a1068d..000000000000 --- a/docs/docs/report/labels/build_labels.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: Build Labels ---- - -## Build Line Labels - -Build label templates are used to generate labels for individual build order line items. - -### Creating Build Line Label Templates - -Build label templates are added (and edited) via the [admin interface](../../settings/admin.md). - -### Printing Build Line Labels - -Build line labels are printed from the Build Order page, under the *Allocate Stock* tab. Multiple line items can be selected for printing: - -{% with id='print_build_labels', url='report/label_build_print.png', description='Print build line labels' %} -{% include 'img.html' %} -{% endwith %} - -### Context Data - -The following context variables are made available to the Build Line label template: - -| Variable | Description | -| --- | --- | -| build_line | The build_line instance | -| build | The build order to which the build_line is linked | -| bom_item | The bom_item to which the build_line is linked | -| part | The required part for this build_line instance. References bom_item.sub_part | -| quantity | The total quantity required for the build line | -| allocated_quantity | The total quantity which has been allocated against the build line | -| allocations | A queryset containing the allocations made against the build_line | - -## Example - -A simple example template is shown below: - -```html -{% raw %} -{% extends "label/label_base.html" %} -{% load barcode report %} -{% load inventree_extras %} - -{% block style %} - -{{ block.super }} - -.label { - margin: 1mm; -} - -.qr { - height: 28mm; - width: 28mm; - position: relative; - top: 0mm; - right: 0mm; - float: right; -} - -.label-table { - width: 100%; - border-collapse: collapse; - border: 1pt solid black; -} - -.label-table tr { - width: 100%; - border-bottom: 1pt solid black; - padding: 2.5mm; -} - -.label-table td { - padding: 3mm; -} - -{% endblock style %} - -{% block content %} - -
- - - - - - - - - -
- Build Order: {{ build.reference }}
- Build Qty: {% decimal build.quantity %}
-
- build qr -
- Part: {{ part.name }}
- {% if part.IPN %} - IPN: {{ part.IPN }}
- {% endif %} - Qty / Unit: {% decimal bom_item.quantity %} {% if part.units %}[{{ part.units }}]{% endif %}
- Qty Total: {% decimal quantity %} {% if part.units %}[{{ part.units }}]{% endif %} -
- part qr -
-
- -{% endblock content %} - -{% endraw %} -``` - -Which results in a label like: - -{% with id='build_label_example', url='report/label_build_example.png', description='Example build line labels' %} -{% include 'img.html' %} -{% endwith %} diff --git a/docs/docs/report/labels/location_labels.md b/docs/docs/report/labels/location_labels.md deleted file mode 100644 index e7af905d7506..000000000000 --- a/docs/docs/report/labels/location_labels.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Location Labels ---- - - -## Stock Location Labels - -Stock Location label templates are used to generate labels for individual Stock Locations. - -### Creating Stock Location Label Templates - -Stock Location label templates are added (and edited) via the admin interface. - -### Printing Stock Location Labels - -To print a single label from the Stock Location detail view, select the *Print Label* option. - -### Context Data - -The following variables are made available to the StockLocation label template: - -| Variable | Description | -| -------- | ----------- | -| location | The [StockLocation](../context_variables.md#stocklocation) object itself | diff --git a/docs/docs/report/labels/part_labels.md b/docs/docs/report/labels/part_labels.md deleted file mode 100644 index 7e9e5606b8db..000000000000 --- a/docs/docs/report/labels/part_labels.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Part Labels ---- - - -## Part Labels - -Part label templates are used to generate labels for individual Part instances. - -### Creating Part Label Templates - -Part label templates are added (and edited) via the admin interface. - -### Printing Part Labels - -Part label can be printed using the following approaches: - -To print a single part label from the Part detail view, select the *Print Label* option. - -To print multiple part labels, select multiple parts in the part table and select the *Print Labels* option. - -### Context Data - -The following context variables are made available to the Part label template: - -| Variable | Description | -| -------- | ----------- | -| part | The [Part](../context_variables.md#part) object | -| category | The [Part Category](../context_variables.md#part-category) which contains the Part | -| name | The name of the part | -| description | The description text for the part | -| IPN | Internal part number (IPN) for the part | -| revision | Part revision code | -| qr_data | String data which can be rendered to a QR code | -| parameters | Map (Python dictionary) object containing the parameters associated with the part instance | - -#### Parameter Values - -The part parameter *values* can be accessed by parameter name lookup in the template, as follows: - -```html -{% raw %} - -Part: {{ part.name }} -Length: {{ parameters.length }} - -{% endraw %} -``` - -!!! warning "Spaces" - Note that for parameters which include a `space` character in their name, lookup using the "dot" notation won't work! In this case, try using the [key lookup](../helpers.md#key-access) method: - -```html -{% raw %} - -Voltage Rating: {% getkey parameters "Voltage Rating" %} -{% endraw %} -``` - -#### Parameter Data - -If you require access to the parameter data itself, and not just the "value" of a particular parameter, you can use the `part_parameter` [helper function](../helpers.md#part-parameters). - -For example, the following label template can be used to generate a label which contains parameter data in addition to parameter units: - -```html -{% raw %} -{% extends "label/label_base.html" %} - -{% load report %} - -{% block content %} - -{% part_parameter part "Width" as width %} -{% part_parameter part "Length" as length %} - -
- Part: {{ part.full_name }}
- Width: {{ width.data }} [{{ width.units }}]
- Length: {{ length.data }} [{{ length.units }}] -
- -{% endblock content %} -{% endraw %} -``` - -The following label is produced: - -{% with id="report-parameters", url="report/label_with_parameters.png", description="Label with parameters" %} -{% include 'img.html' %} -{% endwith %} diff --git a/docs/docs/report/labels/stock_labels.md b/docs/docs/report/labels/stock_labels.md deleted file mode 100644 index eb72147284da..000000000000 --- a/docs/docs/report/labels/stock_labels.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Stock Labels ---- - - -## Stock Item Labels - -Stock Item label templates are used to generate labels for individual Stock Items. - -### Creating Stock Item Label Templates - -Stock Item label templates are added (and edited) via the admin interface. - -### Printing Stock Item Labels - -Stock Item labels can be printed using the following approaches: - -To print a single stock item from the Stock Item detail view, select the *Print Label* option as shown below: - -{% with id='item_label_single', url='report/label_stock_print_single.png', description='Print single stock item label' %} -{% include 'img.html' %} -{% endwith %} - -To print multiple stock items from the Stock table view, select the *Print Labels* option as shown below: - -{% with id='item_label_multiple', url='report/label_stock_print_multiple.png', description='Print multiple stock item labels' %} -{% include 'img.html' %} -{% endwith %} - -### Context Data - -The following variables are made available to the StockItem label template: - -| Variable | Description | -| -------- | ----------- | -| item | The [StockItem](../context_variables.md#stockitem) object itself | -| part | The [Part](../context_variables.md#part) object which is referenced by the [StockItem](../context_variables.md#stockitem) object | -| name | The `name` field of the associated Part object | -| ipn | The `IPN` field of the associated Part object | -| revision | The `revision` field of the associated Part object | -| quantity | The `quantity` field of the StockItem object | -| serial | The `serial` field of the StockItem object | -| uid | The `uid` field of the StockItem object | -| tests | Dict object of TestResult data associated with the StockItem | -| parameters | Dict object containing the parameters associated with the base Part | - -### URL-style QR code - -Stock Item labels support [QR code](../barcodes.md#qr-code) containing the stock item URL, which can be -scanned and opened directly -on a portable device using the camera or a QR code scanner. To generate a URL-style QR code for stock item in the [label HTML template](../labels.md#label-templates), add the -following HTML tag: - -``` html -{% raw %} - -{% endraw %} -``` - -Make sure to customize the `custom_qr_class` CSS class to define the position of the QR code -on the label. diff --git a/docs/docs/report/purchase_order.md b/docs/docs/report/purchase_order.md deleted file mode 100644 index 045e1afa7a23..000000000000 --- a/docs/docs/report/purchase_order.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Purchase Order Report ---- - -## Purchase Order Reports - -Custom purchase order reports may be generated against any given [Purchase Order](../order/purchase_order.md). For example, purchase order reports could be used to generate a pdf of the order to send to a supplier. - -### Purchase Order Filters - -The report template can be filtered against available [Purchase Order](../order/purchase_order.md) instances. - -### Context Variables - -In addition to the default report context variables, the following variables are made available to the purchase order report template for rendering: - -| Variable | Description | -| --- | --- | -| order | The specific Purchase Order object | -| reference | The order reference field (can also be accessed as `{% raw %}{{ order.reference }}{% endraw %}`) | -| description | The order description field | -| supplier | The [supplier](../order/company.md#suppliers) associated with this purchase order | -| lines | A list of available line items for this order | -| extra_lines | A list of available *extra* line items for this order | -| order.created_by | The user who created the order | -| order.responsible | The user or group who is responsible for the order | -| order.creation_date | The date when the order was created | -| order.target_date | The date when the order should arrive | -| order.if_overdue | Boolean value that tells if the target date has passed | -| order.currency | The currency code associated with this order, e.g. 'AUD' | -| order.contact | The [contact](./context_variables.md#contact) object associated with this order | - -#### Lines - -Each line item (available within the `lines` list) has sub variables, as follows: - -| Variable | Description | -| --- | --- | -| quantity | The quantity of the part to be ordered | -| part | The [supplierpart ](./context_variables.md#supplierpart) object to be ordered | -| reference | The reference given in the part of the order | -| notes | The notes given in the part of the order | -| target_date | The date when the part should arrive. Each part can have an individual date | -| price | The unit price the line item | -| total_line_price | The total price for this line item, calculated from the unit price and quantity | -| destination | The stock location where the part will be stored | - -A simple example below shows how to use the context variables for each line item: - -```html -{% raw %} -{% for line in lines %} -Internal Part: {{ line.part.part.name }} - {{ line.part.part.description }} -SKU: {{ line.part.SKU }} -Price: {% render_currency line.total_line_price %} -{% endfor %} -{% endraw %} -``` - - -### Default Report Template - -A default *Purchase Order Report* template is provided out of the box, which is useful for generating simple test reports. Furthermore, it may be used as a starting point for developing custom BOM reports: - -View the [source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templates/report/inventree_po_report_base.html) for the default purchase order report template. diff --git a/docs/docs/report/report.md b/docs/docs/report/report.md index 468802bf5c99..cff02f51417b 100644 --- a/docs/docs/report/report.md +++ b/docs/docs/report/report.md @@ -1,14 +1,14 @@ --- -title: Report Generation +title: Report and LabelGeneration --- -## Custom Reporting +## Custom Reports -InvenTree supports a customizable reporting ecosystem, allowing the user to develop reporting templates that meet their particular needs. +InvenTree supports a customizable reporting ecosystem, allowing the user to develop document templates that meet their particular needs. -PDF reports are generated from custom HTML template files which are written by the user. +PDF files are generated from custom HTML template files which are written by the user. -Reports are used in a variety of situations to format data in a friendly format for printing, distribution, conformance and testing. +Templates can be used to generate *reports* or *labels* which can be used in a variety of situations to format data in a friendly format for printing, distribution, conformance and testing. In addition to providing the ability for end-users to provide their own reporting templates, some report types offer "built-in" report templates ready for use. @@ -44,290 +44,3 @@ For example, rendering the name of a part (which is available in the particular

{% endraw %} ``` - -### Context Variables - -!!! info "Context Variables" - Templates will have different variables available to them depending on the report type. Read the detailed information on each available report type for further information. - -Please refer to the [Context variables](./context_variables.md) page. - -### Conditional Rendering - -The django template system allows for conditional rendering, providing conditional flow statements such as: - -``` -{% raw %} -{% if %} -{% do_something %} -{% elif %} - -{% else %} - -{% endif %} -{% endraw %} -``` - -``` -{% raw %} -{% for in %} -Item: {{ item }} -{% endfor %} -{% endraw %} -``` - -!!! info "Conditionals" - Refer to the [django template language documentation]({% include "django.html" %}/ref/templates/language/) for more information. - -### Localization Issues - -Depending on your localization scheme, inputting raw numbers into the formatting section template can cause some unintended issues. Consider the block below which specifies the page size for a rendered template: - -```html -{% raw %} - - - -{% endraw %} -``` - -If localization settings on the InvenTree server use a comma (`,`) character as a decimal separator, this may produce an output like: - -```html -{% raw %} -{% endraw %} - - - -``` - -The resulting `{% raw %} - -{% endraw %} -``` - -!!! tip "Close it out" - Don't forget to end with a `{% raw %}{% endlocalize %}{% endraw %}` tag! - -!!! tip "l10n" - You will need to add `{% raw %}{% load l10n %}{% endraw %}` to the top of your template file to use the `{% raw %}{% localize %}{% endraw %}` tag. - -### Extending with Plugins - -The [ReportMixin plugin class](../extend/plugins/report.md) allows reporting functionality to be extended with custom features. - -## Report Types - -InvenTree supports the following reporting functionality: - -| Report Type | Description | -| --- | --- | -| [Test Report](./test.md) | Format results of a test report against for a particular StockItem | -| [Build Order Report](./build.md) | Format a build order report | -| [Purchase Order Report](./purchase_order.md) | Format a purchase order report | -| [Sales Order Report](./sales_order.md) | Format a sales order report | -| [Return Order Report](./return_order.md) | Format a return order report | -| [Stock Location Report](./stock_location.md) | Format a stock location report | - -### Default Reports - -InvenTree is supplied with a number of default templates "out of the box". These are generally quite simple, but serve as a starting point for building custom reports to suit a specific need. - -!!! tip "Read the Source" - The source code for the default reports is [available on GitHub](https://github.com/inventree/InvenTree/tree/master/src/backend/InvenTree/report/templates/report). Use this as a guide for generating your own reports! - -## Creating Reports - -Report templates are created (and edited) via the [admin interface](../settings/admin.md), under the *Report* section. Select the certain type of report template you are wanting to create, and press the *Add* button in the top right corner: - -{% with id="report-create", url="report/add_report_template.png", description="Create new report" %} -{% include 'img.html' %} -{% endwith %} - -!!! tip "Staff Access Only" - Only users with staff access can upload or edit report template files. - -!!! info "Editing Reports" - Existing reports can be edited from the admin interface, in the same location as described above. To change the contents of the template, re-upload a template file, to override the existing template data. - -### Name and Description - -Each report template requires a name and description, which identify and describe the report template. - -### Enabled Status - -Boolean field which determines if the specific report template is enabled, and available for use. Reports can be disabled to remove them from the list of available templates, but without deleting them from the database. - -### Filename Pattern - -The filename pattern used to generate the output `.pdf` file. Defaults to "report.pdf". - -The filename pattern allows custom rendering with any context variables which are available to the report. For example, a [test report](./test.md) for a particular [Stock Item](../stock/stock.md#stock-item) can use the part name and serial number of the stock item when generating the report name: - -{% with id="report-filename-pattern", url="report/filename_pattern.png", description="Report filename pattern" %} -{% include 'img.html' %} -{% endwith %} - - -### Report Filters - -Each type of report provides a *filters* field, which can be used to filter which items a report can be generated against. The target of the *filters* field depends on the type of report - refer to the documentation on the specific report type for more information. - -For example, the [Test Report](./test.md) filter targets the linked [Stock Item](../stock/status.md) object, and can be used to select which stock items are allowed for the given report. Let's say that a certain test report should only be generated for "trackable" stock items. A filter could easily be constructed to accommodate this, by limiting available items to those where the associated [Part](../part/part.md) is *trackable*: - -{% with id="report-filter-valid", url="report/filters_valid.png", description="Report filter selection" %} -{% include 'img.html' %} -{% endwith %} - -If you enter an invalid option for the filter field, an error message will be displayed: - -{% with id="report-filter-invalid", url="report/filters_invalid.png", description="Invalid filter selection" %} -{% include 'img.html' %} -{% endwith %} - -!!! warning "Advanced Users" - Report filtering is an advanced topic, and requires a little bit of knowledge of the underlying data structure! - -### Metadata - -A JSON field made available to any [plugins](../extend/plugins.md) - but not used by internal code. - -## Report Options - -A number of global reporting options are available for customizing InvenTree reports: - -{% with id="report-options", url="report/report.png", description="Report Options" %} -{% include 'img.html' %} -{% endwith %} - -### Enable Reports - -By default, the reporting feature is disabled. It must be enabled in the global settings. - - -### Default Page Size - -The built-in InvenTree report templates (and any reports which are derived from the built-in templates) use the *Page Size* option to set the page size of the generated reports. - -!!! info "Override Page Size" - Custom report templates do not have to make use of the *Page Size* option, although it is made available to the template context. - -### Debug Mode - -As templates are rendered directly to a PDF object, it can be difficult to debug problems when the PDF does not render exactly as expected. - -Setting the *Debug Mode* option renders the template as raw HTML instead of PDF, allowing the rendering output to be introspected. This feature allows template designers to understand any issues with the generated HTML (before it is passed to the PDF generation engine). - -!!! warning "HTML Rendering Limitations" - When rendered in debug mode, @page attributes (such as size, etc) will **not** be observed. Additionally, any asset files stored on the InvenTree server will not be rendered. Debug mode is not intended to produce "good looking" documents! - -## Report Assets - -User can upload asset files (e.g. images) which can be used when generating reports. For example, you may wish to generate a report with your company logo in the header. Asset files are uploaded via the admin interface. - -Asset files can be rendered directly into the template as follows - -```html -{% raw %} - -{% load report %} - - - - - - - - - - - - - - - -{% endraw %} -``` - -!!! warning "Asset Naming" - If the requested asset name does not match the name of an uploaded asset, the template will continue without loading the image. - -!!! info "Assets location" - You need to ensure your asset images to the report/assets directory in the [data directory](../start/intro.md#file-storage). Upload new assets via the [admin interface](../settings/admin.md) to ensure they are uploaded to the correct location on the server. - - -## Report Snippets - -A powerful feature provided by the django / WeasyPrint templating framework is the ability to include external template files. This allows commonly used template features to be broken out into separate files and re-used across multiple templates. - -To support this, InvenTree provides report "snippets" - short (or not so short) template files which cannot be rendered by themselves, but can be called from other templates. - -Similar to assets files, snippet template files are uploaded via the admin interface. - -Snippets are included in a template as follows: - -``` -{% raw %}{% include 'snippets/' %}{% endraw %} -``` - -For example, consider a stocktake report for a particular stock location, where we wish to render a table with a row for each item in that location. - -```html -{% raw %} - - - - - - - {% for item in location.stock_items %} - {% include 'snippets/stock_row.html' with item=item %} - {% endfor %} - - -{% endraw %} -``` - -!!! info "Snippet Arguments" - Note above that named argument variables can be passed through to the snippet! - -And the snippet file `stock_row.html` may be written as follows: - -```html -{% raw %} - - - - - -{% endraw %} -``` diff --git a/docs/docs/report/return_order.md b/docs/docs/report/return_order.md deleted file mode 100644 index c3403c7f9817..000000000000 --- a/docs/docs/report/return_order.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Return Order Reports ---- - -## Return Order Reports - -Custom reports may be generated against any given [Return Order](../order/return_order.md). For example, return order reports can be used to generate an RMA request to send to a customer. - -### Context Variables - -In addition to the default report context variables, the following context variables are made available to the return order report template for rendering: - -| Variable | Description | -| --- | --- | -| order | The return order object the report is being generated against | -| description | The description of the order, also accessed through `order.description` | -| reference | The reference of the order, also accessed through `order.reference` | -| customer | The customer object related to this order | -| lines | The list of line items linked to this order | -| extra_lines | The list of extra line items linked to this order | - -### Default Report Template - -A default report template is provided out of the box, which can be used as a starting point for developing custom return order report templates. - -View the [source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templates/report/inventree_return_order_report_base.html) for the default return order report template. diff --git a/docs/docs/report/sales_order.md b/docs/docs/report/sales_order.md deleted file mode 100644 index 46e3aeddb534..000000000000 --- a/docs/docs/report/sales_order.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Sales Order Reports ---- - -## Sales Order Reports - -Custom sales order reports may be generated against any given [Sales Order](../order/sales_order.md). For example, a sales order report could be used to generate an invoice to send to a customer. - -### Sales Order Filters - -The report template can be filtered against available [Sales Order](../order/sales_order.md) instances. - -### Context Variables - -In addition to the default report context variables, the following variables are made available to the sales order report template for rendering: - -| Variable | Description | -| --- | --- | -| order | The specific Sales Order object | -| reference | The order reference field (can also be accessed as `{% raw %}{{ order.description }}{% endraw %}`) | -| description | The order description field | -| customer | The [customer](../order/company.md#customers) associated with the particular sales order | -| lines | A list of available line items for this order | -| extra_lines | A list of available *extra* line items for this order | -| order.currency | The currency code associated with this order, e.g. 'CAD' | - -### Default Report Template - -A default *Sales Order Report* template is provided out of the box, which is useful for generating simple test reports. Furthermore, it may be used as a starting point for developing custom BOM reports: - -View the [source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templates/report/inventree_so_report_base.html) for the default sales order report template. diff --git a/docs/docs/report/samples.md b/docs/docs/report/samples.md new file mode 100644 index 000000000000..d6dff5678b4a --- /dev/null +++ b/docs/docs/report/samples.md @@ -0,0 +1,78 @@ +--- +title: Sample Templates +--- + +## Sample Templates + +A number of pre-built templates are provided with InvenTree, which can be used as a starting point for creating custom reports and labels. + +Users can create their own custom templates, or modify the provided templates to suit their needs. + +## Report Templates + +The following report templates are provided "out of the box" and can be used as a starting point, or as a reference for creating custom reports templates: + +| Template | Model Type | Description | +| --- | --- | --- | +| [Bill of Materials](#bill-of-materials-report) | [Part](../part/part.md) | Bill of Materials report | +| [Build Order](#build-order) | [BuildOrder](../build/build.md) | Build Order report | +| [Purchase Order](#purchase-order) | [PurchaseOrder](../order/purchase_order.md) | Purchase Order report | +| [Return Order](#return-order) | [ReturnOrder](../order/return_order.md) | Return Order report | +| [Sales Order](#sales-order) | [SalesOrder](../order/sales_order.md) | Sales Order report | +| [Stock Location](#stock-location) | [StockLocation](../stock/stock.md#stock-location) | Stock Location report | +| [Test Report](#test-report) | [StockItem](../stock/stock.md#stock-item) | Test Report | + +### Bill of Materials Report + +{{ templatefile("report/inventree_bill_of_materials_report.html") }} + +### Build Order + +{{ templatefile("report/inventree_build_order_report.html") }} + +### Purchase Order + +{{ templatefile("report/inventree_bill_of_materials_report.html") }} + +### Return Order + +{{ templatefile("report/inventree_return_order_report.html") }} + +### Sales Order + +{{ templatefile("report/inventree_sales_order_report.html") }} + +### Stock Location + +{{ templatefile("report/inventree_stock_location_report.html") }} + +### Test Report + +{{ templatefile("report/inventree_test_report.html") }} + +## Label Templates + +The following label templates are provided "out of the box" and can be used as a starting point, or as a reference for creating custom label templates: + +| Template | Model Type | Description | +| --- | --- | --- | +| [Build Line](#build-line-label) | [Build line item](../build/build.md) | Build Line label | +| [Part](#part-label) | [Part](../part/part.md) | Part label | +| [Stock Item](#stock-item-label) | [StockItem](../stock/stock.md#stock-item) | Stock Item label | +| [Stock Location](#stock-location-label) | [StockLocation](../stock/stock.md#stock-location) | Stock Location label | + +### Build Line Label + +{{ templatefile("label/buildline_label.html") }} + +### Part Label + +{{ templatefile("label/part_label_code128.html") }} + +### Stock Item Label + +{{ templatefile("label/stockitem_qr.html") }} + +### Stock Location Label + +{{ templatefile("label/stocklocation_qr_and_text.html") }} diff --git a/docs/docs/report/stock_location.md b/docs/docs/report/stock_location.md deleted file mode 100644 index e1712c06d99a..000000000000 --- a/docs/docs/report/stock_location.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Stock Location Reports ---- - -## Stock location Reports - -You can print a formatted report of a stock location. This makes sense if you have several parts inside one location, e.g. a box that is sent out to a manufacturing partner. Whit a report you can create a box content list. - -### Context Variables -You can use all content variables from the [StockLocation](./context_variables.md#stocklocation) object. - -### Default Report Template - -A default report template is provided out of the box, which can be used as a starting point for developing custom return order report templates. - -View the [source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templates/report/inventree_slr_report.html) for the default stock location report template. diff --git a/docs/docs/report/templates.md b/docs/docs/report/templates.md new file mode 100644 index 000000000000..0910532667f2 --- /dev/null +++ b/docs/docs/report/templates.md @@ -0,0 +1,228 @@ +--- +title: InvenTree Templates +--- + +## Template Overview + +InvenTree supports a customizable reporting ecosystem, allowing the user to develop document templates that meet their particular needs. + +PDF files are generated from custom HTML template files which are written by the user. + +Templates can be used to generate *reports* or *labels* which can be used in a variety of situations to format data in a friendly format for printing, distribution, conformance and testing. + +In addition to providing the ability for end-users to provide their own reporting templates, some report types offer "built-in" report templates ready for use. + +## Template Types + +The following types of templates are available: + +### Reports + +Reports are intended to serve as formal documents, and can be used to generate formatted PDF outputs for a variety of purposes. + +Refer to the [report templates](./report.md) documentation for further information. + +### Labels + +Labels can also be generated using the templating system. Labels are intended to be used for printing small, formatted labels for items, parts, locations, etc. + +Refer to the [label templates](./labels.md) documentation for further information. + +### Template Model Types + +When generating a particular template (to render a report or label output), the template is rendered against a particular "model" type. The model type determines the data that is available to the template, and how it is formatted. + +To read more about the model types for which templates can be rendered, and the associated context information, refer to the [context variables](./context_variables.md) documentation. + +### Default Reports + +InvenTree is supplied with a number of default templates "out of the box" - for generating both labels and reports. These are generally quite simple, but serve as a starting point for building custom reports to suit a specific need. + +!!! tip "Read the Source" + The source code for the default reports is [available on GitHub](https://github.com/inventree/InvenTree/tree/master/src/backend/InvenTree/report/templates/report). Use this as a guide for generating your own reports! + +### Extending with Plugins + +The [ReportMixin plugin class](../extend/plugins/report.md) allows reporting functionality to be extended with custom features. + +## WeasyPrint Template Rendering + +InvenTree report templates utilize the powerful [WeasyPrint](https://weasyprint.org/) PDF generation engine. + +To read more about the capabilities of the report templating engine, and how to use it, refer to the [weasyprint documentation](./weasyprint.md). + +## Creating Templates + +Report and label templates can be created (and edited) via the [admin interface](../settings/admin.md), under the *Report* section. + +Select the type of template you are wanting to create (a *Report Template* or *Label Template*) and press the *Add* button in the top right corner: + +{% with id="report-list", url="report/report_template_admin.png", description="Report templates in admin interface" %} +{% include 'img.html' %} +{% endwith %} + +!!! tip "Staff Access Only" + Only users with staff access can upload or edit report template files. + +!!! info "Editing Reports" + Existing reports can be edited from the admin interface, in the same location as described above. To change the contents of the template, re-upload a template file, to override the existing template data. + +!!! tip "Template Editor" + InvenTree also provides a powerful [template editor](./template_editor.md) which allows for the creation and editing of report templates directly within the browser. + +### Name and Description + +Each report template requires a name and description, which identify and describe the report template. + +### Enabled Status + +Boolean field which determines if the specific report template is enabled, and available for use. Reports can be disabled to remove them from the list of available templates, but without deleting them from the database. + +### Filename Pattern + +The filename pattern used to generate the output `.pdf` file. Defaults to "report.pdf". + +The filename pattern allows custom rendering with any context variables which are available to the report. For example, a test report for a particular [Stock Item](../stock/stock.md#stock-item) can use the part name and serial number of the stock item when generating the report name: + +{% with id="report-filename-pattern", url="report/filename_pattern.png", description="Report filename pattern" %} +{% include 'img.html' %} +{% endwith %} + + +### Template Filters + +Each template instance provides a *filters* field, which can be used to filter which items a report or label template can be generated against. The target of the *filters* field depends on the model type associated with the particular template. + +As an example, let's say that a certain `StockItem` report should only be generated for "trackable" stock items. A filter could easily be constructed to accommodate this, by limiting available items to those where the associated [Part](../part/part.md) is *trackable*: + +{% with id="report-filter-valid", url="report/filters_valid.png", description="Report filter selection" %} +{% include 'img.html' %} +{% endwith %} + +If you enter an invalid option for the filter field, an error message will be displayed: + +{% with id="report-filter-invalid", url="report/filters_invalid.png", description="Invalid filter selection" %} +{% include 'img.html' %} +{% endwith %} + +!!! warning "Advanced Users" + Report filtering is an advanced topic, and requires a little bit of knowledge of the underlying data structure! + +### Metadata + +A JSON field made available to any [plugins](../extend/plugins.md) - but not used by internal code. + +## Reporting Options + +A number of global reporting options are available for customizing InvenTree reports: + +{% with id="report-options", url="report/report.png", description="Report Options" %} +{% include 'img.html' %} +{% endwith %} + +### Enable Reports + +By default, the reporting feature is disabled. It must be enabled in the global settings. + + +### Default Page Size + +The built-in InvenTree report templates (and any reports which are derived from the built-in templates) use the *Page Size* option to set the page size of the generated reports. + +!!! info "Override Page Size" + Custom report templates do not have to make use of the *Page Size* option, although it is made available to the template context. + +### Debug Mode + +As templates are rendered directly to a PDF object, it can be difficult to debug problems when the PDF does not render exactly as expected. + +Setting the *Debug Mode* option renders the template as raw HTML instead of PDF, allowing the rendering output to be introspected. This feature allows template designers to understand any issues with the generated HTML (before it is passed to the PDF generation engine). + +!!! warning "HTML Rendering Limitations" + When rendered in debug mode, @page attributes (such as size, etc) will **not** be observed. Additionally, any asset files stored on the InvenTree server will not be rendered. Debug mode is not intended to produce "good looking" documents! + +## Report Assets + +User can upload asset files (e.g. images) which can be used when generating reports. For example, you may wish to generate a report with your company logo in the header. Asset files are uploaded via the admin interface. + +Asset files can be rendered directly into the template as follows + +```html +{% raw %} + +{% load report %} + + + + + + + + + + + + + + + +{% endraw %} +``` + +!!! warning "Asset Naming" + If the requested asset name does not match the name of an uploaded asset, the template will continue without loading the image. + +!!! info "Assets location" + You need to ensure your asset images to the report/assets directory in the [data directory](../start/intro.md#file-storage). Upload new assets via the [admin interface](../settings/admin.md) to ensure they are uploaded to the correct location on the server. + + +## Report Snippets + +A powerful feature provided by the django / WeasyPrint templating framework is the ability to include external template files. This allows commonly used template features to be broken out into separate files and re-used across multiple templates. + +To support this, InvenTree provides report "snippets" - short (or not so short) template files which cannot be rendered by themselves, but can be called from other templates. + +Similar to assets files, snippet template files are uploaded via the admin interface. + +Snippets are included in a template as follows: + +``` +{% raw %}{% include 'snippets/' %}{% endraw %} +``` + +For example, consider a stocktake report for a particular stock location, where we wish to render a table with a row for each item in that location. + +```html +{% raw %} + +
{{ item.part.full_name }}{{ item.quantity }}
+ + + + + {% for item in location.stock_items %} + {% include 'snippets/stock_row.html' with item=item %} + {% endfor %} + + +{% endraw %} +``` + +!!! info "Snippet Arguments" + Note above that named argument variables can be passed through to the snippet! + +And the snippet file `stock_row.html` may be written as follows: + +```html +{% raw %} + + + + + +{% endraw %} +``` diff --git a/docs/docs/report/test.md b/docs/docs/report/test.md deleted file mode 100644 index 7e6dcd67a257..000000000000 --- a/docs/docs/report/test.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: Test Report ---- - -## Test Report - -InvenTree provides [test result](../stock/test.md) tracking functionality which allows the users to keep track of any tests which have been performed on a given [stock item](../stock/stock.md). - -Custom test reports may be generated against any given stock item. All testing data is made available to the template for custom rendering as required. - -For example, an "Acceptance Test" report template may be customized to the particular device, with the results for certain tests rendering in a particular part of the page, with any tests which have not passed highlighted. - -### Stock Item Filters - -A TestReport template may define a set of filters against which stock items are sorted. Any [StockItem](../stock/stock.md) objects which match the provided filters can use the given TestReport. - -This allows each TestReport to easily be assigned to a particular StockItem, or even multiple items. - -In the example below, a test report template is uploaded and available to any stock items linked to a part with the name *"My Widget"*. Any combination of fields relevant to the StockItem model can be used here. - -{% with id="test-report-filters", url="report/test_report_filters.png", description="Test report filters" %} -{% include 'img.html' %} -{% endwith %} - - -### Context Variables - -In addition to the default report context variables, the following context variables are made available to the TestReport template for rendering: - -| Variable | Description | -| --- | --- | -| stock_item | The individual [Stock Item](./context_variables.md#stockitem) object for which this test report is being generated | -| serial | The serial number of the linked Stock Item | -| part | The [Part](./context_variables.md#part) object of which the stock_item is an instance | -| parameters | A dict object representing the [parameters](../part/parameter.md) of the referenced part | -| test_keys | A list of the available 'keys' for the test results recorded against the stock item | -| test_template_list | A list of the available [test templates](../part/test.md#part-test-templates) for the referenced part | -| test_template_map | A map / dict of the available test templates | -| results | A dict of test result objects, where the 'key' for each test result is a shortened version of the test name (see below) | -| result_list | A list of each test result object | -| installed_items | A flattened list representing all [Stock Item](./context_variables.md#stockitem) objects which are *installed inside* the referenced [Stock Item](./context_variables.md#stockitem) object | - -#### Results - -The *results* context variable provides a very convenient method of callout out a particular test result by name. - -#### Example - -Say for example that a Part "Electronic Widget" has a stock item with serial number #123, and has a test result uploaded called "Firmware Checksum". The templated file can reference this data as follows: - -``` html -

Part: {% raw %}{{ part.name }}{% endraw %}

-Serial Number: {% raw %}{{ stock_item.serial }}{% endraw %} -
-

-Firmware Checksum: {% raw %}{{ results.firmwarechecksum.value }}. -Uploaded by {{ results.firmwarechecksum.user }}{% endraw %} -

-``` - -#### Installed Items - -The *installed_items* context variable is a list of all [StockItem](./context_variables.md#stockitem) instances which are installed inside the [StockItem](./context_variables.md#stockitem) referenced by the report template. Each [StockItem](./context_variables.md#stockitem) can be dereferenced as follows: - -```html -{% raw %} -
{{ item.part.full_name }}{{ item.quantity }}
- {% for sub_item in installed_items %} - - - - - - {% endfor %} -
{{ sub_item.full_name }}Serial Number: {{ sub_item.serial }}Pass: {{ sub_item.passedAllRequiredTests }}
-{% endraw %} -``` - -### Default Report Template - -A default *Test Report* template is provided out of the box, which is useful for generating simple test reports. Furthermore, it may be used as a starting point for developing custom test reports: - -{% with id="test-report-example", url="report/test_report_example.png", description="Example Test Report" %} -{% include "img.html" %} -{% endwith %} - -View the [source code](https://github.com/inventree/InvenTree/blob/master/src/backend/InvenTree/report/templates/report/inventree_test_report_base.html) for the default test report template. diff --git a/docs/docs/report/weasyprint.md b/docs/docs/report/weasyprint.md new file mode 100644 index 000000000000..e2aaaccad5f1 --- /dev/null +++ b/docs/docs/report/weasyprint.md @@ -0,0 +1,111 @@ +--- +title: Weasyprint Templates +--- + +## WeasyPrint Templates + +We use the powerful [WeasyPrint](https://weasyprint.org/) PDF generation engine to create custom reports and labels. + +!!! info "WeasyPrint" + WeasyPrint is an extremely powerful and flexible reporting library. Refer to the [WeasyPrint docs](https://doc.courtbouillon.org/weasyprint/stable/) for further information. + +### Stylesheets + +Templates are rendered using standard HTML / CSS - if you are familiar with web page layout, you're ready to go! + +### Template Language + +Uploaded report template files are passed through the [django template rendering framework]({% include "django.html" %}/topics/templates/), and as such accept the same variable template strings as any other django template file. Different variables are passed to the report template (based on the context of the report) and can be used to customize the contents of the generated PDF. + +### Context Variables + +!!! info "Context Variables" + Templates will have different variables available to them depending on the report type. Read the detailed information on each available report type for further information. + +Please refer to the [Context variables](./context_variables.md) page. + + +### Conditional Rendering + +The django template system allows for conditional rendering, providing conditional flow statements such as: + +``` +{% raw %} +{% if %} +{% do_something %} +{% elif %} + +{% else %} + +{% endif %} +{% endraw %} +``` + +``` +{% raw %} +{% for in %} +Item: {{ item }} +{% endfor %} +{% endraw %} +``` + +!!! info "Conditionals" + Refer to the [django template language documentation]({% include "django.html" %}/ref/templates/language/) for more information. + +### Localization Issues + +Depending on your localization scheme, inputting raw numbers into the formatting section template can cause some unintended issues. Consider the block below which specifies the page size for a rendered template: + +```html +{% raw %} + + + +{% endraw %} +``` + +If localization settings on the InvenTree server use a comma (`,`) character as a decimal separator, this may produce an output like: + +```html +{% raw %} +{% endraw %} + + + +``` + +The resulting `{% raw %} + +{% endraw %} +``` + +!!! tip "Close it out" + Don't forget to end with a `{% raw %}{% endlocalize %}{% endraw %}` tag! + +!!! tip "l10n" + You will need to add `{% raw %}{% load l10n %}{% endraw %}` to the top of your template file to use the `{% raw %}{% localize %}{% endraw %}` tag. diff --git a/docs/docs/start/installer.md b/docs/docs/start/installer.md index 721a30fbedbb..450cb58807fc 100644 --- a/docs/docs/start/installer.md +++ b/docs/docs/start/installer.md @@ -171,4 +171,4 @@ The packages are provided by [packager.io](https://packager.io/). They are built The package sets up [services](#controlling-inventree) that run the needed processes as the unprivileged user `inventree`. This keeps the privileges of InvenTree as low as possible. -A CLI is provided to interface with low-level management functions like [variable management](#enviroment-variables), log access, commands, process scaling, etc. +A CLI is provided to interface with low-level management functions like [variable management](#environment-variables), log access, commands, process scaling, etc. diff --git a/docs/main.py b/docs/main.py index ad5c2fe75a1c..129732a0ca40 100644 --- a/docs/main.py +++ b/docs/main.py @@ -1,6 +1,7 @@ """Main entry point for the documentation build process.""" import os +import textwrap def define_env(env): @@ -22,3 +23,29 @@ def listimages(subdir): assets.append(os.path.join(subdir, asset)) return assets + + @env.macro + def templatefile(filename): + """Include code for a provided template file.""" + here = os.path.dirname(__file__) + template_dir = os.path.join( + here, '..', 'src', 'backend', 'InvenTree', 'report', 'templates' + ) + template_file = os.path.join(template_dir, filename) + template_file = os.path.abspath(template_file) + + basename = os.path.basename(filename) + + if not os.path.exists(template_file): + raise FileNotFoundError(f'Report template file {filename} does not exist.') + + with open(template_file, 'r') as f: + content = f.read() + + data = f'??? abstract "Template: {basename}"\n\n' + data += ' ```html\n' + data += textwrap.indent(content, ' ') + data += '\n\n' + data += ' ```\n\n' + + return data diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index c02a03896a96..14c8ddd83275 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -135,25 +135,15 @@ nav: - Return Orders: order/return_order.md - Project Codes: order/project_codes.md - Report: - - Templates: report/report.md + - Templates: report/templates.md + - Template Rendering: report/weasyprint.md - Template Editor: report/template_editor.md - - Report Types: - - Test Reports: report/test.md - - Build Order: report/build.md - - Purchase Order: report/purchase_order.md - - Sales Order: report/sales_order.md - - Return Order: report/return_order.md - - BOM: report/bom.md - - Stock Location: report/stock_location.md - - Labels: - - Custom Labels: report/labels.md - - Part Labels: report/labels/part_labels.md - - Stock Labels: report/labels/stock_labels.md - - Location Labels: report/labels/location_labels.md - - Build Labels: report/labels/build_labels.md + - Reports: report/report.md + - Labels: report/labels.md + - Context Variables: report/context_variables.md - Helper Functions: report/helpers.md - Barcodes: report/barcodes.md - - Context Variables: report/context_variables.md + - Sample Templates: report/samples.md - Admin: - Global Settings: settings/global.md - User Settings: settings/user.md @@ -241,6 +231,7 @@ plugins: on_config: "docs.docs.hooks:on_config" - macros: include_dir: docs/_includes + module_name: main - mkdocstrings: default_handler: python handlers: @@ -250,6 +241,8 @@ plugins: options: show_symbol_type_heading: true show_symbol_type_toc: true + show_root_heading: false + show_root_toc_entry: false # Extensions markdown_extensions: diff --git a/docs/requirements.in b/docs/requirements.in index 303f8bb6f5b3..a2442f381447 100644 --- a/docs/requirements.in +++ b/docs/requirements.in @@ -5,4 +5,4 @@ mkdocs-git-revision-date-localized-plugin>=1.1,<2.0 mkdocs-simple-hooks>=0.1,<1.0 mkdocs-include-markdown-plugin neoteroi-mkdocs -mkdocstrings[python]>=0.24.0 +mkdocstrings[python]>=0.25.0 diff --git a/src/backend/InvenTree/InvenTree/api_version.py b/src/backend/InvenTree/InvenTree/api_version.py index d4bdd7f537a7..0ad025b8a7df 100644 --- a/src/backend/InvenTree/InvenTree/api_version.py +++ b/src/backend/InvenTree/InvenTree/api_version.py @@ -1,12 +1,16 @@ """InvenTree API version information.""" # InvenTree API version -INVENTREE_API_VERSION = 200 +INVENTREE_API_VERSION = 201 """Increment this API version number whenever there is a significant change to the API that any clients need to know about.""" INVENTREE_API_TEXT = """ +v201 - 2024-05-21 : https://github.com/inventree/InvenTree/pull/7074 + - Major refactor of the report template / report printing interface + - This is a *breaking change* to the report template API + v200 - 2024-05-20 : https://github.com/inventree/InvenTree/pull/7000 - Adds API endpoint for generating custom batch codes - Adds API endpoint for generating custom serial numbers diff --git a/src/backend/InvenTree/InvenTree/apps.py b/src/backend/InvenTree/InvenTree/apps.py index 2e90780efa20..c10a2e156e20 100644 --- a/src/backend/InvenTree/InvenTree/apps.py +++ b/src/backend/InvenTree/InvenTree/apps.py @@ -74,6 +74,7 @@ def remove_obsolete_tasks(self): obsolete = [ 'InvenTree.tasks.delete_expired_sessions', 'stock.tasks.delete_old_stock_items', + 'label.tasks.cleanup_old_label_outputs', ] try: @@ -83,7 +84,14 @@ def remove_obsolete_tasks(self): # Remove any existing obsolete tasks try: - Schedule.objects.filter(func__in=obsolete).delete() + obsolete_tasks = Schedule.objects.filter(func__in=obsolete) + + if obsolete_tasks.exists(): + logger.info( + 'Removing %s obsolete background tasks', obsolete_tasks.count() + ) + obsolete_tasks.delete() + except Exception: logger.exception('Failed to remove obsolete tasks - database not ready') diff --git a/src/backend/InvenTree/InvenTree/metadata.py b/src/backend/InvenTree/InvenTree/metadata.py index 9811a41d7c67..242516f59b4b 100644 --- a/src/backend/InvenTree/InvenTree/metadata.py +++ b/src/backend/InvenTree/InvenTree/metadata.py @@ -121,6 +121,16 @@ def get_serializer_info(self, serializer): serializer_info = super().get_serializer_info(serializer) + # Look for any dynamic fields which were not available when the serializer was instantiated + for field_name in serializer.Meta.fields: + if field_name in serializer_info: + # Already know about this one + continue + + if hasattr(serializer, field_name): + field = getattr(serializer, field_name) + serializer_info[field_name] = self.get_field_info(field) + model_class = None # Attributes to copy extra attributes from the model to the field (if they don't exist) @@ -264,7 +274,9 @@ def get_field_info(self, field): # Introspect writable related fields if field_info['type'] == 'field' and not field_info['read_only']: # If the field is a PrimaryKeyRelatedField, we can extract the model from the queryset - if isinstance(field, serializers.PrimaryKeyRelatedField): + if isinstance(field, serializers.PrimaryKeyRelatedField) or issubclass( + field.__class__, serializers.PrimaryKeyRelatedField + ): model = field.queryset.model else: logger.debug( @@ -285,6 +297,9 @@ def get_field_info(self, field): else: field_info['api_url'] = model.get_api_url() + # Handle custom 'primary key' field + field_info['pk_field'] = getattr(field, 'pk_field', 'pk') or 'pk' + # Add more metadata about dependent fields if field_info['type'] == 'dependent field': field_info['depends_on'] = field.depends_on diff --git a/src/backend/InvenTree/InvenTree/settings.py b/src/backend/InvenTree/InvenTree/settings.py index 13da19b11b91..c99da3b461b1 100644 --- a/src/backend/InvenTree/InvenTree/settings.py +++ b/src/backend/InvenTree/InvenTree/settings.py @@ -193,7 +193,6 @@ 'common.apps.CommonConfig', 'company.apps.CompanyConfig', 'plugin.apps.PluginAppConfig', # Plugin app runs before all apps that depend on the isPluginRegistryLoaded function - 'label.apps.LabelConfig', 'order.apps.OrderConfig', 'part.apps.PartConfig', 'report.apps.ReportConfig', @@ -434,12 +433,7 @@ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [ - BASE_DIR.joinpath('templates'), - # Allow templates in the reporting directory to be accessed - MEDIA_ROOT.joinpath('report'), - MEDIA_ROOT.joinpath('label'), - ], + 'DIRS': [BASE_DIR.joinpath('templates'), MEDIA_ROOT.joinpath('report')], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', diff --git a/src/backend/InvenTree/InvenTree/tests.py b/src/backend/InvenTree/InvenTree/tests.py index b0e3e075c2ce..891759c885f5 100644 --- a/src/backend/InvenTree/InvenTree/tests.py +++ b/src/backend/InvenTree/InvenTree/tests.py @@ -1065,7 +1065,8 @@ def test_commit_info(self): subprocess.check_output('git rev-parse --short HEAD'.split()), 'utf-8' ).strip() - self.assertEqual(hash, version.inventreeCommitHash()) + # On some systems the hash is a different length, so just check the first 6 characters + self.assertEqual(hash[:6], version.inventreeCommitHash()[:6]) d = ( str(subprocess.check_output('git show -s --format=%ci'.split()), 'utf-8') diff --git a/src/backend/InvenTree/InvenTree/urls.py b/src/backend/InvenTree/InvenTree/urls.py index bd97236ca69d..e9cd4ead4ca6 100644 --- a/src/backend/InvenTree/InvenTree/urls.py +++ b/src/backend/InvenTree/InvenTree/urls.py @@ -21,7 +21,6 @@ import build.api import common.api import company.api -import label.api import machine.api import order.api import part.api @@ -104,7 +103,7 @@ path('stock/', include(stock.api.stock_api_urls)), path('build/', include(build.api.build_api_urls)), path('order/', include(order.api.order_api_urls)), - path('label/', include(label.api.label_api_urls)), + path('label/', include(report.api.label_api_urls)), path('report/', include(report.api.report_api_urls)), path('machine/', include(machine.api.machine_api_urls)), path('user/', include(users.api.user_urls)), diff --git a/src/backend/InvenTree/build/admin.py b/src/backend/InvenTree/build/admin.py index b3d14c6ec645..1a12166fa4ec 100644 --- a/src/backend/InvenTree/build/admin.py +++ b/src/backend/InvenTree/build/admin.py @@ -18,7 +18,7 @@ class BuildResource(InvenTreeResource): # TODO: 2022-05-12 - Need to investigate why this is the case! class Meta: - """Metaclass options""" + """Metaclass options.""" models = Build skip_unchanged = True report_skipped = False diff --git a/src/backend/InvenTree/build/api.py b/src/backend/InvenTree/build/api.py index 09926ffb237d..e47011ae8b67 100644 --- a/src/backend/InvenTree/build/api.py +++ b/src/backend/InvenTree/build/api.py @@ -30,7 +30,7 @@ class BuildFilter(rest_filters.FilterSet): """Custom filterset for BuildList API endpoint.""" class Meta: - """Metaclass options""" + """Metaclass options.""" model = Build fields = [ 'parent', diff --git a/src/backend/InvenTree/build/migrations/0043_buildline.py b/src/backend/InvenTree/build/migrations/0043_buildline.py index 8da86bc01523..981b533649da 100644 --- a/src/backend/InvenTree/build/migrations/0043_buildline.py +++ b/src/backend/InvenTree/build/migrations/0043_buildline.py @@ -23,6 +23,7 @@ class Migration(migrations.Migration): ], options={ 'unique_together': {('build', 'bom_item')}, + 'verbose_name': 'Build Order Line Item', }, ), ] diff --git a/src/backend/InvenTree/build/models.py b/src/backend/InvenTree/build/models.py index bf878a91bfe9..7257cafda332 100644 --- a/src/backend/InvenTree/build/models.py +++ b/src/backend/InvenTree/build/models.py @@ -38,6 +38,7 @@ from plugin.events import trigger_event import part.models +import report.mixins import stock.models import users.models @@ -45,7 +46,14 @@ logger = logging.getLogger('inventree') -class Build(InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models.InvenTreeNotesMixin, InvenTree.models.MetadataMixin, InvenTree.models.PluginValidationMixin, InvenTree.models.ReferenceIndexingMixin, MPTTModel): +class Build( + report.mixins.InvenTreeReportMixin, + InvenTree.models.InvenTreeBarcodeMixin, + InvenTree.models.InvenTreeNotesMixin, + InvenTree.models.MetadataMixin, + InvenTree.models.PluginValidationMixin, + InvenTree.models.ReferenceIndexingMixin, + MPTTModel): """A Build object organises the creation of new StockItem objects from other existing StockItem objects. Attributes: @@ -139,6 +147,21 @@ def clean(self): 'part': _('Build order part cannot be changed') }) + def report_context(self) -> dict: + """Generate custom report context data.""" + + return { + 'bom_items': self.part.get_bom_items(), + 'build': self, + 'build_outputs': self.build_outputs.all(), + 'line_items': self.build_lines.all(), + 'part': self.part, + 'quantity': self.quantity, + 'reference': self.reference, + 'title': str(self) + } + + @staticmethod def filterByDate(queryset, min_date, max_date): """Filter by 'minimum and maximum date range'. @@ -1291,7 +1314,7 @@ def getSubdir(self): build = models.ForeignKey(Build, on_delete=models.CASCADE, related_name='attachments') -class BuildLine(InvenTree.models.InvenTreeModel): +class BuildLine(report.mixins.InvenTreeReportMixin, InvenTree.models.InvenTreeModel): """A BuildLine object links a BOMItem to a Build. When a new Build is created, the BuildLine objects are created automatically. @@ -1308,7 +1331,8 @@ class BuildLine(InvenTree.models.InvenTreeModel): """ class Meta: - """Model meta options""" + """Model meta options.""" + verbose_name = _('Build Order Line Item') unique_together = [ ('build', 'bom_item'), ] @@ -1318,6 +1342,19 @@ def get_api_url(): """Return the API URL used to access this model""" return reverse('api-build-line-list') + def report_context(self): + """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, + 'build_line': self, + 'part': self.bom_item.sub_part, + 'quantity': self.quantity, + } + build = models.ForeignKey( Build, on_delete=models.CASCADE, related_name='build_lines', help_text=_('Build object') @@ -1384,7 +1421,7 @@ class BuildItem(InvenTree.models.InvenTreeMetadataModel): """ class Meta: - """Model meta options""" + """Model meta options.""" unique_together = [ ('build_line', 'stock_item', 'install_into'), ] diff --git a/src/backend/InvenTree/build/templates/build/build_base.html b/src/backend/InvenTree/build/templates/build/build_base.html index 4ead85bca821..8254673fc79e 100644 --- a/src/backend/InvenTree/build/templates/build/build_base.html +++ b/src/backend/InvenTree/build/templates/build/build_base.html @@ -257,11 +257,7 @@

{% if report_enabled %} $('#print-build-report').click(function() { - printReports({ - items: [{{ build.pk }}], - key: 'build', - url: '{% url "api-build-report-list" %}', - }); + printReports('build', [{{ build.pk }}]); }); {% endif %} diff --git a/src/backend/InvenTree/common/tasks.py b/src/backend/InvenTree/common/tasks.py index 92a666cfe7ad..ffb67311b9f5 100644 --- a/src/backend/InvenTree/common/tasks.py +++ b/src/backend/InvenTree/common/tasks.py @@ -55,7 +55,7 @@ def update_news_feed(): # Fetch and parse feed try: - feed = requests.get(settings.INVENTREE_NEWS_URL) + feed = requests.get(settings.INVENTREE_NEWS_URL, timeout=30) d = feedparser.parse(feed.content) except Exception: # pragma: no cover logger.warning('update_news_feed: Error parsing the newsfeed') diff --git a/src/backend/InvenTree/generic/templating/__init__.py b/src/backend/InvenTree/generic/templating/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/src/backend/InvenTree/generic/templating/apps.py b/src/backend/InvenTree/generic/templating/apps.py deleted file mode 100644 index 1fde7e47e90f..000000000000 --- a/src/backend/InvenTree/generic/templating/apps.py +++ /dev/null @@ -1,134 +0,0 @@ -"""Shared templating code.""" - -import logging -import warnings -from pathlib import Path - -from django.core.exceptions import AppRegistryNotReady -from django.core.files.storage import default_storage -from django.db.utils import IntegrityError, OperationalError, ProgrammingError - -from maintenance_mode.core import maintenance_mode_on, set_maintenance_mode - -import InvenTree.helpers -from InvenTree.config import ensure_dir - -logger = logging.getLogger('inventree') - - -class TemplatingMixin: - """Mixin that contains shared templating code.""" - - name: str = '' - db: str = '' - - def __init__(self, *args, **kwargs): - """Ensure that the required properties are set.""" - super().__init__(*args, **kwargs) - if self.name == '': - raise NotImplementedError('ref must be set') - if self.db == '': - raise NotImplementedError('db must be set') - - def create_defaults(self): - """Function that creates all default templates for the app.""" - raise NotImplementedError('create_defaults must be implemented') - - def get_src_dir(self, ref_name): - """Get the source directory for the default templates.""" - raise NotImplementedError('get_src_dir must be implemented') - - def get_new_obj_data(self, data, filename): - """Get the data for a new template db object.""" - raise NotImplementedError('get_new_obj_data must be implemented') - - # Standardized code - def ready(self): - """This function is called whenever the app is loaded.""" - import InvenTree.ready - - # skip loading if plugin registry is not loaded or we run in a background thread - if ( - not InvenTree.ready.isPluginRegistryLoaded() - or not InvenTree.ready.isInMainThread() - ): - return - - if not InvenTree.ready.canAppAccessDatabase(allow_test=False): - return # pragma: no cover - - with maintenance_mode_on(): - try: - self.create_defaults() - except ( - AppRegistryNotReady, - IntegrityError, - OperationalError, - ProgrammingError, - ): - # Database might not yet be ready - warnings.warn( - f'Database was not ready for creating {self.name}s', stacklevel=2 - ) - - set_maintenance_mode(False) - - def create_template_dir(self, model, data): - """Create folder and database entries for the default templates, if they do not already exist.""" - ref_name = model.getSubdir() - - # Create root dir for templates - src_dir = self.get_src_dir(ref_name) - ensure_dir(Path(self.name, 'inventree', ref_name), default_storage) - - # Copy each template across (if required) - for entry in data: - self.create_template_file(model, src_dir, entry, ref_name) - - def create_template_file(self, model, src_dir, data, ref_name): - """Ensure a label template is in place.""" - # Destination filename - filename = Path(self.name, 'inventree', ref_name, data['file']) - src_file = src_dir.joinpath(data['file']) - - do_copy = False - - if not default_storage.exists(filename): - logger.info("%s template '%s' is not present", self.name, filename) - do_copy = True - else: - # Check if the file contents are different - src_hash = InvenTree.helpers.hash_file(src_file) - dst_hash = InvenTree.helpers.hash_file(filename, default_storage) - - if src_hash != dst_hash: - logger.info("Hash differs for '%s'", filename) - do_copy = True - - if do_copy: - logger.info("Copying %s template '%s'", self.name, filename) - # Ensure destination dir exists - ensure_dir(filename.parent, default_storage) - - # Copy file - default_storage.save(filename, src_file.open('rb')) - - # Check if a file matching the template already exists - try: - if model.objects.filter(**{self.db: filename}).exists(): - return # pragma: no cover - except Exception: - logger.exception( - "Failed to query %s for '%s' - you should run 'invoke update' first!", - self.name, - filename, - ) - - logger.info("Creating entry for %s '%s'", model, data.get('name')) - - try: - model.objects.create(**self.get_new_obj_data(data, str(filename))) - except Exception as _e: - logger.warning( - "Failed to create %s '%s' with error '%s'", self.name, data['name'], _e - ) diff --git a/src/backend/InvenTree/label/__init__.py b/src/backend/InvenTree/label/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/src/backend/InvenTree/label/admin.py b/src/backend/InvenTree/label/admin.py deleted file mode 100644 index fd11629134a1..000000000000 --- a/src/backend/InvenTree/label/admin.py +++ /dev/null @@ -1,17 +0,0 @@ -"""Admin functionality for the 'label' app.""" - -from django.contrib import admin - -import label.models - - -class LabelAdmin(admin.ModelAdmin): - """Admin class for the various label models.""" - - list_display = ('name', 'description', 'label', 'filters', 'enabled') - - -admin.site.register(label.models.StockItemLabel, LabelAdmin) -admin.site.register(label.models.StockLocationLabel, LabelAdmin) -admin.site.register(label.models.PartLabel, LabelAdmin) -admin.site.register(label.models.BuildLineLabel, LabelAdmin) diff --git a/src/backend/InvenTree/label/api.py b/src/backend/InvenTree/label/api.py deleted file mode 100644 index 9cf252b2ebc1..000000000000 --- a/src/backend/InvenTree/label/api.py +++ /dev/null @@ -1,504 +0,0 @@ -"""API functionality for the 'label' app.""" - -from django.core.exceptions import FieldError, ValidationError -from django.http import JsonResponse -from django.urls import include, path, re_path -from django.utils.decorators import method_decorator -from django.utils.translation import gettext_lazy as _ -from django.views.decorators.cache import cache_page, never_cache - -from django_filters.rest_framework import DjangoFilterBackend -from rest_framework import serializers -from rest_framework.exceptions import NotFound -from rest_framework.request import clone_request - -import build.models -import common.models -import InvenTree.exceptions -import InvenTree.helpers -import label.models -import label.serializers -from InvenTree.api import MetadataView -from InvenTree.filters import InvenTreeSearchFilter -from InvenTree.mixins import ListCreateAPI, RetrieveAPI, RetrieveUpdateDestroyAPI -from part.models import Part -from plugin.builtin.labels.inventree_label import InvenTreeLabelPlugin -from plugin.registry import registry -from stock.models import StockItem, StockLocation - - -class LabelFilterMixin: - """Mixin for filtering a queryset by a list of object ID values. - - Each implementing class defines a database model to lookup, - and a "key" (query parameter) for providing a list of ID (PK) values. - - This mixin defines a 'get_items' method which provides a generic - implementation to return a list of matching database model instances. - """ - - # Database model for instances to actually be "printed" against this label template - ITEM_MODEL = None - - # Default key for looking up database model instances - ITEM_KEY = 'item' - - def get_items(self): - """Return a list of database objects from query parameter.""" - ids = [] - - # Construct a list of possible query parameter value options - # e.g. if self.ITEM_KEY = 'part' -> ['part', 'part[]', 'parts', parts[]'] - for k in [self.ITEM_KEY + x for x in ['', '[]', 's', 's[]']]: - if ids := self.request.query_params.getlist(k, []): - # Return the first list of matches - break - - # Next we must validate each provided object ID - valid_ids = [] - - for id in ids: - try: - valid_ids.append(int(id)) - except ValueError: - pass - - # Filter queryset by matching ID values - return self.ITEM_MODEL.objects.filter(pk__in=valid_ids) - - -class LabelListView(LabelFilterMixin, ListCreateAPI): - """Generic API class for label templates.""" - - def filter_queryset(self, queryset): - """Filter the queryset based on the provided label ID values. - - As each 'label' instance may optionally define its own filters, - the resulting queryset is the 'union' of the two. - """ - queryset = super().filter_queryset(queryset) - - items = self.get_items() - - if len(items) > 0: - """ - At this point, we are basically forced to be inefficient, - as we need to compare the 'filters' string of each label, - and see if it matches against each of the requested items. - - TODO: In the future, if this becomes excessively slow, it - will need to be readdressed. - """ - valid_label_ids = set() - - for lbl in queryset.all(): - matches = True - - try: - filters = InvenTree.helpers.validateFilterString(lbl.filters) - except ValidationError: - continue - - for item in items: - item_query = self.ITEM_MODEL.objects.filter(pk=item.pk) - - try: - if not item_query.filter(**filters).exists(): - matches = False - break - except FieldError: - matches = False - break - - # Matched all items - if matches: - valid_label_ids.add(lbl.pk) - else: - continue - - # Reduce queryset to only valid matches - queryset = queryset.filter(pk__in=list(valid_label_ids)) - - return queryset - - filter_backends = [DjangoFilterBackend, InvenTreeSearchFilter] - - filterset_fields = ['enabled'] - - search_fields = ['name', 'description'] - - -@method_decorator(cache_page(5), name='dispatch') -class LabelPrintMixin(LabelFilterMixin): - """Mixin for printing labels.""" - - rolemap = {'GET': 'view', 'POST': 'view'} - - def check_permissions(self, request): - """Override request method to GET so that also non superusers can print using a post request.""" - if request.method == 'POST': - request = clone_request(request, 'GET') - return super().check_permissions(request) - - @method_decorator(never_cache) - def dispatch(self, *args, **kwargs): - """Prevent caching when printing report templates.""" - return super().dispatch(*args, **kwargs) - - def get_serializer(self, *args, **kwargs): - """Define a get_serializer method to be discoverable by the OPTIONS request.""" - # Check the request to determine if the user has selected a label printing plugin - plugin = self.get_plugin(self.request) - - kwargs.setdefault('context', self.get_serializer_context()) - serializer = plugin.get_printing_options_serializer( - self.request, *args, **kwargs - ) - - # if no serializer is defined, return an empty serializer - if not serializer: - return serializers.Serializer() - - return serializer - - def get(self, request, *args, **kwargs): - """Perform a GET request against this endpoint to print labels.""" - common.models.InvenTreeUserSetting.set_setting( - 'DEFAULT_' + self.ITEM_KEY.upper() + '_LABEL_TEMPLATE', - self.get_object().pk, - None, - user=request.user, - ) - return self.print(request, self.get_items()) - - def post(self, request, *args, **kwargs): - """Perform a GET request against this endpoint to print labels.""" - return self.get(request, *args, **kwargs) - - def get_plugin(self, request): - """Return the label printing plugin associated with this request. - - This is provided in the url, e.g. ?plugin=myprinter - - Requires: - - settings.PLUGINS_ENABLED is True - - matching plugin can be found - - matching plugin implements the 'labels' mixin - - matching plugin is enabled - """ - plugin_key = request.query_params.get('plugin', None) - - # No plugin provided! - if plugin_key is None: - # Default to the builtin label printing plugin - plugin_key = InvenTreeLabelPlugin.NAME.lower() - - plugin = registry.get_plugin(plugin_key) - - if not plugin: - raise NotFound(f"Plugin '{plugin_key}' not found") - - if not plugin.is_active(): - raise ValidationError(f"Plugin '{plugin_key}' is not enabled") - - if not plugin.mixin_enabled('labels'): - raise ValidationError( - f"Plugin '{plugin_key}' is not a label printing plugin" - ) - - # Only return the plugin if it is enabled and has the label printing mixin - return plugin - - def print(self, request, items_to_print): - """Print this label template against a number of pre-validated items.""" - # Check the request to determine if the user has selected a label printing plugin - plugin = self.get_plugin(request) - - if len(items_to_print) == 0: - # No valid items provided, return an error message - raise ValidationError('No valid objects provided to label template') - - # Label template - label = self.get_object() - - # Check the label dimensions - if label.width <= 0 or label.height <= 0: - raise ValidationError('Label has invalid dimensions') - - # if the plugin returns a serializer, validate the data - if serializer := plugin.get_printing_options_serializer( - request, data=request.data, context=self.get_serializer_context() - ): - serializer.is_valid(raise_exception=True) - - # At this point, we offload the label(s) to the selected plugin. - # The plugin is responsible for handling the request and returning a response. - - try: - result = plugin.print_labels( - label, - items_to_print, - request, - printing_options=(serializer.data if serializer else {}), - ) - except ValidationError as e: - raise (e) - except Exception as e: - raise ValidationError([_('Error printing label'), str(e)]) - - if isinstance(result, JsonResponse): - result['plugin'] = plugin.plugin_slug() - return result - raise ValidationError( - f"Plugin '{plugin.plugin_slug()}' returned invalid response type '{type(result)}'" - ) - - -class StockItemLabelMixin: - """Mixin for StockItemLabel endpoints.""" - - queryset = label.models.StockItemLabel.objects.all() - serializer_class = label.serializers.StockItemLabelSerializer - - ITEM_MODEL = StockItem - ITEM_KEY = 'item' - - -class StockItemLabelList(StockItemLabelMixin, LabelListView): - """API endpoint for viewing list of StockItemLabel objects. - - Filterable by: - - - enabled: Filter by enabled / disabled status - - item: Filter by single stock item - - items: Filter by list of stock items - """ - - pass - - -class StockItemLabelDetail(StockItemLabelMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single StockItemLabel object.""" - - pass - - -class StockItemLabelPrint(StockItemLabelMixin, LabelPrintMixin, RetrieveAPI): - """API endpoint for printing a StockItemLabel object.""" - - pass - - -class StockLocationLabelMixin: - """Mixin for StockLocationLabel endpoints.""" - - queryset = label.models.StockLocationLabel.objects.all() - serializer_class = label.serializers.StockLocationLabelSerializer - - ITEM_MODEL = StockLocation - ITEM_KEY = 'location' - - -class StockLocationLabelList(StockLocationLabelMixin, LabelListView): - """API endpoint for viewiing list of StockLocationLabel objects. - - Filterable by: - - - enabled: Filter by enabled / disabled status - - location: Filter by a single stock location - - locations: Filter by list of stock locations - """ - - pass - - -class StockLocationLabelDetail(StockLocationLabelMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single StockLocationLabel object.""" - - pass - - -class StockLocationLabelPrint(StockLocationLabelMixin, LabelPrintMixin, RetrieveAPI): - """API endpoint for printing a StockLocationLabel object.""" - - pass - - -class PartLabelMixin: - """Mixin for PartLabel endpoints.""" - - queryset = label.models.PartLabel.objects.all() - serializer_class = label.serializers.PartLabelSerializer - - ITEM_MODEL = Part - ITEM_KEY = 'part' - - -class PartLabelList(PartLabelMixin, LabelListView): - """API endpoint for viewing list of PartLabel objects.""" - - pass - - -class PartLabelDetail(PartLabelMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single PartLabel object.""" - - pass - - -class PartLabelPrint(PartLabelMixin, LabelPrintMixin, RetrieveAPI): - """API endpoint for printing a PartLabel object.""" - - pass - - -class BuildLineLabelMixin: - """Mixin class for BuildLineLabel endpoints.""" - - queryset = label.models.BuildLineLabel.objects.all() - serializer_class = label.serializers.BuildLineLabelSerializer - - ITEM_MODEL = build.models.BuildLine - ITEM_KEY = 'line' - - -class BuildLineLabelList(BuildLineLabelMixin, LabelListView): - """API endpoint for viewing a list of BuildLineLabel objects.""" - - pass - - -class BuildLineLabelDetail(BuildLineLabelMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single BuildLineLabel object.""" - - pass - - -class BuildLineLabelPrint(BuildLineLabelMixin, LabelPrintMixin, RetrieveAPI): - """API endpoint for printing a BuildLineLabel object.""" - - pass - - -label_api_urls = [ - # Stock item labels - path( - 'stock/', - include([ - # Detail views - path( - '/', - include([ - re_path( - r'print/?', - StockItemLabelPrint.as_view(), - name='api-stockitem-label-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'model': label.models.StockItemLabel}, - name='api-stockitem-label-metadata', - ), - path( - '', - StockItemLabelDetail.as_view(), - name='api-stockitem-label-detail', - ), - ]), - ), - # List view - path('', StockItemLabelList.as_view(), name='api-stockitem-label-list'), - ]), - ), - # Stock location labels - path( - 'location/', - include([ - # Detail views - path( - '/', - include([ - re_path( - r'print/?', - StockLocationLabelPrint.as_view(), - name='api-stocklocation-label-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'model': label.models.StockLocationLabel}, - name='api-stocklocation-label-metadata', - ), - path( - '', - StockLocationLabelDetail.as_view(), - name='api-stocklocation-label-detail', - ), - ]), - ), - # List view - path( - '', - StockLocationLabelList.as_view(), - name='api-stocklocation-label-list', - ), - ]), - ), - # Part labels - path( - 'part/', - include([ - # Detail views - path( - '/', - include([ - re_path( - r'print/?', - PartLabelPrint.as_view(), - name='api-part-label-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'model': label.models.PartLabel}, - name='api-part-label-metadata', - ), - path('', PartLabelDetail.as_view(), name='api-part-label-detail'), - ]), - ), - # List view - path('', PartLabelList.as_view(), name='api-part-label-list'), - ]), - ), - # BuildLine labels - path( - 'buildline/', - include([ - # Detail views - path( - '/', - include([ - re_path( - r'print/?', - BuildLineLabelPrint.as_view(), - name='api-buildline-label-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'model': label.models.BuildLineLabel}, - name='api-buildline-label-metadata', - ), - path( - '', - BuildLineLabelDetail.as_view(), - name='api-buildline-label-detail', - ), - ]), - ), - # List view - path('', BuildLineLabelList.as_view(), name='api-buildline-label-list'), - ]), - ), -] diff --git a/src/backend/InvenTree/label/apps.py b/src/backend/InvenTree/label/apps.py deleted file mode 100644 index 583d2a2591f6..000000000000 --- a/src/backend/InvenTree/label/apps.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Config options for the label app.""" - -from pathlib import Path - -from django.apps import AppConfig - -from generic.templating.apps import TemplatingMixin - - -class LabelConfig(TemplatingMixin, AppConfig): - """Configuration class for the "label" app.""" - - name = 'label' - db = 'label' - - def create_defaults(self): - """Create all default templates.""" - # Test if models are ready - try: - import label.models - except Exception: # pragma: no cover - # Database is not ready yet - return - assert bool(label.models.StockLocationLabel is not None) - - # Create the categories - self.create_template_dir( - label.models.StockItemLabel, - [ - { - 'file': 'qr.html', - 'name': 'QR Code', - 'description': 'Simple QR code label', - 'width': 24, - 'height': 24, - } - ], - ) - - self.create_template_dir( - label.models.StockLocationLabel, - [ - { - 'file': 'qr.html', - 'name': 'QR Code', - 'description': 'Simple QR code label', - 'width': 24, - 'height': 24, - }, - { - 'file': 'qr_and_text.html', - 'name': 'QR and text', - 'description': 'Label with QR code and name of location', - 'width': 50, - 'height': 24, - }, - ], - ) - - self.create_template_dir( - label.models.PartLabel, - [ - { - 'file': 'part_label.html', - 'name': 'Part Label', - 'description': 'Simple part label', - 'width': 70, - 'height': 24, - }, - { - 'file': 'part_label_code128.html', - 'name': 'Barcode Part Label', - 'description': 'Simple part label with Code128 barcode', - 'width': 70, - 'height': 24, - }, - ], - ) - - self.create_template_dir( - label.models.BuildLineLabel, - [ - { - 'file': 'buildline_label.html', - 'name': 'Build Line Label', - 'description': 'Example build line label', - 'width': 125, - 'height': 48, - } - ], - ) - - def get_src_dir(self, ref_name): - """Get the source directory.""" - return Path(__file__).parent.joinpath('templates', self.name, ref_name) - - def get_new_obj_data(self, data, filename): - """Get the data for a new template db object.""" - return { - 'name': data['name'], - 'description': data['description'], - 'label': filename, - 'filters': '', - 'enabled': True, - 'width': data['width'], - 'height': data['height'], - } diff --git a/src/backend/InvenTree/label/migrations/0001_initial.py b/src/backend/InvenTree/label/migrations/0001_initial.py deleted file mode 100644 index e960bcef67b5..000000000000 --- a/src/backend/InvenTree/label/migrations/0001_initial.py +++ /dev/null @@ -1,30 +0,0 @@ -# Generated by Django 3.0.7 on 2020-08-15 23:27 - -import InvenTree.helpers -import django.core.validators -from django.db import migrations, models -import label.models - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ] - - operations = [ - migrations.CreateModel( - name='StockItemLabel', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(help_text='Label name', max_length=100, unique=True)), - ('description', models.CharField(blank=True, help_text='Label description', max_length=250, null=True)), - ('label', models.FileField(help_text='Label template file', upload_to=label.models.rename_label, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html'])])), - ('filters', models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs', max_length=250, validators=[InvenTree.helpers.validateFilterString])), - ], - options={ - 'abstract': False, - }, - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0002_stockitemlabel_enabled.py b/src/backend/InvenTree/label/migrations/0002_stockitemlabel_enabled.py deleted file mode 100644 index 684299e18424..000000000000 --- a/src/backend/InvenTree/label/migrations/0002_stockitemlabel_enabled.py +++ /dev/null @@ -1,18 +0,0 @@ -# Generated by Django 3.0.7 on 2020-08-22 23:04 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0001_initial'), - ] - - operations = [ - migrations.AddField( - model_name='stockitemlabel', - name='enabled', - field=models.BooleanField(default=True, help_text='Label template is enabled', verbose_name='Enabled'), - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0003_stocklocationlabel.py b/src/backend/InvenTree/label/migrations/0003_stocklocationlabel.py deleted file mode 100644 index d15fcfa396bc..000000000000 --- a/src/backend/InvenTree/label/migrations/0003_stocklocationlabel.py +++ /dev/null @@ -1,30 +0,0 @@ -# Generated by Django 3.0.7 on 2021-01-08 12:06 - -import InvenTree.helpers -import django.core.validators -from django.db import migrations, models -import label.models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0002_stockitemlabel_enabled'), - ] - - operations = [ - migrations.CreateModel( - name='StockLocationLabel', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(help_text='Label name', max_length=100, unique=True)), - ('description', models.CharField(blank=True, help_text='Label description', max_length=250, null=True)), - ('label', models.FileField(help_text='Label template file', upload_to=label.models.rename_label, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html'])])), - ('filters', models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs', max_length=250, validators=[InvenTree.helpers.validateFilterString])), - ('enabled', models.BooleanField(default=True, help_text='Label template is enabled', verbose_name='Enabled')), - ], - options={ - 'abstract': False, - }, - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0004_auto_20210111_2302.py b/src/backend/InvenTree/label/migrations/0004_auto_20210111_2302.py deleted file mode 100644 index 5194a4bda1d1..000000000000 --- a/src/backend/InvenTree/label/migrations/0004_auto_20210111_2302.py +++ /dev/null @@ -1,56 +0,0 @@ -# Generated by Django 3.0.7 on 2021-01-11 12:02 - -import InvenTree.helpers -import django.core.validators -from django.db import migrations, models -import label.models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0003_stocklocationlabel'), - ] - - operations = [ - migrations.AlterField( - model_name='stockitemlabel', - name='description', - field=models.CharField(blank=True, help_text='Label description', max_length=250, null=True, verbose_name='Description'), - ), - migrations.AlterField( - model_name='stockitemlabel', - name='filters', - field=models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs', max_length=250, validators=[InvenTree.helpers.validateFilterString], verbose_name='Filters'), - ), - migrations.AlterField( - model_name='stockitemlabel', - name='label', - field=models.FileField(help_text='Label template file', unique=True, upload_to=label.models.rename_label, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html'])], verbose_name='Label'), - ), - migrations.AlterField( - model_name='stockitemlabel', - name='name', - field=models.CharField(help_text='Label name', max_length=100, verbose_name='Name'), - ), - migrations.AlterField( - model_name='stocklocationlabel', - name='description', - field=models.CharField(blank=True, help_text='Label description', max_length=250, null=True, verbose_name='Description'), - ), - migrations.AlterField( - model_name='stocklocationlabel', - name='filters', - field=models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs', max_length=250, validators=[InvenTree.helpers.validateFilterString], verbose_name='Filters'), - ), - migrations.AlterField( - model_name='stocklocationlabel', - name='label', - field=models.FileField(help_text='Label template file', unique=True, upload_to=label.models.rename_label, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html'])], verbose_name='Label'), - ), - migrations.AlterField( - model_name='stocklocationlabel', - name='name', - field=models.CharField(help_text='Label name', max_length=100, verbose_name='Name'), - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0005_auto_20210113_2302.py b/src/backend/InvenTree/label/migrations/0005_auto_20210113_2302.py deleted file mode 100644 index ad256412acc4..000000000000 --- a/src/backend/InvenTree/label/migrations/0005_auto_20210113_2302.py +++ /dev/null @@ -1,24 +0,0 @@ -# Generated by Django 3.0.7 on 2021-01-13 12:02 - -from django.db import migrations, models -import label.models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0004_auto_20210111_2302'), - ] - - operations = [ - migrations.AlterField( - model_name='stockitemlabel', - name='filters', - field=models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs', max_length=250, validators=[label.models.validate_stock_item_filters], verbose_name='Filters'), - ), - migrations.AlterField( - model_name='stocklocationlabel', - name='filters', - field=models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs', max_length=250, validators=[label.models.validate_stock_location_filters], verbose_name='Filters'), - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0006_auto_20210222_1535.py b/src/backend/InvenTree/label/migrations/0006_auto_20210222_1535.py deleted file mode 100644 index ea3441b64fa1..000000000000 --- a/src/backend/InvenTree/label/migrations/0006_auto_20210222_1535.py +++ /dev/null @@ -1,34 +0,0 @@ -# Generated by Django 3.0.7 on 2021-02-22 04:35 - -import django.core.validators -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0005_auto_20210113_2302'), - ] - - operations = [ - migrations.AddField( - model_name='stockitemlabel', - name='height', - field=models.FloatField(default=20, help_text='Label height, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Height [mm]'), - ), - migrations.AddField( - model_name='stockitemlabel', - name='width', - field=models.FloatField(default=50, help_text='Label width, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Width [mm]'), - ), - migrations.AddField( - model_name='stocklocationlabel', - name='height', - field=models.FloatField(default=20, help_text='Label height, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Height [mm]'), - ), - migrations.AddField( - model_name='stocklocationlabel', - name='width', - field=models.FloatField(default=50, help_text='Label width, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Width [mm]'), - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0007_auto_20210513_1327.py b/src/backend/InvenTree/label/migrations/0007_auto_20210513_1327.py deleted file mode 100644 index d49c83c92b58..000000000000 --- a/src/backend/InvenTree/label/migrations/0007_auto_20210513_1327.py +++ /dev/null @@ -1,23 +0,0 @@ -# Generated by Django 3.2 on 2021-05-13 03:27 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0006_auto_20210222_1535'), - ] - - operations = [ - migrations.AddField( - model_name='stockitemlabel', - name='filename_pattern', - field=models.CharField(default='label.pdf', help_text='Pattern for generating label filenames', max_length=100, verbose_name='Filename Pattern'), - ), - migrations.AddField( - model_name='stocklocationlabel', - name='filename_pattern', - field=models.CharField(default='label.pdf', help_text='Pattern for generating label filenames', max_length=100, verbose_name='Filename Pattern'), - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0008_auto_20210708_2106.py b/src/backend/InvenTree/label/migrations/0008_auto_20210708_2106.py deleted file mode 100644 index ea575269097f..000000000000 --- a/src/backend/InvenTree/label/migrations/0008_auto_20210708_2106.py +++ /dev/null @@ -1,37 +0,0 @@ -# Generated by Django 3.2.4 on 2021-07-08 11:06 - -import django.core.validators -from django.db import migrations, models -import label.models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0007_auto_20210513_1327'), - ] - - operations = [ - migrations.CreateModel( - name='PartLabel', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('name', models.CharField(help_text='Label name', max_length=100, verbose_name='Name')), - ('description', models.CharField(blank=True, help_text='Label description', max_length=250, null=True, verbose_name='Description')), - ('label', models.FileField(help_text='Label template file', unique=True, upload_to=label.models.rename_label, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html'])], verbose_name='Label')), - ('enabled', models.BooleanField(default=True, help_text='Label template is enabled', verbose_name='Enabled')), - ('width', models.FloatField(default=50, help_text='Label width, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Width [mm]')), - ('height', models.FloatField(default=20, help_text='Label height, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Height [mm]')), - ('filename_pattern', models.CharField(default='label.pdf', help_text='Pattern for generating label filenames', max_length=100, verbose_name='Filename Pattern')), - ('filters', models.CharField(blank=True, help_text='Part query filters (comma-separated value of key=value pairs)', max_length=250, validators=[label.models.validate_part_filters], verbose_name='Filters')), - ], - options={ - 'abstract': False, - }, - ), - migrations.AlterField( - model_name='stockitemlabel', - name='filters', - field=models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs),', max_length=250, validators=[label.models.validate_stock_item_filters], verbose_name='Filters'), - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0009_auto_20230317_0816.py b/src/backend/InvenTree/label/migrations/0009_auto_20230317_0816.py deleted file mode 100644 index 16b81a5f7f02..000000000000 --- a/src/backend/InvenTree/label/migrations/0009_auto_20230317_0816.py +++ /dev/null @@ -1,28 +0,0 @@ -# Generated by Django 3.2.18 on 2023-03-17 08:16 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0008_auto_20210708_2106'), - ] - - operations = [ - migrations.AddField( - model_name='partlabel', - name='metadata', - field=models.JSONField(blank=True, help_text='JSON metadata field, for use by external plugins', null=True, verbose_name='Plugin Metadata'), - ), - migrations.AddField( - model_name='stockitemlabel', - name='metadata', - field=models.JSONField(blank=True, help_text='JSON metadata field, for use by external plugins', null=True, verbose_name='Plugin Metadata'), - ), - migrations.AddField( - model_name='stocklocationlabel', - name='metadata', - field=models.JSONField(blank=True, help_text='JSON metadata field, for use by external plugins', null=True, verbose_name='Plugin Metadata'), - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0010_buildlinelabel.py b/src/backend/InvenTree/label/migrations/0010_buildlinelabel.py deleted file mode 100644 index 329c2743670b..000000000000 --- a/src/backend/InvenTree/label/migrations/0010_buildlinelabel.py +++ /dev/null @@ -1,33 +0,0 @@ -# Generated by Django 3.2.19 on 2023-06-13 11:10 - -import django.core.validators -from django.db import migrations, models -import label.models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0009_auto_20230317_0816'), - ] - - operations = [ - migrations.CreateModel( - name='BuildLineLabel', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('metadata', models.JSONField(blank=True, help_text='JSON metadata field, for use by external plugins', null=True, verbose_name='Plugin Metadata')), - ('name', models.CharField(help_text='Label name', max_length=100, verbose_name='Name')), - ('description', models.CharField(blank=True, help_text='Label description', max_length=250, null=True, verbose_name='Description')), - ('label', models.FileField(help_text='Label template file', unique=True, upload_to=label.models.rename_label, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html'])], verbose_name='Label')), - ('enabled', models.BooleanField(default=True, help_text='Label template is enabled', verbose_name='Enabled')), - ('width', models.FloatField(default=50, help_text='Label width, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Width [mm]')), - ('height', models.FloatField(default=20, help_text='Label height, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Height [mm]')), - ('filename_pattern', models.CharField(default='label.pdf', help_text='Pattern for generating label filenames', max_length=100, verbose_name='Filename Pattern')), - ('filters', models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs)', max_length=250, validators=[label.models.validate_build_line_filters], verbose_name='Filters')), - ], - options={ - 'abstract': False, - }, - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0011_auto_20230623_2158.py b/src/backend/InvenTree/label/migrations/0011_auto_20230623_2158.py deleted file mode 100644 index 764925fc07ff..000000000000 --- a/src/backend/InvenTree/label/migrations/0011_auto_20230623_2158.py +++ /dev/null @@ -1,29 +0,0 @@ -# Generated by Django 3.2.19 on 2023-06-23 21:58 - -from django.db import migrations, models -import label.models - - -class Migration(migrations.Migration): - - dependencies = [ - ('label', '0010_buildlinelabel'), - ] - - operations = [ - migrations.AlterField( - model_name='partlabel', - name='filters', - field=models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs)', max_length=250, validators=[label.models.validate_part_filters], verbose_name='Filters'), - ), - migrations.AlterField( - model_name='stockitemlabel', - name='filters', - field=models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs)', max_length=250, validators=[label.models.validate_stock_item_filters], verbose_name='Filters'), - ), - migrations.AlterField( - model_name='stocklocationlabel', - name='filters', - field=models.CharField(blank=True, help_text='Query filters (comma-separated list of key=value pairs)', max_length=250, validators=[label.models.validate_stock_location_filters], verbose_name='Filters'), - ), - ] diff --git a/src/backend/InvenTree/label/migrations/0012_labeloutput.py b/src/backend/InvenTree/label/migrations/0012_labeloutput.py deleted file mode 100644 index 3a69fb9a9b50..000000000000 --- a/src/backend/InvenTree/label/migrations/0012_labeloutput.py +++ /dev/null @@ -1,26 +0,0 @@ -# Generated by Django 3.2.20 on 2023-07-14 11:55 - -from django.conf import settings -from django.db import migrations, models -import django.db.models.deletion -import label.models - - -class Migration(migrations.Migration): - - dependencies = [ - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ('label', '0011_auto_20230623_2158'), - ] - - operations = [ - migrations.CreateModel( - name='LabelOutput', - fields=[ - ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('label', models.FileField(unique=True, upload_to=label.models.rename_label_output)), - ('created', models.DateField(auto_now_add=True)), - ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)), - ], - ), - ] diff --git a/src/backend/InvenTree/label/migrations/__init__.py b/src/backend/InvenTree/label/migrations/__init__.py deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/src/backend/InvenTree/label/models.py b/src/backend/InvenTree/label/models.py deleted file mode 100644 index 17cc252afb26..000000000000 --- a/src/backend/InvenTree/label/models.py +++ /dev/null @@ -1,429 +0,0 @@ -"""Label printing models.""" - -import logging -import os -import sys - -from django.conf import settings -from django.contrib.auth.models import User -from django.core.validators import FileExtensionValidator, MinValueValidator -from django.db import models -from django.template import Context, Template -from django.template.loader import render_to_string -from django.urls import reverse -from django.utils.translation import gettext_lazy as _ - -import build.models -import InvenTree.helpers -import InvenTree.models -import part.models -import stock.models -from InvenTree.helpers import normalize, validateFilterString -from InvenTree.helpers_model import get_base_url -from plugin.registry import registry - -try: - from django_weasyprint import WeasyTemplateResponseMixin -except OSError as err: # pragma: no cover - print(f'OSError: {err}') - print('You may require some further system packages to be installed.') - sys.exit(1) - - -logger = logging.getLogger('inventree') - - -def rename_label(instance, filename): - """Place the label file into the correct subdirectory.""" - filename = os.path.basename(filename) - - return os.path.join('label', 'template', instance.SUBDIR, filename) - - -def rename_label_output(instance, filename): - """Place the label output file into the correct subdirectory.""" - filename = os.path.basename(filename) - - return os.path.join('label', 'output', filename) - - -def validate_stock_item_filters(filters): - """Validate query filters for the StockItemLabel model.""" - filters = validateFilterString(filters, model=stock.models.StockItem) - - return filters - - -def validate_stock_location_filters(filters): - """Validate query filters for the StockLocationLabel model.""" - filters = validateFilterString(filters, model=stock.models.StockLocation) - - return filters - - -def validate_part_filters(filters): - """Validate query filters for the PartLabel model.""" - filters = validateFilterString(filters, model=part.models.Part) - - return filters - - -def validate_build_line_filters(filters): - """Validate query filters for the BuildLine model.""" - filters = validateFilterString(filters, model=build.models.BuildLine) - - return filters - - -class WeasyprintLabelMixin(WeasyTemplateResponseMixin): - """Class for rendering a label to a PDF.""" - - pdf_filename = 'label.pdf' - pdf_attachment = True - - def __init__(self, request, template, **kwargs): - """Initialize a label mixin with certain properties.""" - self.request = request - self.template_name = template - self.pdf_filename = kwargs.get('filename', 'label.pdf') - - -class LabelTemplate(InvenTree.models.InvenTreeMetadataModel): - """Base class for generic, filterable labels.""" - - class Meta: - """Metaclass options. Abstract ensures no database table is created.""" - - abstract = True - - @classmethod - def getSubdir(cls) -> str: - """Return the subdirectory for this label.""" - return cls.SUBDIR - - # Each class of label files will be stored in a separate subdirectory - SUBDIR: str = 'label' - - # Object we will be printing against (will be filled out later) - object_to_print = None - - @property - def template(self): - """Return the file path of the template associated with this label instance.""" - return self.label.path - - def __str__(self): - """Format a string representation of a label instance.""" - return f'{self.name} - {self.description}' - - name = models.CharField( - blank=False, max_length=100, verbose_name=_('Name'), help_text=_('Label name') - ) - - description = models.CharField( - max_length=250, - blank=True, - null=True, - verbose_name=_('Description'), - help_text=_('Label description'), - ) - - label = models.FileField( - upload_to=rename_label, - unique=True, - blank=False, - null=False, - verbose_name=_('Label'), - help_text=_('Label template file'), - validators=[FileExtensionValidator(allowed_extensions=['html'])], - ) - - enabled = models.BooleanField( - default=True, - verbose_name=_('Enabled'), - help_text=_('Label template is enabled'), - ) - - width = models.FloatField( - default=50, - verbose_name=_('Width [mm]'), - help_text=_('Label width, specified in mm'), - validators=[MinValueValidator(2)], - ) - - height = models.FloatField( - default=20, - verbose_name=_('Height [mm]'), - help_text=_('Label height, specified in mm'), - validators=[MinValueValidator(2)], - ) - - filename_pattern = models.CharField( - default='label.pdf', - verbose_name=_('Filename Pattern'), - help_text=_('Pattern for generating label filenames'), - max_length=100, - ) - - @property - def template_name(self): - """Returns the file system path to the template file. - - Required for passing the file to an external process - """ - template = self.label.name - template = template.replace('/', os.path.sep) - template = template.replace('\\', os.path.sep) - - template = settings.MEDIA_ROOT.joinpath(template) - - return template - - def get_context_data(self, request): - """Supply custom context data to the template for rendering. - - Note: Override this in any subclass - """ - return {} # pragma: no cover - - def generate_filename(self, request, **kwargs): - """Generate a filename for this label.""" - template_string = Template(self.filename_pattern) - - ctx = self.context(request) - - context = Context(ctx) - - return template_string.render(context) - - 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', 0) - - return f""" - @page {{ - size: {width}mm {height}mm; - margin: {margin}mm; - }} - """ - - def context(self, request, **kwargs): - """Provides context data to the template. - - Arguments: - request: The HTTP request object - kwargs: Additional keyword arguments - """ - context = self.get_context_data(request) - - # By default, each label is supplied with '@page' data - # However, it can be excluded, e.g. when rendering a label sheet - if kwargs.get('insert_page_style', True): - context['page_style'] = self.generate_page_style() - - # Add "basic" context data which gets passed to every label - context['base_url'] = get_base_url(request=request) - context['date'] = InvenTree.helpers.current_date() - context['datetime'] = InvenTree.helpers.current_time() - context['request'] = request - context['user'] = request.user - context['width'] = self.width - context['height'] = self.height - - # Pass the context through to any registered plugins - plugins = registry.with_mixin('report') - - for plugin in plugins: - # Let each plugin add its own context data - plugin.add_label_context(self, self.object_to_print, request, context) - - return context - - def render_as_string(self, request, target_object=None, **kwargs): - """Render the label to a HTML string.""" - if target_object: - self.object_to_print = target_object - - context = self.context(request, **kwargs) - - return render_to_string(self.template_name, context, request) - - def render(self, request, target_object=None, **kwargs): - """Render the label template to a PDF file. - - Uses django-weasyprint plugin to render HTML template - """ - if target_object: - self.object_to_print = target_object - - context = self.context(request, **kwargs) - - wp = WeasyprintLabelMixin( - request, - self.template_name, - base_url=request.build_absolute_uri('/'), - presentational_hints=True, - filename=self.generate_filename(request), - **kwargs, - ) - - return wp.render_to_response(context, **kwargs) - - -class LabelOutput(models.Model): - """Class representing a label output file. - - 'Printing' a label may generate a file object (such as PDF) - which is made available for download. - - Future work will offload this task to the background worker, - and provide a 'progress' bar for the user. - """ - - # File will be stored in a subdirectory - label = models.FileField( - upload_to=rename_label_output, unique=True, blank=False, null=False - ) - - # Creation date of label output - created = models.DateField(auto_now_add=True, editable=False) - - # User who generated the label - user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) - - -class StockItemLabel(LabelTemplate): - """Template for printing StockItem labels.""" - - @staticmethod - def get_api_url(): - """Return the API URL associated with the StockItemLabel model.""" - return reverse('api-stockitem-label-list') # pragma: no cover - - SUBDIR = 'stockitem' - - filters = models.CharField( - blank=True, - max_length=250, - help_text=_('Query filters (comma-separated list of key=value pairs)'), - verbose_name=_('Filters'), - validators=[validate_stock_item_filters], - ) - - def get_context_data(self, request): - """Generate context data for each provided StockItem.""" - stock_item = self.object_to_print - - return { - 'item': stock_item, - 'part': stock_item.part, - 'name': stock_item.part.full_name, - 'ipn': stock_item.part.IPN, - 'revision': stock_item.part.revision, - 'quantity': normalize(stock_item.quantity), - 'serial': stock_item.serial, - 'barcode_data': stock_item.barcode_data, - 'barcode_hash': stock_item.barcode_hash, - 'qr_data': stock_item.format_barcode(brief=True), - 'qr_url': request.build_absolute_uri(stock_item.get_absolute_url()), - 'tests': stock_item.testResultMap(), - 'parameters': stock_item.part.parameters_map(), - } - - -class StockLocationLabel(LabelTemplate): - """Template for printing StockLocation labels.""" - - @staticmethod - def get_api_url(): - """Return the API URL associated with the StockLocationLabel model.""" - return reverse('api-stocklocation-label-list') # pragma: no cover - - SUBDIR = 'stocklocation' - - filters = models.CharField( - blank=True, - max_length=250, - help_text=_('Query filters (comma-separated list of key=value pairs)'), - verbose_name=_('Filters'), - validators=[validate_stock_location_filters], - ) - - def get_context_data(self, request): - """Generate context data for each provided StockLocation.""" - location = self.object_to_print - - return {'location': location, 'qr_data': location.format_barcode(brief=True)} - - -class PartLabel(LabelTemplate): - """Template for printing Part labels.""" - - @staticmethod - def get_api_url(): - """Return the API url associated with the PartLabel model.""" - return reverse('api-part-label-list') # pragma: no cover - - SUBDIR = 'part' - - filters = models.CharField( - blank=True, - max_length=250, - help_text=_('Query filters (comma-separated list of key=value pairs)'), - verbose_name=_('Filters'), - validators=[validate_part_filters], - ) - - def get_context_data(self, request): - """Generate context data for each provided Part object.""" - part = self.object_to_print - - return { - 'part': part, - 'category': part.category, - 'name': part.name, - 'description': part.description, - 'IPN': part.IPN, - 'revision': part.revision, - 'qr_data': part.format_barcode(brief=True), - 'qr_url': request.build_absolute_uri(part.get_absolute_url()), - 'parameters': part.parameters_map(), - } - - -class BuildLineLabel(LabelTemplate): - """Template for printing labels against BuildLine objects.""" - - @staticmethod - def get_api_url(): - """Return the API URL associated with the BuildLineLabel model.""" - return reverse('api-buildline-label-list') - - SUBDIR = 'buildline' - - filters = models.CharField( - blank=True, - max_length=250, - help_text=_('Query filters (comma-separated list of key=value pairs)'), - verbose_name=_('Filters'), - validators=[validate_build_line_filters], - ) - - def get_context_data(self, request): - """Generate context data for each provided BuildLine object.""" - build_line = self.object_to_print - - return { - 'build_line': build_line, - 'build': build_line.build, - 'bom_item': build_line.bom_item, - 'part': build_line.bom_item.sub_part, - 'quantity': build_line.quantity, - 'allocated_quantity': build_line.allocated_quantity, - 'allocations': build_line.allocations, - } diff --git a/src/backend/InvenTree/label/serializers.py b/src/backend/InvenTree/label/serializers.py deleted file mode 100644 index ef1f467937c3..000000000000 --- a/src/backend/InvenTree/label/serializers.py +++ /dev/null @@ -1,67 +0,0 @@ -"""API serializers for the label app.""" - -import label.models -from InvenTree.serializers import ( - InvenTreeAttachmentSerializerField, - InvenTreeModelSerializer, -) - - -class LabelSerializerBase(InvenTreeModelSerializer): - """Base class for label serializer.""" - - label = InvenTreeAttachmentSerializerField(required=True) - - @staticmethod - def label_fields(): - """Generic serializer fields for a label template.""" - return [ - 'pk', - 'name', - 'description', - 'label', - 'filters', - 'width', - 'height', - 'enabled', - ] - - -class StockItemLabelSerializer(LabelSerializerBase): - """Serializes a StockItemLabel object.""" - - class Meta: - """Metaclass options.""" - - model = label.models.StockItemLabel - fields = LabelSerializerBase.label_fields() - - -class StockLocationLabelSerializer(LabelSerializerBase): - """Serializes a StockLocationLabel object.""" - - class Meta: - """Metaclass options.""" - - model = label.models.StockLocationLabel - fields = LabelSerializerBase.label_fields() - - -class PartLabelSerializer(LabelSerializerBase): - """Serializes a PartLabel object.""" - - class Meta: - """Metaclass options.""" - - model = label.models.PartLabel - fields = LabelSerializerBase.label_fields() - - -class BuildLineLabelSerializer(LabelSerializerBase): - """Serializes a BuildLineLabel object.""" - - class Meta: - """Metaclass options.""" - - model = label.models.BuildLineLabel - fields = LabelSerializerBase.label_fields() diff --git a/src/backend/InvenTree/label/tasks.py b/src/backend/InvenTree/label/tasks.py deleted file mode 100644 index b1630f629694..000000000000 --- a/src/backend/InvenTree/label/tasks.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Background tasks for the label app.""" - -from datetime import timedelta - -from django.utils import timezone - -from InvenTree.tasks import ScheduledTask, scheduled_task -from label.models import LabelOutput - - -@scheduled_task(ScheduledTask.DAILY) -def cleanup_old_label_outputs(): - """Remove old label outputs from the database.""" - # Remove any label outputs which are older than 30 days - LabelOutput.objects.filter(created__lte=timezone.now() - timedelta(days=5)).delete() diff --git a/src/backend/InvenTree/label/templates/label/buildline/buildline_label.html b/src/backend/InvenTree/label/templates/label/buildline/buildline_label.html deleted file mode 100644 index efbb9a3db655..000000000000 --- a/src/backend/InvenTree/label/templates/label/buildline/buildline_label.html +++ /dev/null @@ -1,3 +0,0 @@ -{% extends "label/buildline/buildline_label_base.html" %} - - diff --git a/src/backend/InvenTree/label/test_api.py b/src/backend/InvenTree/label/test_api.py deleted file mode 100644 index f2e4d728ec96..000000000000 --- a/src/backend/InvenTree/label/test_api.py +++ /dev/null @@ -1,301 +0,0 @@ -"""Unit tests for label API.""" - -import json -from io import StringIO - -from django.core.cache import cache -from django.urls import reverse - -import label.models as label_models -from build.models import BuildLine -from InvenTree.unit_test import InvenTreeAPITestCase -from part.models import Part -from stock.models import StockItem, StockLocation - - -class LabelTest(InvenTreeAPITestCase): - """Base class for unit testing label model API endpoints.""" - - fixtures = ['category', 'part', 'location', 'stock', 'bom', 'build'] - - superuser = True - - model = None - list_url = None - detail_url = None - metadata_url = None - - print_url = None - print_itemname = None - print_itemmodel = None - - def setUp(self): - """Ensure cache is cleared as part of test setup.""" - cache.clear() - return super().setUp() - - def test_api_url(self): - """Test returned API Url against URL tag defined in this file.""" - if not self.list_url: - return - - self.assertEqual(reverse(self.list_url), self.model.get_api_url()) - - def test_list_endpoint(self): - """Test that the LIST endpoint works for each model.""" - if not self.list_url: - return - - url = reverse(self.list_url) - - response = self.get(url) - self.assertEqual(response.status_code, 200) - - labels = self.model.objects.all() - n = len(labels) - - # API endpoint must return correct number of reports - self.assertEqual(len(response.data), n) - - # Filter by "enabled" status - response = self.get(url, {'enabled': True}) - self.assertEqual(len(response.data), n) - - response = self.get(url, {'enabled': False}) - self.assertEqual(len(response.data), 0) - - # Filter by "enabled" status - response = self.get(url, {'enabled': True}) - self.assertEqual(len(response.data), 0) - - response = self.get(url, {'enabled': False}) - self.assertEqual(len(response.data), n) - - def test_create_endpoint(self): - """Test that creating a new report works for each label.""" - if not self.list_url: - return - - url = reverse(self.list_url) - - # Create a new label - # Django REST API "APITestCase" does not work like requests - to send a file without it existing on disk, - # create it as a StringIO object, and upload it under parameter template - filestr = StringIO( - '{% extends "label/label_base.html" %}{% block content %}
TEST LABEL
{% endblock content %}' - ) - filestr.name = 'ExampleTemplate.html' - - response = self.post( - url, - data={ - 'name': 'New label', - 'description': 'A fancy new label created through API test', - 'label': filestr, - }, - format=None, - expected_code=201, - ) - - # Make sure the expected keys are in the response - self.assertIn('pk', response.data) - self.assertIn('name', response.data) - self.assertIn('description', response.data) - self.assertIn('label', response.data) - self.assertIn('filters', response.data) - self.assertIn('enabled', response.data) - - self.assertEqual(response.data['name'], 'New label') - self.assertEqual( - response.data['description'], 'A fancy new label created through API test' - ) - self.assertEqual(response.data['label'].count('ExampleTemplate'), 1) - - def test_detail_endpoint(self): - """Test that the DETAIL endpoint works for each label.""" - if not self.detail_url: - return - - # Create an item first - self.test_create_endpoint() - - labels = self.model.objects.all() - - n = len(labels) - - # Make sure at least one report defined - self.assertGreaterEqual(n, 1) - - # Check detail page for first report - response = self.get( - reverse(self.detail_url, kwargs={'pk': labels[0].pk}), expected_code=200 - ) - - # Make sure the expected keys are in the response - self.assertIn('pk', response.data) - self.assertIn('name', response.data) - self.assertIn('description', response.data) - self.assertIn('label', response.data) - self.assertIn('filters', response.data) - self.assertIn('enabled', response.data) - - filestr = StringIO( - '{% extends "label/label_base.html" %}{% block content %}
TEST LABEL
{% endblock content %}' - ) - filestr.name = 'ExampleTemplate_Updated.html' - - # Check PATCH method - response = self.patch( - reverse(self.detail_url, kwargs={'pk': labels[0].pk}), - { - 'name': 'Changed name during test', - 'description': 'New version of the template', - 'label': filestr, - }, - format=None, - expected_code=200, - ) - - # Make sure the expected keys are in the response - self.assertIn('pk', response.data) - self.assertIn('name', response.data) - self.assertIn('description', response.data) - self.assertIn('label', response.data) - self.assertIn('filters', response.data) - self.assertIn('enabled', response.data) - - self.assertEqual(response.data['name'], 'Changed name during test') - self.assertEqual(response.data['description'], 'New version of the template') - - self.assertEqual(response.data['label'].count('ExampleTemplate_Updated'), 1) - - def test_delete(self): - """Test deleting, after other test are done.""" - if not self.detail_url: - return - - # Create an item first - self.test_create_endpoint() - - labels = self.model.objects.all() - n = len(labels) - # Make sure at least one label defined - self.assertGreaterEqual(n, 1) - - # Delete the last report - self.delete( - reverse(self.detail_url, kwargs={'pk': labels[n - 1].pk}), expected_code=204 - ) - - def test_print_label(self): - """Test printing a label.""" - if not self.print_url: - return - - # Create an item first - self.test_create_endpoint() - - labels = self.model.objects.all() - n = len(labels) - # Make sure at least one label defined - self.assertGreaterEqual(n, 1) - - url = reverse(self.print_url, kwargs={'pk': labels[0].pk}) - - # Try to print without providing a valid item - self.get(url, expected_code=400) - - # Try to print with an invalid item - self.get(url, {self.print_itemname: 9999}, expected_code=400) - - # Now print with a valid item - print(f'{self.print_itemmodel = }') - print(f'{self.print_itemmodel.objects.all() = }') - - item = self.print_itemmodel.objects.first() - self.assertIsNotNone(item) - - response = self.get(url, {self.print_itemname: item.pk}, expected_code=200) - - response_json = json.loads(response.content.decode('utf-8')) - - self.assertIn('file', response_json) - self.assertIn('success', response_json) - self.assertIn('message', response_json) - self.assertTrue(response_json['success']) - - def test_metadata_endpoint(self): - """Unit tests for the metadata field.""" - if not self.metadata_url: - return - - # Create an item first - self.test_create_endpoint() - - labels = self.model.objects.all() - n = len(labels) - # Make sure at least one label defined - self.assertGreaterEqual(n, 1) - - # Test getting metadata - response = self.get( - reverse(self.metadata_url, kwargs={'pk': labels[0].pk}), expected_code=200 - ) - - self.assertEqual(response.data, {'metadata': {}}) - - -class TestStockItemLabel(LabelTest): - """Unit testing class for the StockItemLabel model.""" - - model = label_models.StockItemLabel - - list_url = 'api-stockitem-label-list' - detail_url = 'api-stockitem-label-detail' - metadata_url = 'api-stockitem-label-metadata' - - print_url = 'api-stockitem-label-print' - print_itemname = 'item' - print_itemmodel = StockItem - - -class TestStockLocationLabel(LabelTest): - """Unit testing class for the StockLocationLabel model.""" - - model = label_models.StockLocationLabel - - list_url = 'api-stocklocation-label-list' - detail_url = 'api-stocklocation-label-detail' - metadata_url = 'api-stocklocation-label-metadata' - - print_url = 'api-stocklocation-label-print' - print_itemname = 'location' - print_itemmodel = StockLocation - - -class TestPartLabel(LabelTest): - """Unit testing class for the PartLabel model.""" - - model = label_models.PartLabel - - list_url = 'api-part-label-list' - detail_url = 'api-part-label-detail' - metadata_url = 'api-part-label-metadata' - - print_url = 'api-part-label-print' - print_itemname = 'part' - print_itemmodel = Part - - -class TestBuildLineLabel(LabelTest): - """Unit testing class for the BuildLine model.""" - - model = label_models.BuildLineLabel - - list_url = 'api-buildline-label-list' - detail_url = 'api-buildline-label-detail' - metadata_url = 'api-buildline-label-metadata' - - print_url = 'api-buildline-label-print' - print_itemname = 'line' - print_itemmodel = BuildLine diff --git a/src/backend/InvenTree/label/tests.py b/src/backend/InvenTree/label/tests.py deleted file mode 100644 index 62a84c6439b7..000000000000 --- a/src/backend/InvenTree/label/tests.py +++ /dev/null @@ -1,166 +0,0 @@ -"""Tests for labels.""" - -import io -import json - -from django.apps import apps -from django.conf import settings -from django.core.exceptions import ValidationError -from django.core.files.base import ContentFile -from django.http import JsonResponse -from django.urls import reverse - -from common.models import InvenTreeSetting -from InvenTree.helpers import validateFilterString -from InvenTree.unit_test import InvenTreeAPITestCase -from label.models import LabelOutput -from part.models import Part -from plugin.registry import registry -from stock.models import StockItem - -from .models import PartLabel, StockItemLabel, StockLocationLabel - - -class LabelTest(InvenTreeAPITestCase): - """Unit test class for label models.""" - - fixtures = ['category', 'part', 'location', 'stock'] - - @classmethod - def setUpTestData(cls): - """Ensure that some label instances exist as part of init routine.""" - super().setUpTestData() - apps.get_app_config('label').create_defaults() - - def test_default_labels(self): - """Test that the default label templates are copied across.""" - labels = StockItemLabel.objects.all() - - self.assertGreater(labels.count(), 0) - - labels = StockLocationLabel.objects.all() - - self.assertGreater(labels.count(), 0) - - def test_default_files(self): - """Test that label files exist in the MEDIA directory.""" - - def test_subdir(ref_name): - item_dir = settings.MEDIA_ROOT.joinpath('label', 'inventree', ref_name) - self.assertGreater(len([item_dir.iterdir()]), 0) - - test_subdir('stockitem') - test_subdir('stocklocation') - test_subdir('part') - - def test_filters(self): - """Test the label filters.""" - filter_string = 'part__pk=10' - - filters = validateFilterString(filter_string, model=StockItem) - - self.assertEqual(type(filters), dict) - - bad_filter_string = 'part_pk=10' - - with self.assertRaises(ValidationError): - validateFilterString(bad_filter_string, model=StockItem) - - def test_label_rendering(self): - """Test label rendering.""" - labels = PartLabel.objects.all() - part = Part.objects.first() - - for label in labels: - url = reverse('api-part-label-print', kwargs={'pk': label.pk}) - - # Check that label printing returns the correct response type - response = self.get(f'{url}?parts={part.pk}', expected_code=200) - self.assertIsInstance(response, JsonResponse) - data = json.loads(response.content) - - self.assertIn('message', data) - self.assertIn('file', data) - label_file = data['file'] - self.assertIn('/media/label/output/', label_file) - - def test_print_part_label(self): - """Actually 'print' a label, and ensure that the correct information is contained.""" - label_data = """ - {% load barcode %} - {% load report %} - - - - part: {{ part.pk }} - {{ part.name }} - - data: {{ qr_data|safe }} - - url: {{ qr_url|safe }} - - image: {% part_image part width=128 %} - - logo: {% logo_image %} - - """ - - buffer = io.StringIO() - buffer.write(label_data) - - template = ContentFile(buffer.getvalue(), 'label.html') - - # Construct a label template - label = PartLabel.objects.create( - name='test', description='Test label', enabled=True, label=template - ) - - # Ensure we are in "debug" mode (so the report is generated as HTML) - InvenTreeSetting.set_setting('REPORT_ENABLE', True, None) - - # Set the 'debug' setting for the plugin - plugin = registry.get_plugin('inventreelabel') - plugin.set_setting('DEBUG', True) - - # Print via the API (Note: will default to the builtin plugin if no plugin supplied) - url = reverse('api-part-label-print', kwargs={'pk': label.pk}) - - prt = Part.objects.first() - part_pk = prt.pk - part_name = prt.name - - response = self.get(f'{url}?parts={part_pk}', expected_code=200) - data = json.loads(response.content) - self.assertIn('file', data) - - # Find the generated file - output = LabelOutput.objects.last() - - # Open the file and read data - with open(output.label.path, 'r') as f: - content = f.read() - - # Test that each element has been rendered correctly - self.assertIn(f'part: {part_pk} - {part_name}', content) - self.assertIn(f'data: {{"part": {part_pk}}}', content) - if settings.ENABLE_CLASSIC_FRONTEND: - self.assertIn(f'http://testserver/part/{part_pk}/', content) - - # Check that a encoded image has been generated - self.assertIn('data:image/png;charset=utf-8;base64,', content) - - def test_metadata(self): - """Unit tests for the metadata field.""" - for model in [StockItemLabel, StockLocationLabel, PartLabel]: - p = model.objects.first() - - self.assertIsNone(p.get_metadata('test')) - self.assertEqual(p.get_metadata('test', backup_value=123), 123) - - # Test update via the set_metadata() method - p.set_metadata('test', 3) - self.assertEqual(p.get_metadata('test'), 3) - - for k in ['apple', 'banana', 'carrot', 'carrot', 'banana']: - p.set_metadata(k, k) - - self.assertEqual(len(p.metadata.keys()), 4) diff --git a/src/backend/InvenTree/machine/machine_types/label_printer.py b/src/backend/InvenTree/machine/machine_types/label_printer.py index bfbff04a4559..4fd7f044054c 100644 --- a/src/backend/InvenTree/machine/machine_types/label_printer.py +++ b/src/backend/InvenTree/machine/machine_types/label_printer.py @@ -2,6 +2,7 @@ from typing import Union, cast +from django.db import models from django.db.models.query import QuerySet from django.http import HttpResponse, JsonResponse from django.utils.translation import gettext_lazy as _ @@ -10,10 +11,10 @@ from rest_framework import serializers from rest_framework.request import Request -from label.models import LabelTemplate from machine.machine_type import BaseDriver, BaseMachineType, MachineStatus from plugin import registry as plg_registry -from plugin.base.label.mixins import LabelItemType, LabelPrintingMixin +from plugin.base.label.mixins import LabelPrintingMixin +from report.models import LabelTemplate from stock.models import StockLocation @@ -32,7 +33,7 @@ def print_label( self, machine: 'LabelPrinterMachine', label: LabelTemplate, - item: LabelItemType, + item: models.Model, request: Request, **kwargs, ) -> None: @@ -56,7 +57,7 @@ def print_labels( self, machine: 'LabelPrinterMachine', label: LabelTemplate, - items: QuerySet[LabelItemType], + items: QuerySet, request: Request, **kwargs, ) -> Union[None, JsonResponse]: @@ -83,7 +84,7 @@ def print_labels( self.print_label(machine, label, item, request, **kwargs) def get_printers( - self, label: LabelTemplate, items: QuerySet[LabelItemType], **kwargs + self, label: LabelTemplate, items: QuerySet, **kwargs ) -> list['LabelPrinterMachine']: """Get all printers that would be available to print this job. @@ -122,7 +123,7 @@ def machine_plugin(self) -> LabelPrintingMixin: return cast(LabelPrintingMixin, plg) def render_to_pdf( - self, label: LabelTemplate, item: LabelItemType, request: Request, **kwargs + self, label: LabelTemplate, item: models.Model, request: Request, **kwargs ) -> HttpResponse: """Helper method to render a label to PDF format for a specific item. @@ -137,7 +138,7 @@ def render_to_pdf( return response def render_to_pdf_data( - self, label: LabelTemplate, item: LabelItemType, request: Request, **kwargs + self, label: LabelTemplate, item: models.Model, request: Request, **kwargs ) -> bytes: """Helper method to render a label to PDF and return it as bytes for a specific item. @@ -153,7 +154,7 @@ def render_to_pdf_data( ) def render_to_html( - self, label: LabelTemplate, item: LabelItemType, request: Request, **kwargs + self, label: LabelTemplate, item: models.Model, request: Request, **kwargs ) -> str: """Helper method to render a label to HTML format for a specific item. @@ -168,7 +169,7 @@ def render_to_html( return html def render_to_png( - self, label: LabelTemplate, item: LabelItemType, request: Request, **kwargs + self, label: LabelTemplate, item: models.Model, request: Request, **kwargs ) -> Image: """Helper method to render a label to PNG format for a specific item. diff --git a/src/backend/InvenTree/machine/tests.py b/src/backend/InvenTree/machine/tests.py index ef37f5d5b376..992ca3fe0eff 100755 --- a/src/backend/InvenTree/machine/tests.py +++ b/src/backend/InvenTree/machine/tests.py @@ -10,7 +10,6 @@ from rest_framework import serializers from InvenTree.unit_test import InvenTreeAPITestCase -from label.models import PartLabel from machine.machine_type import BaseDriver, BaseMachineType, MachineStatus from machine.machine_types.label_printer import LabelPrinterBaseDriver from machine.models import MachineConfig @@ -18,6 +17,7 @@ from part.models import Part from plugin.models import PluginConfig from plugin.registry import registry as plg_registry +from report.models import LabelTemplate class TestMachineRegistryMixin(TestCase): @@ -247,31 +247,33 @@ def test_print_label(self): plugin_ref = 'inventreelabelmachine' # setup the label app - apps.get_app_config('label').create_defaults() # type: ignore + apps.get_app_config('report').create_default_labels() # type: ignore plg_registry.reload_plugins() config = cast(PluginConfig, plg_registry.get_plugin(plugin_ref).plugin_config()) # type: ignore config.active = True config.save() parts = Part.objects.all()[:2] - label = cast(PartLabel, PartLabel.objects.first()) + template = LabelTemplate.objects.filter(enabled=True, model_type='part').first() - url = reverse('api-part-label-print', kwargs={'pk': label.pk}) - url += f'/?plugin={plugin_ref}&part[]={parts[0].pk}&part[]={parts[1].pk}' + url = reverse('api-label-print') self.post( url, { + 'plugin': config.key, + 'items': [a.pk for a in parts], + 'template': template.pk, 'machine': str(self.machine.pk), 'driver_options': {'copies': '1', 'test_option': '2'}, }, - expected_code=200, + expected_code=201, ) # test the print labels method call self.print_labels.assert_called_once() self.assertEqual(self.print_labels.call_args.args[0], self.machine.machine) - self.assertEqual(self.print_labels.call_args.args[1], label) + self.assertEqual(self.print_labels.call_args.args[1], template) # TODO re-activate test # self.assertQuerySetEqual( diff --git a/src/backend/InvenTree/order/migrations/0001_initial.py b/src/backend/InvenTree/order/migrations/0001_initial.py index 642b321d4747..edceeffc1191 100644 --- a/src/backend/InvenTree/order/migrations/0001_initial.py +++ b/src/backend/InvenTree/order/migrations/0001_initial.py @@ -30,6 +30,7 @@ class Migration(migrations.Migration): ], options={ 'abstract': False, + 'verbose_name': 'Purchase Order' }, ), migrations.CreateModel( diff --git a/src/backend/InvenTree/order/migrations/0020_auto_20200420_0940.py b/src/backend/InvenTree/order/migrations/0020_auto_20200420_0940.py index aef57a343774..76e903b45aad 100644 --- a/src/backend/InvenTree/order/migrations/0020_auto_20200420_0940.py +++ b/src/backend/InvenTree/order/migrations/0020_auto_20200420_0940.py @@ -35,6 +35,7 @@ class Migration(migrations.Migration): ], options={ 'abstract': False, + 'verbose_name': 'Sales Order', }, ), migrations.AlterField( diff --git a/src/backend/InvenTree/order/migrations/0081_auto_20230314_0725.py b/src/backend/InvenTree/order/migrations/0081_auto_20230314_0725.py index 719a7a503759..f15b800ffebc 100644 --- a/src/backend/InvenTree/order/migrations/0081_auto_20230314_0725.py +++ b/src/backend/InvenTree/order/migrations/0081_auto_20230314_0725.py @@ -39,6 +39,7 @@ class Migration(migrations.Migration): ], options={ 'abstract': False, + 'verbose_name': 'Return Order', }, ), migrations.AlterField( diff --git a/src/backend/InvenTree/order/models.py b/src/backend/InvenTree/order/models.py index 8eae8562ed15..b149f31503df 100644 --- a/src/backend/InvenTree/order/models.py +++ b/src/backend/InvenTree/order/models.py @@ -30,6 +30,7 @@ import InvenTree.tasks import InvenTree.validators import order.validators +import report.mixins import stock.models import users.models as UserModels from common.notifications import InvenTreeNotificationBodies @@ -185,6 +186,7 @@ class Order( StateTransitionMixin, InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models.InvenTreeNotesMixin, + report.mixins.InvenTreeReportMixin, InvenTree.models.MetadataMixin, InvenTree.models.ReferenceIndexingMixin, InvenTree.models.InvenTreeModel, @@ -246,6 +248,17 @@ def clean(self): 'contact': _('Contact does not match selected company') }) + def report_context(self): + """Generate context data for the reporting interface.""" + return { + 'description': self.description, + 'extra_lines': self.extra_lines, + 'lines': self.lines, + 'order': self, + 'reference': self.reference, + 'title': str(self), + } + @classmethod def overdue_filter(cls): """A generic implementation of an 'overdue' filter for the Model class. @@ -362,6 +375,15 @@ class PurchaseOrder(TotalPriceMixin, Order): REFERENCE_PATTERN_SETTING = 'PURCHASEORDER_REFERENCE_PATTERN' REQUIRE_RESPONSIBLE_SETTING = 'PURCHASEORDER_REQUIRE_RESPONSIBLE' + class Meta: + """Model meta options.""" + + verbose_name = _('Purchase Order') + + def report_context(self): + """Return report context data for this PurchaseOrder.""" + return {**super().report_context(), 'supplier': self.supplier} + def get_absolute_url(self): """Get the 'web' URL for this order.""" if settings.ENABLE_CLASSIC_FRONTEND: @@ -820,6 +842,15 @@ class SalesOrder(TotalPriceMixin, Order): REFERENCE_PATTERN_SETTING = 'SALESORDER_REFERENCE_PATTERN' REQUIRE_RESPONSIBLE_SETTING = 'SALESORDER_REQUIRE_RESPONSIBLE' + class Meta: + """Model meta options.""" + + verbose_name = _('Sales Order') + + def report_context(self): + """Generate report context data for this SalesOrder.""" + return {**super().report_context(), 'customer': self.customer} + def get_absolute_url(self): """Get the 'web' URL for this order.""" if settings.ENABLE_CLASSIC_FRONTEND: @@ -1977,6 +2008,15 @@ class ReturnOrder(TotalPriceMixin, Order): REFERENCE_PATTERN_SETTING = 'RETURNORDER_REFERENCE_PATTERN' REQUIRE_RESPONSIBLE_SETTING = 'RETURNORDER_REQUIRE_RESPONSIBLE' + class Meta: + """Model meta options.""" + + verbose_name = _('Return Order') + + def report_context(self): + """Generate report context data for this ReturnOrder.""" + return {**super().report_context(), 'customer': self.customer} + def get_absolute_url(self): """Get the 'web' URL for this order.""" if settings.ENABLE_CLASSIC_FRONTEND: diff --git a/src/backend/InvenTree/order/templates/order/order_base.html b/src/backend/InvenTree/order/templates/order/order_base.html index 173eaeb11944..af422e679456 100644 --- a/src/backend/InvenTree/order/templates/order/order_base.html +++ b/src/backend/InvenTree/order/templates/order/order_base.html @@ -253,11 +253,7 @@ {% if report_enabled %} $('#print-order-report').click(function() { - printReports({ - items: [{{ order.pk }}], - key: 'order', - url: '{% url "api-po-report-list" %}', - }); + printReports('purchaseorder', [{{ order.pk }}]); }); {% endif %} diff --git a/src/backend/InvenTree/order/templates/order/return_order_base.html b/src/backend/InvenTree/order/templates/order/return_order_base.html index eb80a70d53e2..32ccd23f85d7 100644 --- a/src/backend/InvenTree/order/templates/order/return_order_base.html +++ b/src/backend/InvenTree/order/templates/order/return_order_base.html @@ -248,11 +248,7 @@ {% if report_enabled %} $('#print-order-report').click(function() { - printReports({ - items: [{{ order.pk }}], - key: 'order', - url: '{% url "api-return-order-report-list" %}', - }); + printReports('returnorder', [{{ order.pk }}]); }); {% endif %} diff --git a/src/backend/InvenTree/order/templates/order/sales_order_base.html b/src/backend/InvenTree/order/templates/order/sales_order_base.html index e1ed302804c0..6bfb9b098934 100644 --- a/src/backend/InvenTree/order/templates/order/sales_order_base.html +++ b/src/backend/InvenTree/order/templates/order/sales_order_base.html @@ -310,11 +310,7 @@ {% if report_enabled %} $('#print-order-report').click(function() { - printReports({ - items: [{{ order.pk }}], - key: 'order', - url: '{% url "api-so-report-list" %}', - }); + printReports('salesorder', [{{ order.pk }}]); }); {% endif %} diff --git a/src/backend/InvenTree/part/models.py b/src/backend/InvenTree/part/models.py index 80254c61cf72..6364683c5d63 100644 --- a/src/backend/InvenTree/part/models.py +++ b/src/backend/InvenTree/part/models.py @@ -7,7 +7,7 @@ import logging import os import re -from datetime import datetime, timedelta +from datetime import timedelta from decimal import Decimal, InvalidOperation from django.conf import settings @@ -43,6 +43,7 @@ import InvenTree.tasks import part.helpers as part_helpers import part.settings as part_settings +import report.mixins import users.models from build import models as BuildModels from common.models import InvenTreeSetting @@ -340,6 +341,7 @@ def get_queryset(self): class Part( InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models.InvenTreeNotesMixin, + report.mixins.InvenTreeReportMixin, InvenTree.models.MetadataMixin, InvenTree.models.PluginValidationMixin, MPTTModel, @@ -409,8 +411,28 @@ def api_instance_filters(self): """Return API query filters for limiting field results against this instance.""" return {'variant_of': {'exclude_tree': self.pk}} + def report_context(self): + """Return custom report context information.""" + return { + 'bom_items': self.get_bom_items(), + 'category': self.category, + 'description': self.description, + 'IPN': self.IPN, + 'name': self.name, + 'parameters': self.parameters_map(), + 'part': self, + 'qr_data': self.format_barcode(brief=True), + 'qr_url': self.get_absolute_url(), + 'revision': self.revision, + 'test_template_list': self.getTestTemplates(), + 'test_templates': self.getTestTemplates(), + } + def get_context_data(self, request, **kwargs): - """Return some useful context data about this part for template rendering.""" + """Return some useful context data about this part for template rendering. + + TODO: 2024-04-21 - Remove this method once the legacy UI code is removed + """ context = {} context['disabled'] = not self.active diff --git a/src/backend/InvenTree/part/serializers.py b/src/backend/InvenTree/part/serializers.py index 7bed55d416e0..e2182b163541 100644 --- a/src/backend/InvenTree/part/serializers.py +++ b/src/backend/InvenTree/part/serializers.py @@ -432,6 +432,11 @@ class DuplicatePartSerializer(serializers.Serializer): The fields in this serializer control how the Part is duplicated. """ + class Meta: + """Metaclass options.""" + + fields = ['part', 'copy_image', 'copy_bom', 'copy_parameters', 'copy_notes'] + part = serializers.PrimaryKeyRelatedField( queryset=Part.objects.all(), label=_('Original Part'), @@ -471,6 +476,11 @@ class DuplicatePartSerializer(serializers.Serializer): class InitialStockSerializer(serializers.Serializer): """Serializer for creating initial stock quantity.""" + class Meta: + """Metaclass options.""" + + fields = ['quantity', 'location'] + quantity = serializers.DecimalField( max_digits=15, decimal_places=5, @@ -494,6 +504,11 @@ class InitialStockSerializer(serializers.Serializer): class InitialSupplierSerializer(serializers.Serializer): """Serializer for adding initial supplier / manufacturer information.""" + class Meta: + """Metaclass options.""" + + fields = ['supplier', 'sku', 'manufacturer', 'mpn'] + supplier = serializers.PrimaryKeyRelatedField( queryset=company.models.Company.objects.all(), label=_('Supplier'), diff --git a/src/backend/InvenTree/part/templates/part/detail.html b/src/backend/InvenTree/part/templates/part/detail.html index 4cf36dc387bf..1e0c8d471852 100644 --- a/src/backend/InvenTree/part/templates/part/detail.html +++ b/src/backend/InvenTree/part/templates/part/detail.html @@ -629,11 +629,7 @@

{% trans "Part Manufacturers" %}

{% if report_enabled %} $("#print-bom-report").click(function() { - printReports({ - items: [{{ part.pk }}], - key: 'part', - url: '{% url "api-bom-report-list" %}' - }); + printReports('part', [{{ part.pk }}]); }); {% endif %} }); diff --git a/src/backend/InvenTree/part/templates/part/part_base.html b/src/backend/InvenTree/part/templates/part/part_base.html index 16ce73b29104..3b6b57542dff 100644 --- a/src/backend/InvenTree/part/templates/part/part_base.html +++ b/src/backend/InvenTree/part/templates/part/part_base.html @@ -468,9 +468,8 @@
$('#print-label').click(function() { printLabels({ items: [{{ part.pk }}], - key: 'part', + model_type: 'part', singular_name: 'part', - url: '{% url "api-part-label-list" %}', }); }); {% endif %} diff --git a/src/backend/InvenTree/plugin/base/integration/ReportMixin.py b/src/backend/InvenTree/plugin/base/integration/ReportMixin.py index 1dd2a7ae2f82..1c81df722f7f 100644 --- a/src/backend/InvenTree/plugin/base/integration/ReportMixin.py +++ b/src/backend/InvenTree/plugin/base/integration/ReportMixin.py @@ -47,3 +47,16 @@ def add_label_context(self, label_instance, model_instance, request, context): context: The context dictionary to add to """ pass + + def report_callback(self, template, instance, report, request): + """Callback function called after a report is generated. + + Arguments: + template: The ReportTemplate model + instance: The instance of the target model + report: The generated report object + request: The initiating request object + + The default implementation does nothing. + """ + pass diff --git a/src/backend/InvenTree/plugin/base/label/mixins.py b/src/backend/InvenTree/plugin/base/label/mixins.py index 736d431d0069..68236ec29fa2 100644 --- a/src/backend/InvenTree/plugin/base/label/mixins.py +++ b/src/backend/InvenTree/plugin/base/label/mixins.py @@ -11,17 +11,12 @@ from rest_framework import serializers from rest_framework.request import Request -from build.models import BuildLine from common.models import InvenTreeSetting from InvenTree.exceptions import log_error from InvenTree.tasks import offload_task -from label.models import LabelTemplate -from part.models import Part from plugin.base.label import label as plugin_label from plugin.helpers import MixinNotImplementedError -from stock.models import StockItem, StockLocation - -LabelItemType = Union[StockItem, StockLocation, Part, BuildLine] +from report.models import LabelTemplate, TemplateOutput class LabelPrintingMixin: @@ -34,11 +29,6 @@ class LabelPrintingMixin: Note that the print_labels() function can also be overridden to provide custom behavior. """ - # If True, the print_label() method will block until the label is printed - # If False, the offload_label() method will be called instead - # By default, this is False, which means that labels will be printed in the background - BLOCKING_PRINT = False - class MixinMeta: """Meta options for this mixin.""" @@ -49,37 +39,42 @@ def __init__(self): # pragma: no cover super().__init__() self.add_mixin('labels', True, __class__) - def render_to_pdf(self, label: LabelTemplate, request, **kwargs): + BLOCKING_PRINT = True + + def render_to_pdf(self, label: LabelTemplate, instance, request, **kwargs): """Render this label to PDF format. Arguments: - label: The LabelTemplate object to render + label: The LabelTemplate object to render against + instance: The model instance to render request: The HTTP request object which triggered this print job """ try: - return label.render(request) + return label.render(instance, request) except Exception: log_error('label.render_to_pdf') raise ValidationError(_('Error rendering label to PDF')) - def render_to_html(self, label: LabelTemplate, request, **kwargs): + def render_to_html(self, label: LabelTemplate, instance, request, **kwargs): """Render this label to HTML format. Arguments: - label: The LabelTemplate object to render + label: The LabelTemplate object to render against + instance: The model instance to render request: The HTTP request object which triggered this print job """ try: - return label.render_as_string(request) + return label.render_as_string(instance, request) except Exception: log_error('label.render_to_html') raise ValidationError(_('Error rendering label to HTML')) - def render_to_png(self, label: LabelTemplate, request=None, **kwargs): + def render_to_png(self, label: LabelTemplate, instance, request=None, **kwargs): """Render this label to PNG format. Arguments: - label: The LabelTemplate object to render + label: The LabelTemplate object to render against + item: The model instance to render request: The HTTP request object which triggered this print job Keyword Arguments: pdf_data: The raw PDF data of the rendered label (if already rendered) @@ -94,7 +89,9 @@ def render_to_png(self, label: LabelTemplate, request=None, **kwargs): if not pdf_data: pdf_data = ( - self.render_to_pdf(label, request, **kwargs).get_document().write_pdf() + self.render_to_pdf(label, instance, request, **kwargs) + .get_document() + .write_pdf() ) pdf2image_kwargs = { @@ -108,19 +105,21 @@ def render_to_png(self, label: LabelTemplate, request=None, **kwargs): return pdf2image.convert_from_bytes(pdf_data, **pdf2image_kwargs)[0] except Exception: log_error('label.render_to_png') - raise ValidationError(_('Error rendering label to PNG')) + return None def print_labels( self, label: LabelTemplate, - items: QuerySet[LabelItemType], + output: TemplateOutput, + items: list, request: Request, **kwargs, - ): + ) -> None: """Print one or more labels with the provided template and items. Arguments: label: The LabelTemplate object to use for printing + output: The TemplateOutput object used to store the results items: The list of database items to print (e.g. StockItem instances) request: The HTTP request object which triggered this print job @@ -128,7 +127,10 @@ def print_labels( printing_options: The printing options set for this print job defined in the PrintingOptionsSerializer Returns: - A JSONResponse object which indicates outcome to the user + None. Output data should be stored in the provided TemplateOutput object + + Raises: + ValidationError if there is an error during the print process The default implementation simply calls print_label() for each label, producing multiple single label output "jobs" but this can be overridden by the particular plugin. @@ -138,19 +140,30 @@ def print_labels( except AttributeError: user = None + # Initial state for the output print job + output.progress = 0 + output.complete = False + output.save() + + N = len(items) + # Generate a label output for each provided item for item in items: - label.object_to_print = item - filename = label.generate_filename(request) - pdf_file = self.render_to_pdf(label, request, **kwargs) + context = label.get_context(item, request) + filename = label.generate_filename(context) + pdf_file = self.render_to_pdf(label, item, request, **kwargs) pdf_data = pdf_file.get_document().write_pdf() - png_file = self.render_to_png(label, request, pdf_data=pdf_data, **kwargs) + png_file = self.render_to_png( + label, item, request, pdf_data=pdf_data, **kwargs + ) print_args = { 'pdf_file': pdf_file, 'pdf_data': pdf_data, 'png_file': png_file, 'filename': filename, + 'context': context, + 'output': output, 'label_instance': label, 'item_instance': item, 'user': user, @@ -160,19 +173,34 @@ def print_labels( } if self.BLOCKING_PRINT: - # Blocking print job + # Print the label (blocking) self.print_label(**print_args) else: - # Non-blocking print job + # Offload the print task to the background worker + # Exclude the 'pdf_file' object - cannot be pickled + + kwargs.pop('pdf_file', None) + offload_task(plugin_label.print_label, self.plugin_slug(), **print_args) + + # Update the progress of the print job + output.progress += int(100 / N) + output.save() + + # Mark the output as complete + output.complete = True + output.progress = 100 - # Offload the print job to a background worker - self.offload_label(**print_args) + # Add in the generated file (if applicable) + output.output = self.get_generated_file(**print_args) - # Return a JSON response to the user - return JsonResponse({ - 'success': True, - 'message': f'{len(items)} labels printed', - }) + output.save() + + def get_generated_file(self, **kwargs): + """Return the generated file for download (or None, if this plugin does not generate a file output). + + The default implementation returns None, but this can be overridden by the particular plugin. + """ + return None def print_label(self, **kwargs): """Print a single label (blocking). @@ -183,6 +211,7 @@ def print_label(self, **kwargs): filename: The filename of this PDF label label_instance: The instance of the label model which triggered the print_label() method item_instance: The instance of the database model against which the label is printed + output: The TemplateOutput object used to store the results of the print job user: The user who triggered this print job width: The expected width of the label (in mm) height: The expected height of the label (in mm) @@ -195,19 +224,6 @@ def print_label(self, **kwargs): 'This Plugin must implement a `print_label` method' ) - def offload_label(self, **kwargs): - """Offload a single label (non-blocking). - - Instead of immediately printing the label (which is a blocking process), - this method should offload the label to a background worker process. - - Offloads a call to the 'print_label' method (of this plugin) to a background worker. - """ - # Exclude the 'pdf_file' object - cannot be pickled - kwargs.pop('pdf_file', None) - - offload_task(plugin_label.print_label, self.plugin_slug(), **kwargs) - def get_printing_options_serializer( self, request: Request, *args, **kwargs ) -> Union[serializers.Serializer, None]: @@ -227,3 +243,11 @@ def get_printing_options_serializer( return None return serializer(*args, **kwargs) + + def before_printing(self): + """Hook method called before printing labels.""" + pass + + def after_printing(self): + """Hook method called after printing labels.""" + pass diff --git a/src/backend/InvenTree/plugin/base/label/test_label_mixin.py b/src/backend/InvenTree/plugin/base/label/test_label_mixin.py index 3fa140968765..5845163e6334 100644 --- a/src/backend/InvenTree/plugin/base/label/test_label_mixin.py +++ b/src/backend/InvenTree/plugin/base/label/test_label_mixin.py @@ -12,62 +12,28 @@ from InvenTree.settings import BASE_DIR from InvenTree.unit_test import InvenTreeAPITestCase -from label.models import PartLabel, StockItemLabel, StockLocationLabel from part.models import Part from plugin.base.label.mixins import LabelPrintingMixin from plugin.helpers import MixinNotImplementedError from plugin.plugin import InvenTreePlugin from plugin.registry import registry +from report.models import LabelTemplate +from report.tests import PrintTestMixins from stock.models import StockItem, StockLocation -class LabelMixinTests(InvenTreeAPITestCase): +class LabelMixinTests(PrintTestMixins, InvenTreeAPITestCase): """Test that the Label mixin operates correctly.""" fixtures = ['category', 'part', 'location', 'stock'] roles = 'all' + plugin_ref = 'samplelabelprinter' - def do_activate_plugin(self): - """Activate the 'samplelabel' plugin.""" - config = registry.get_plugin('samplelabelprinter').plugin_config() - config.active = True - config.save() - - def do_url( - self, - parts, - plugin_ref, - label, - url_name: str = 'api-part-label-print', - url_single: str = 'part', - invalid: bool = False, - ): - """Generate an URL to print a label.""" - # Construct URL - kwargs = {} - if label: - kwargs['pk'] = label.pk - - url = reverse(url_name, kwargs=kwargs) - - # Append part filters - if not parts: - pass - elif len(parts) == 1: - url += f'?{url_single}={parts[0].pk}' - elif len(parts) > 1: - url += '?' + '&'.join([f'{url_single}s={item.pk}' for item in parts]) - - # Append an invalid item - if invalid: - url += f'&{url_single}{"s" if len(parts) > 1 else ""}=abc' - - # Append plugin reference - if plugin_ref: - url += f'&plugin={plugin_ref}' - - return url + @property + def printing_url(self): + """Return the label printing URL.""" + return reverse('api-label-print') def test_wrong_implementation(self): """Test that a wrong implementation raises an error.""" @@ -121,52 +87,106 @@ def test_api(self): def test_printing_process(self): """Test that a label can be printed.""" # Ensure the labels were created - apps.get_app_config('label').create_defaults() + apps.get_app_config('report').create_default_labels() + apps.get_app_config('report').create_default_reports() + + test_path = BASE_DIR / '_testfolder' / 'label' - # Lookup references - part = Part.objects.first() parts = Part.objects.all()[:2] - plugin_ref = 'samplelabelprinter' - label = PartLabel.objects.first() - url = self.do_url([part], plugin_ref, label) + template = LabelTemplate.objects.filter(enabled=True, model_type='part').first() + + self.assertIsNotNone(template) + self.assertTrue(template.enabled) + + url = self.printing_url - # Non-existing plugin - response = self.get(f'{url}123', expected_code=404) - self.assertIn( - f"Plugin '{plugin_ref}123' not found", str(response.content, 'utf8') + # Template does not exist + response = self.post( + url, {'template': 9999, 'plugin': 9999, 'items': []}, expected_code=400 ) - # Inactive plugin - response = self.get(url, expected_code=400) - self.assertIn( - f"Plugin '{plugin_ref}' is not enabled", str(response.content, 'utf8') + self.assertIn('object does not exist', str(response.data['template'])) + self.assertIn('list may not be empty', str(response.data['items'])) + + # Plugin is not a label plugin + no_valid_plg = registry.get_plugin('digikeyplugin').plugin_config() + + response = self.post( + url, + {'template': template.pk, 'plugin': no_valid_plg.key, 'items': [1, 2, 3]}, + expected_code=400, ) + self.assertIn('Plugin does not support label printing', str(response.data)) + + # Find available plugins + plugins = registry.with_mixin('labels') + self.assertGreater(len(plugins), 0) + + plugin = registry.get_plugin('samplelabelprinter') + config = plugin.plugin_config() + + # Ensure that the plugin is not active + registry.set_plugin_state(plugin.slug, False) + + # Plugin is not active - should return error + response = self.post( + url, + {'template': template.pk, 'plugin': config.key, 'items': [1, 2, 3]}, + expected_code=400, + ) + self.assertIn('Plugin is not active', str(response.data['plugin'])) + # Active plugin self.do_activate_plugin() # Print one part - self.get(url, expected_code=200) + response = self.post( + url, + {'template': template.pk, 'plugin': config.key, 'items': [parts[0].pk]}, + expected_code=201, + ) + + self.assertEqual(response.data['plugin'], 'samplelabelprinter') + self.assertIsNone(response.data['output']) # Print multiple parts - self.get(self.do_url(parts, plugin_ref, label), expected_code=200) + response = self.post( + url, + { + 'template': template.pk, + 'plugin': config.key, + 'items': [item.pk for item in parts], + }, + expected_code=201, + ) + + self.assertEqual(response.data['plugin'], 'samplelabelprinter') + self.assertIsNone(response.data['output']) # Print multiple parts without a plugin - self.get(self.do_url(parts, None, label), expected_code=200) + response = self.post( + url, + {'template': template.pk, 'items': [item.pk for item in parts]}, + expected_code=201, + ) - # Print multiple parts without a plugin in debug mode - response = self.get(self.do_url(parts, None, label), expected_code=200) + self.assertEqual(response.data['plugin'], 'inventreelabel') + self.assertIsNotNone(response.data['output']) data = json.loads(response.content) - self.assertIn('file', data) + self.assertIn('output', data) # Print no part - self.get(self.do_url(None, plugin_ref, label), expected_code=400) + self.post( + url, + {'template': template.pk, 'plugin': plugin.pk, 'items': None}, + expected_code=400, + ) # Test that the labels have been printed # The sample labelling plugin simply prints to file - test_path = BASE_DIR / '_testfolder' / 'label' self.assertTrue(os.path.exists(f'{test_path}.pdf')) # Read the raw .pdf data - ensure it contains some sensible information @@ -183,27 +203,30 @@ def test_printing_process(self): def test_printing_options(self): """Test printing options.""" # Ensure the labels were created - apps.get_app_config('label').create_defaults() + apps.get_app_config('report').create_default_labels() # Lookup references parts = Part.objects.all()[:2] - plugin_ref = 'samplelabelprinter' - label = PartLabel.objects.first() - + template = LabelTemplate.objects.filter(enabled=True, model_type='part').first() self.do_activate_plugin() + plugin = registry.get_plugin(self.plugin_ref) # test options response options = self.options( - self.do_url(parts, plugin_ref, label), expected_code=200 + self.printing_url, data={'plugin': plugin.slug}, expected_code=200 ).json() self.assertIn('amount', options['actions']['POST']) - plg = registry.get_plugin(plugin_ref) - with mock.patch.object(plg, 'print_label') as print_label: + with mock.patch.object(plugin, 'print_label') as print_label: # wrong value type res = self.post( - self.do_url(parts, plugin_ref, label), - data={'amount': '-no-valid-int-'}, + self.printing_url, + { + 'plugin': plugin.slug, + 'template': template.pk, + 'items': [a.pk for a in parts], + 'amount': '-no-valid-int-', + }, expected_code=400, ).json() self.assertIn('amount', res) @@ -211,9 +234,14 @@ def test_printing_options(self): # correct value type self.post( - self.do_url(parts, plugin_ref, label), - data={'amount': 13}, - expected_code=200, + self.printing_url, + { + 'template': template.pk, + 'plugin': plugin.slug, + 'items': [a.pk for a in parts], + 'amount': 13, + }, + expected_code=201, ).json() self.assertEqual( print_label.call_args.kwargs['printing_options'], {'amount': 13} @@ -221,57 +249,15 @@ def test_printing_options(self): def test_printing_endpoints(self): """Cover the endpoints not covered by `test_printing_process`.""" - plugin_ref = 'samplelabelprinter' - # Activate the label components - apps.get_app_config('label').create_defaults() + apps.get_app_config('report').create_default_labels() self.do_activate_plugin() - def run_print_test(label, qs, url_name, url_single): - """Run tests on single and multiple page printing. - - Args: - label: class of the label - qs: class of the base queryset - url_name: url for endpoints - url_single: item lookup reference - """ - label = label.objects.first() - qs = qs.objects.all() - - # List endpoint - self.get( - self.do_url(None, None, None, f'{url_name}-list', url_single), - expected_code=200, - ) + # Test StockItemLabel + self.run_print_test(StockItem, 'stockitem') - # List endpoint with filter - self.get( - self.do_url( - qs[:2], None, None, f'{url_name}-list', url_single, invalid=True - ), - expected_code=200, - ) - - # Single page printing - self.get( - self.do_url(qs[:1], plugin_ref, label, f'{url_name}-print', url_single), - expected_code=200, - ) - - # Multi page printing - self.get( - self.do_url(qs[:2], plugin_ref, label, f'{url_name}-print', url_single), - expected_code=200, - ) - - # Test StockItemLabels - run_print_test(StockItemLabel, StockItem, 'api-stockitem-label', 'item') - - # Test StockLocationLabels - run_print_test( - StockLocationLabel, StockLocation, 'api-stocklocation-label', 'location' - ) + # Test StockLocationLabel + self.run_print_test(StockLocation, 'stocklocation') - # Test PartLabels - run_print_test(PartLabel, Part, 'api-part-label', 'part') + # Test PartLabel + self.run_print_test(Part, 'part') diff --git a/src/backend/InvenTree/plugin/builtin/labels/inventree_label.py b/src/backend/InvenTree/plugin/builtin/labels/inventree_label.py index ed2d6c70d9b8..07bb3c8ef1fb 100644 --- a/src/backend/InvenTree/plugin/builtin/labels/inventree_label.py +++ b/src/backend/InvenTree/plugin/builtin/labels/inventree_label.py @@ -1,10 +1,9 @@ """Default label printing plugin (supports PDF generation).""" from django.core.files.base import ContentFile -from django.http import JsonResponse from django.utils.translation import gettext_lazy as _ -from label.models import LabelOutput, LabelTemplate +from InvenTree.helpers import str2bool from plugin import InvenTreePlugin from plugin.mixins import LabelPrintingMixin, SettingsMixin @@ -19,7 +18,7 @@ class InvenTreeLabelPlugin(LabelPrintingMixin, SettingsMixin, InvenTreePlugin): NAME = 'InvenTreeLabel' TITLE = _('InvenTree PDF label printer') DESCRIPTION = _('Provides native support for printing PDF labels') - VERSION = '1.0.0' + VERSION = '1.1.0' AUTHOR = _('InvenTree contributors') BLOCKING_PRINT = True @@ -33,58 +32,57 @@ class InvenTreeLabelPlugin(LabelPrintingMixin, SettingsMixin, InvenTreePlugin): } } - def print_labels(self, label: LabelTemplate, items: list, request, **kwargs): - """Handle printing of multiple labels. + # Keep track of individual label outputs + # These will be stitched together at the end of printing + outputs = [] + debug = None - - Label outputs are concatenated together, and we return a single PDF file. - - If DEBUG mode is enabled, we return a single HTML file. - """ - debug = self.get_setting('DEBUG') + def before_printing(self): + """Reset the list of label outputs.""" + self.outputs = [] + self.debug = None - outputs = [] - output_file = None + def in_debug_mode(self): + """Check if the plugin is printing in debug mode.""" + if self.debug is None: + self.debug = str2bool(self.get_setting('DEBUG')) - for item in items: - label.object_to_print = item + return self.debug - outputs.append(self.print_label(label, request, debug=debug, **kwargs)) + def print_label(self, **kwargs): + """Print a single label.""" + label = kwargs['label_instance'] + instance = kwargs['item_instance'] - if self.get_setting('DEBUG'): - html = '\n'.join(outputs) + if self.in_debug_mode(): + # In debug mode, return raw HTML output + output = self.render_to_html(label, instance, None, **kwargs) + else: + # Output is already provided + output = kwargs['pdf_file'] + + self.outputs.append(output) + + def get_generated_file(self, **kwargs): + """Return the generated file, by stitching together the individual label outputs.""" + if len(self.outputs) == 0: + return None - output_file = ContentFile(html, 'labels.html') + if self.in_debug_mode(): + # Simple HTML output + data = '\n'.join(self.outputs) + filename = 'labels.html' else: + # Stitch together the PDF outputs pages = [] - # Following process is required to stitch labels together into a single PDF - for output in outputs: + for output in self.outputs: doc = output.get_document() for page in doc.pages: pages.append(page) - pdf = outputs[0].get_document().copy(pages).write_pdf() - - # Create label output file - output_file = ContentFile(pdf, 'labels.pdf') - - # Save the generated file to the database - output = LabelOutput.objects.create(label=output_file, user=request.user) - - return JsonResponse({ - 'file': output.label.url, - 'success': True, - 'message': f'{len(items)} labels generated', - }) - - def print_label(self, label: LabelTemplate, request, **kwargs): - """Handle printing of a single label. - - Returns either a PDF or HTML output, depending on the DEBUG setting. - """ - debug = kwargs.get('debug', self.get_setting('DEBUG')) - - if debug: - return self.render_to_html(label, request, **kwargs) + data = self.outputs[0].get_document().copy(pages).write_pdf() + filename = kwargs.get('filename', 'labels.pdf') - return self.render_to_pdf(label, request, **kwargs) + return ContentFile(data, name=filename) diff --git a/src/backend/InvenTree/plugin/builtin/labels/inventree_machine.py b/src/backend/InvenTree/plugin/builtin/labels/inventree_machine.py index 1d5d8c6651b8..39af2e7ccaf1 100644 --- a/src/backend/InvenTree/plugin/builtin/labels/inventree_machine.py +++ b/src/backend/InvenTree/plugin/builtin/labels/inventree_machine.py @@ -10,11 +10,11 @@ from common.models import InvenTreeUserSetting from InvenTree.serializers import DependentField from InvenTree.tasks import offload_task -from label.models import LabelTemplate from machine.machine_types import LabelPrinterBaseDriver, LabelPrinterMachine from plugin import InvenTreePlugin from plugin.machine import registry from plugin.mixins import LabelPrintingMixin +from report.models import LabelTemplate def get_machine_and_driver(machine_pk: str): @@ -63,7 +63,7 @@ class InvenTreeLabelPlugin(LabelPrintingMixin, InvenTreePlugin): VERSION = '1.0.0' AUTHOR = _('InvenTree contributors') - def print_labels(self, label: LabelTemplate, items, request, **kwargs): + def print_labels(self, label: LabelTemplate, output, items, request, **kwargs): """Print labels implementation that calls the correct machine driver print_labels method.""" machine, driver = get_machine_and_driver( kwargs['printing_options'].get('machine', '') @@ -111,9 +111,10 @@ def __init__(self, *args, **kwargs): """Custom __init__ method to dynamically override the machine choices based on the request.""" super().__init__(*args, **kwargs) - view = kwargs['context']['view'] - template = view.get_object() - items_to_print = view.get_items() + # TODO @matmair Re-enable this when the need is clear + # view = kwargs['context']['view'] + template = None # view.get_object() + items_to_print = None # view.get_items() # get all available printers for each driver machines: list[LabelPrinterMachine] = [] diff --git a/src/backend/InvenTree/plugin/builtin/labels/label_sheet.py b/src/backend/InvenTree/plugin/builtin/labels/label_sheet.py index 5f6ca952e460..bf88e0f132f1 100644 --- a/src/backend/InvenTree/plugin/builtin/labels/label_sheet.py +++ b/src/backend/InvenTree/plugin/builtin/labels/label_sheet.py @@ -12,9 +12,9 @@ from rest_framework import serializers import report.helpers -from label.models import LabelOutput, LabelTemplate from plugin import InvenTreePlugin from plugin.mixins import LabelPrintingMixin, SettingsMixin +from report.models import LabelOutput, LabelTemplate logger = logging.getLogger('inventree') @@ -68,8 +68,13 @@ class InvenTreeLabelSheetPlugin(LabelPrintingMixin, SettingsMixin, InvenTreePlug PrintingOptionsSerializer = LabelPrintingOptionsSerializer - def print_labels(self, label: LabelTemplate, items: list, request, **kwargs): - """Handle printing of the provided labels.""" + def print_labels( + self, label: LabelTemplate, output: LabelOutput, items: list, request, **kwargs + ): + """Handle printing of the provided labels. + + Note that we override the entire print_labels method for this plugin. + """ printing_options = kwargs['printing_options'] # Extract page size for the label sheet @@ -134,15 +139,10 @@ def print_labels(self, label: LabelTemplate, items: list, request, **kwargs): html = weasyprint.HTML(string=html_data) document = html.render().write_pdf() - output_file = ContentFile(document, 'labels.pdf') - - output = LabelOutput.objects.create(label=output_file, user=request.user) - - return JsonResponse({ - 'file': output.label.url, - 'success': True, - 'message': f'{len(items)} labels generated', - }) + output.output = ContentFile(document, 'labels.pdf') + output.progress = 100 + output.complete = True + output.save() def print_page(self, label: LabelTemplate, items: list, request, **kwargs): """Generate a single page of labels. @@ -185,7 +185,7 @@ def print_page(self, label: LabelTemplate, items: list, request, **kwargs): # Render the individual label template # Note that we disable @page styling for this cell = label.render_as_string( - request, target_object=items[idx], insert_page_style=False + items[idx], request, insert_page_style=False ) html += cell except Exception as exc: diff --git a/src/backend/InvenTree/plugin/models.py b/src/backend/InvenTree/plugin/models.py index 065eb4f9af42..c6fee27fd3ad 100644 --- a/src/backend/InvenTree/plugin/models.py +++ b/src/backend/InvenTree/plugin/models.py @@ -7,7 +7,7 @@ from django.contrib import admin from django.contrib.auth.models import User from django.db import models -from django.db.utils import IntegrityError +from django.urls import reverse from django.utils.translation import gettext_lazy as _ import common.models @@ -24,6 +24,11 @@ class PluginConfig(InvenTree.models.MetadataMixin, models.Model): active: Should the plugin be loaded? """ + @staticmethod + def get_api_url(): + """Return the API URL associated with the PluginConfig model.""" + return reverse('api-plugin-list') + class Meta: """Meta for PluginConfig.""" diff --git a/src/backend/InvenTree/plugin/samples/integration/label_sample.py b/src/backend/InvenTree/plugin/samples/integration/label_sample.py index 7e7c5c8645ec..312205314e38 100644 --- a/src/backend/InvenTree/plugin/samples/integration/label_sample.py +++ b/src/backend/InvenTree/plugin/samples/integration/label_sample.py @@ -34,7 +34,9 @@ def print_label(self, **kwargs): print(f"Printing Label: {kwargs['filename']} (User: {kwargs['user']})") pdf_data = kwargs['pdf_data'] - png_file = self.render_to_png(label=None, pdf_data=pdf_data) + png_file = self.render_to_png( + kwargs['label_instance'], kwargs['item_instance'], **kwargs + ) filename = str(BASE_DIR / '_testfolder' / 'label.pdf') diff --git a/src/backend/InvenTree/plugin/samples/integration/report_plugin_sample.py b/src/backend/InvenTree/plugin/samples/integration/report_plugin_sample.py index a0b37b53f17b..d81fcd187395 100644 --- a/src/backend/InvenTree/plugin/samples/integration/report_plugin_sample.py +++ b/src/backend/InvenTree/plugin/samples/integration/report_plugin_sample.py @@ -4,7 +4,7 @@ from plugin import InvenTreePlugin from plugin.mixins import ReportMixin -from report.models import PurchaseOrderReport +from report.models import ReportTemplate class SampleReportPlugin(ReportMixin, InvenTreePlugin): @@ -32,7 +32,7 @@ def add_report_context(self, report_instance, model_instance, request, context): context['random_int'] = self.some_custom_function() # We can also add extra data to the context which is specific to the report type - context['is_purchase_order'] = isinstance(report_instance, PurchaseOrderReport) + context['is_purchase_order'] = report_instance.model_type == 'purchaseorder' # We can also use the 'request' object to add extra context data context['request_method'] = request.method diff --git a/src/backend/InvenTree/plugin/serializers.py b/src/backend/InvenTree/plugin/serializers.py index b2bca31d4a8c..ffe9b066e266 100644 --- a/src/backend/InvenTree/plugin/serializers.py +++ b/src/backend/InvenTree/plugin/serializers.py @@ -268,3 +268,26 @@ class Meta: active_plugins = serializers.IntegerField(read_only=True) registry_errors = serializers.ListField(child=PluginRegistryErrorSerializer()) + + +class PluginRelationSerializer(serializers.PrimaryKeyRelatedField): + """Serializer for a plugin field. Uses the 'slug' of the plugin as the lookup.""" + + def __init__(self, **kwargs): + """Custom init routine for the serializer.""" + kwargs['pk_field'] = 'key' + kwargs['queryset'] = PluginConfig.objects.all() + + super().__init__(**kwargs) + + def use_pk_only_optimization(self): + """Disable the PK optimization.""" + return False + + def to_internal_value(self, data): + """Lookup the PluginConfig object based on the slug.""" + return PluginConfig.objects.filter(key=data).first() + + def to_representation(self, value): + """Return the 'key' of the PluginConfig object.""" + return value.key diff --git a/src/backend/InvenTree/report/admin.py b/src/backend/InvenTree/report/admin.py index 6a715f913403..04cab8734931 100644 --- a/src/backend/InvenTree/report/admin.py +++ b/src/backend/InvenTree/report/admin.py @@ -2,32 +2,32 @@ from django.contrib import admin +from .helpers import report_model_options from .models import ( - BillOfMaterialsReport, - BuildReport, - PurchaseOrderReport, + LabelOutput, + LabelTemplate, ReportAsset, + ReportOutput, ReportSnippet, - ReturnOrderReport, - SalesOrderReport, - StockLocationReport, - TestReport, + ReportTemplate, ) -@admin.register( - BillOfMaterialsReport, - BuildReport, - PurchaseOrderReport, - ReturnOrderReport, - SalesOrderReport, - StockLocationReport, - TestReport, -) -class ReportTemplateAdmin(admin.ModelAdmin): - """Admin class for the various reporting models.""" +@admin.register(LabelTemplate) +@admin.register(ReportTemplate) +class ReportAdmin(admin.ModelAdmin): + """Admin class for the LabelTemplate and ReportTemplate models.""" + + list_display = ('name', 'description', 'model_type', 'enabled') + + list_filter = ('model_type', 'enabled') + + def formfield_for_dbfield(self, db_field, request, **kwargs): + """Provide custom choices for 'model_type' field.""" + if db_field.name == 'model_type': + db_field.choices = report_model_options() - list_display = ('name', 'description', 'template', 'filters', 'enabled', 'revision') + return super().formfield_for_dbfield(db_field, request, **kwargs) @admin.register(ReportSnippet) @@ -42,3 +42,11 @@ class ReportAssetAdmin(admin.ModelAdmin): """Admin class for the ReportAsset model.""" list_display = ('id', 'asset', 'description') + + +@admin.register(LabelOutput) +@admin.register(ReportOutput) +class TemplateOutputAdmin(admin.ModelAdmin): + """Admin class for the TemplateOutput model.""" + + list_display = ('id', 'output', 'progress', 'complete') diff --git a/src/backend/InvenTree/report/api.py b/src/backend/InvenTree/report/api.py index 315c6b015953..d710359b5107 100644 --- a/src/backend/InvenTree/report/api.py +++ b/src/backend/InvenTree/report/api.py @@ -1,164 +1,324 @@ """API functionality for the 'report' app.""" -from django.core.exceptions import FieldError, ValidationError +from django.core.exceptions import ValidationError from django.core.files.base import ContentFile -from django.http import HttpResponse from django.template.exceptions import TemplateDoesNotExist -from django.urls import include, path, re_path +from django.urls import include, path from django.utils.decorators import method_decorator from django.utils.translation import gettext_lazy as _ from django.views.decorators.cache import cache_page, never_cache +from django_filters import rest_framework as rest_filters from django_filters.rest_framework import DjangoFilterBackend +from rest_framework import permissions +from rest_framework.generics import GenericAPIView +from rest_framework.request import clone_request from rest_framework.response import Response -import build.models import common.models +import InvenTree.exceptions import InvenTree.helpers -import order.models -import part.models +import report.helpers import report.models import report.serializers -from InvenTree.api import MetadataView +from InvenTree.api import BulkDeleteMixin, MetadataView from InvenTree.exceptions import log_error from InvenTree.filters import InvenTreeSearchFilter -from InvenTree.mixins import ListCreateAPI, RetrieveAPI, RetrieveUpdateDestroyAPI -from stock.models import StockItem, StockItemAttachment, StockLocation +from InvenTree.mixins import ( + ListAPI, + ListCreateAPI, + RetrieveAPI, + RetrieveUpdateDestroyAPI, +) +from plugin.builtin.labels.inventree_label import InvenTreeLabelPlugin +from plugin.registry import registry -class ReportListView(ListCreateAPI): - """Generic API class for report templates.""" - - filter_backends = [DjangoFilterBackend, InvenTreeSearchFilter] +@method_decorator(cache_page(5), name='dispatch') +class TemplatePrintBase(RetrieveAPI): + """Base class for printing against templates.""" - filterset_fields = ['enabled'] + @method_decorator(never_cache) + def dispatch(self, *args, **kwargs): + """Prevent caching when printing report templates.""" + return super().dispatch(*args, **kwargs) - search_fields = ['name', 'description'] + def check_permissions(self, request): + """Override request method to GET so that also non superusers can print using a post request.""" + if request.method == 'POST': + request = clone_request(request, 'GET') + return super().check_permissions(request) + def post(self, request, *args, **kwargs): + """Respond as if a POST request was provided.""" + return self.get(request, *args, **kwargs) -class ReportFilterMixin: - """Mixin for extracting multiple objects from query params. + def get(self, request, *args, **kwargs): + """GET action for a template printing endpoint. - Each subclass *must* have an attribute called 'ITEM_KEY', - which is used to determine what 'key' is used in the query parameters. + - Items are expected to be passed as a list of valid IDs + """ + # Extract a list of items to print from the queryset + item_ids = [] - This mixin defines a 'get_items' method which provides a generic implementation - to return a list of matching database model instances - """ + for value in request.query_params.get('items', '').split(','): + try: + item_ids.append(int(value)) + except Exception: + pass - # Database model for instances to actually be "printed" against this report template - ITEM_MODEL = None + template = self.get_object() - # Default key for looking up database model instances - ITEM_KEY = 'item' + items = template.get_model().objects.filter(pk__in=item_ids) - def get_items(self): - """Return a list of database objects from query parameters.""" - if not self.ITEM_MODEL: - raise NotImplementedError( - f'ITEM_MODEL attribute not defined for {__class__}' + if len(items) == 0: + # At least one item must be provided + return Response( + {'error': _('No valid objects provided to template')}, status=400 ) - ids = [] + return self.print(request, items) - # Construct a list of possible query parameter value options - # e.g. if self.ITEM_KEY = 'order' -> ['order', 'order[]', 'orders', 'orders[]'] - for k in [self.ITEM_KEY + x for x in ['', '[]', 's', 's[]']]: - if ids := self.request.query_params.getlist(k, []): - # Return the first list of matches - break - # Next we must validated each provided object ID - valid_ids = [] +class ReportFilterBase(rest_filters.FilterSet): + """Base filter class for label and report templates.""" - for id in ids: - try: - valid_ids.append(int(id)) - except ValueError: - pass + enabled = rest_filters.BooleanFilter() + + model_type = rest_filters.ChoiceFilter( + choices=report.helpers.report_model_options(), label=_('Model Type') + ) - # Filter queryset by matching ID values - return self.ITEM_MODEL.objects.filter(pk__in=valid_ids) + items = rest_filters.CharFilter(method='filter_items', label=_('Items')) - def filter_queryset(self, queryset): - """Filter the queryset based on the provided report ID values. + def filter_items(self, queryset, name, values): + """Filter against a comma-separated list of provided items. - As each 'report' instance may optionally define its own filters, - the resulting queryset is the 'union' of the two + Note: This filter is only applied if the 'model_type' is also provided. """ - queryset = super().filter_queryset(queryset) + model_type = self.data.get('model_type', None) + values = values.strip().split(',') - items = self.get_items() + if model_class := report.helpers.report_model_from_name(model_type): + model_items = model_class.objects.filter(pk__in=values) - if len(items) > 0: - """At this point, we are basically forced to be inefficient: + # Ensure that we have already filtered by model_type + queryset = queryset.filter(model_type=model_type) - We need to compare the 'filters' string of each report template, - and see if it matches against each of the requested items. + # Construct a list of templates which match the list of provided IDs + matching_template_ids = [] - In practice, this is not too bad. - """ + for template in queryset.all(): + filters = template.get_filters() + results = model_items.filter(**filters) + # If the resulting queryset is *shorter* than the provided items, then this template does not match + if results.count() == model_items.count(): + matching_template_ids.append(template.pk) - valid_report_ids = set() + queryset = queryset.filter(pk__in=matching_template_ids) - for report in queryset.all(): - matches = True + return queryset - try: - filters = InvenTree.helpers.validateFilterString(report.filters) - except ValidationError: - continue - for item in items: - item_query = self.ITEM_MODEL.objects.filter(pk=item.pk) +class ReportFilter(ReportFilterBase): + """Filter class for report template list.""" - try: - if not item_query.filter(**filters).exists(): - matches = False - break - except FieldError: - matches = False - break + class Meta: + """Filter options.""" - # Matched all items - if matches: - valid_report_ids.add(report.pk) + model = report.models.ReportTemplate + fields = ['landscape'] - # Reduce queryset to only valid matches - queryset = queryset.filter(pk__in=list(valid_report_ids)) - return queryset +class LabelFilter(ReportFilterBase): + """Filter class for label template list.""" + class Meta: + """Filter options.""" -@method_decorator(cache_page(5), name='dispatch') -class ReportPrintMixin: - """Mixin for printing reports.""" + model = report.models.LabelTemplate + fields = [] + + +class LabelPrint(GenericAPIView): + """API endpoint for printing labels.""" + + permission_classes = [permissions.IsAuthenticated] + serializer_class = report.serializers.LabelPrintSerializer + + 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 plugin_slug is None: + # Use the default label printing plugin + plugin_slug = InvenTreeLabelPlugin.NAME.lower() + + plugin = None + + try: + plugin_config = PluginConfig.objects.get(key=plugin_slug) + plugin = plugin_config.plugin + except (ValueError, PluginConfig.DoesNotExist): + pass + + error = None + + if not plugin: + error = _('Plugin not found') + elif not plugin.is_active(): + error = _('Plugin is not active') + elif not plugin.mixin_enabled('labels'): + error = _('Plugin does not support label printing') + + if error: + plugin = None + + if raise_error: + raise ValidationError({'plugin': error}) + + return plugin + + 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, + context=self.get_serializer_context(), + ) + + return None + + 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', None) + # Legacy url based lookup + if not plugin_key: + plugin_key = self.request.query_params.get('plugin', None) + plugin = self.get_plugin_class(plugin_key) + plugin_serializer = self.get_plugin_serializer(plugin) + + if plugin_serializer: + kwargs['plugin_serializer'] = plugin_serializer + + serializer = super().get_serializer(*args, **kwargs) + return serializer @method_decorator(never_cache) - def dispatch(self, *args, **kwargs): - """Prevent caching when printing report templates.""" - return super().dispatch(*args, **kwargs) + def post(self, request, *args, **kwargs): + """POST action for printing labels.""" + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) - def report_callback(self, object, report, request): - """Callback function for each object/report combination. + template = serializer.validated_data['template'] - Allows functionality to be performed before returning the consolidated PDF + if template.width <= 0 or template.height <= 0: + raise ValidationError({'template': _('Invalid label dimensions')}) - Arguments: - object: The model instance to be printed - report: The individual PDF file object - request: The request instance associated with this print call - """ - ... + items = serializer.validated_data['items'] + + # Default to the InvenTreeLabelPlugin + plugin_key = InvenTreeLabelPlugin.NAME.lower() + + if plugin_config := serializer.validated_data.get('plugin', None): + plugin_key = plugin_config.key + + plugin = self.get_plugin_class(plugin_key, raise_error=True) + + instances = template.get_model().objects.filter(pk__in=items) + + if instances.count() == 0: + raise ValidationError(_('No valid items provided to template')) + + return self.print(template, instances, plugin, request) + + def print(self, template, items_to_print, plugin, request): + """Print this label template against a number of provided items.""" + if plugin_serializer := plugin.get_printing_options_serializer( + request, data=request.data, context=self.get_serializer_context() + ): + plugin_serializer.is_valid(raise_exception=True) + + # Create a new LabelOutput instance to print against + output = report.models.LabelOutput.objects.create( + template=template, + items=len(items_to_print), + plugin=plugin.slug, + user=request.user, + progress=0, + complete=False, + ) + + try: + plugin.before_printing() + plugin.print_labels( + template, + output, + items_to_print, + request, + printing_options=(plugin_serializer.data if plugin_serializer else {}), + ) + plugin.after_printing() + except ValidationError as e: + raise (e) + except Exception as e: + InvenTree.exceptions.log_error(f'plugins.{plugin.slug}.print_labels') + raise ValidationError([_('Error printing label'), str(e)]) + + output.refresh_from_db() + + return Response( + report.serializers.LabelOutputSerializer(output).data, status=201 + ) - def print(self, request, items_to_print): - """Print this report template against a number of pre-validated items.""" - if len(items_to_print) == 0: - # No valid items provided, return an error message - data = {'error': _('No valid objects provided to template')} - return Response(data, status=400) +class LabelTemplateList(ListCreateAPI): + """API endpoint for viewing list of LabelTemplate objects.""" + queryset = report.models.LabelTemplate.objects.all() + serializer_class = report.serializers.LabelTemplateSerializer + filterset_class = LabelFilter + filter_backends = [DjangoFilterBackend, InvenTreeSearchFilter] + search_fields = ['name', 'description'] + ordering_fields = ['name', 'enabled'] + + +class LabelTemplateDetail(RetrieveUpdateDestroyAPI): + """Detail API endpoint for label template model.""" + + queryset = report.models.LabelTemplate.objects.all() + serializer_class = report.serializers.LabelTemplateSerializer + + +class ReportPrint(GenericAPIView): + """API endpoint for printing reports.""" + + permission_classes = [permissions.IsAuthenticated] + serializer_class = report.serializers.ReportPrintSerializer + + @method_decorator(never_cache) + def post(self, request, *args, **kwargs): + """POST action for printing a report.""" + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + + template = serializer.validated_data['template'] + items = serializer.validated_data['items'] + + instances = template.get_model().objects.filter(pk__in=items) + + if instances.count() == 0: + raise ValidationError(_('No valid items provided to template')) + + return self.print(template, instances, request) + + def print(self, template, items_to_print, request): + """Print this report template against a number of provided items.""" outputs = [] # In debug mode, generate single HTML output, rather than PDF @@ -171,25 +331,30 @@ def print(self, request, items_to_print): try: # Merge one or more PDF files into a single download - for item in items_to_print: - report = self.get_object() - report.object_to_print = item + for instance in items_to_print: + context = template.get_context(instance, request) + report_name = template.generate_filename(context) - report_name = report.generate_filename(request) - output = report.render(request) + output = template.render(instance, request) - # Run report callback for each generated report - self.report_callback(item, output, request) + # Provide generated report to any interested plugins + for plugin in registry.with_mixin('report'): + try: + plugin.report_callback(self, instance, output, request) + except Exception as e: + InvenTree.exceptions.log_error( + f'plugins.{plugin.slug}.report_callback' + ) try: if debug_mode: - outputs.append(report.render_as_string(request)) + outputs.append(template.render_as_string(instance, request)) else: - outputs.append(output) + outputs.append(template.render(instance, request)) except TemplateDoesNotExist as e: template = str(e) if not template: - template = report.template + template = template.template return Response( { @@ -206,9 +371,8 @@ def print(self, request, items_to_print): if debug_mode: """Concatenate all rendered templates into a single HTML string, and return the string as a HTML response.""" - html = '\n'.join(outputs) - - return HttpResponse(html) + data = '\n'.join(outputs) + report_name = report_name.replace('.pdf', '.html') else: """Concatenate all rendered pages into a single PDF object, and return the resulting document!""" @@ -220,13 +384,13 @@ def print(self, request, items_to_print): for page in doc.pages: pages.append(page) - pdf = outputs[0].get_document().copy(pages).write_pdf() + data = outputs[0].get_document().copy(pages).write_pdf() except TemplateDoesNotExist as e: template = str(e) if not template: - template = report.template + template = template.template return Response( { @@ -237,14 +401,6 @@ def print(self, request, items_to_print): status=400, ) - inline = common.models.InvenTreeUserSetting.get_setting( - 'REPORT_INLINE', user=request.user, cache=False - ) - - return InvenTree.helpers.DownloadFile( - pdf, report_name, content_type='application/pdf', inline=inline - ) - except Exception as exc: # Log the exception to the database if InvenTree.helpers.str2bool( @@ -261,242 +417,39 @@ def print(self, request, items_to_print): 'path': request.path, }) - def get(self, request, *args, **kwargs): - """Default implementation of GET for a print endpoint. - - Note that it expects the class has defined a get_items() method - """ - items = self.get_items() - return self.print(request, items) - - -class StockItemTestReportMixin(ReportFilterMixin): - """Mixin for StockItemTestReport report template.""" - - ITEM_MODEL = StockItem - ITEM_KEY = 'item' - queryset = report.models.TestReport.objects.all() - serializer_class = report.serializers.TestReportSerializer - - -class StockItemTestReportList(StockItemTestReportMixin, ReportListView): - """API endpoint for viewing list of TestReport objects. - - Filterable by: - - - enabled: Filter by enabled / disabled status - - item: Filter by stock item(s) - """ - - pass - - -class StockItemTestReportDetail(StockItemTestReportMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single TestReport object.""" - - pass - - -class StockItemTestReportPrint(StockItemTestReportMixin, ReportPrintMixin, RetrieveAPI): - """API endpoint for printing a TestReport object.""" - - def report_callback(self, item, report, request): - """Callback to (optionally) save a copy of the generated report.""" - if common.models.InvenTreeSetting.get_setting( - 'REPORT_ATTACH_TEST_REPORT', cache=False - ): - # Construct a PDF file object - try: - pdf = report.get_document().write_pdf() - pdf_content = ContentFile(pdf, 'test_report.pdf') - except TemplateDoesNotExist: - return - - StockItemAttachment.objects.create( - attachment=pdf_content, - stock_item=item, - user=request.user, - comment=_('Test report'), - ) - - -class BOMReportMixin(ReportFilterMixin): - """Mixin for BillOfMaterialsReport report template.""" - - ITEM_MODEL = part.models.Part - ITEM_KEY = 'part' - - queryset = report.models.BillOfMaterialsReport.objects.all() - serializer_class = report.serializers.BOMReportSerializer - - -class BOMReportList(BOMReportMixin, ReportListView): - """API endpoint for viewing a list of BillOfMaterialReport objects. - - Filterably by: - - - enabled: Filter by enabled / disabled status - - part: Filter by part(s) - """ - - pass - - -class BOMReportDetail(BOMReportMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single BillOfMaterialReport object.""" - - pass - - -class BOMReportPrint(BOMReportMixin, ReportPrintMixin, RetrieveAPI): - """API endpoint for printing a BillOfMaterialReport object.""" - - pass - - -class BuildReportMixin(ReportFilterMixin): - """Mixin for the BuildReport report template.""" - - ITEM_MODEL = build.models.Build - ITEM_KEY = 'build' - - queryset = report.models.BuildReport.objects.all() - serializer_class = report.serializers.BuildReportSerializer - - -class BuildReportList(BuildReportMixin, ReportListView): - """API endpoint for viewing a list of BuildReport objects. - - Can be filtered by: - - - enabled: Filter by enabled / disabled status - - build: Filter by Build object - """ - - pass - - -class BuildReportDetail(BuildReportMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single BuildReport object.""" - - pass - - -class BuildReportPrint(BuildReportMixin, ReportPrintMixin, RetrieveAPI): - """API endpoint for printing a BuildReport.""" - - pass - - -class PurchaseOrderReportMixin(ReportFilterMixin): - """Mixin for the PurchaseOrderReport report template.""" - - ITEM_MODEL = order.models.PurchaseOrder - ITEM_KEY = 'order' - - queryset = report.models.PurchaseOrderReport.objects.all() - serializer_class = report.serializers.PurchaseOrderReportSerializer - - -class PurchaseOrderReportList(PurchaseOrderReportMixin, ReportListView): - """API list endpoint for the PurchaseOrderReport model.""" - - pass - - -class PurchaseOrderReportDetail(PurchaseOrderReportMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single PurchaseOrderReport object.""" - - pass - - -class PurchaseOrderReportPrint(PurchaseOrderReportMixin, ReportPrintMixin, RetrieveAPI): - """API endpoint for printing a PurchaseOrderReport object.""" - - pass - - -class SalesOrderReportMixin(ReportFilterMixin): - """Mixin for the SalesOrderReport report template.""" - - ITEM_MODEL = order.models.SalesOrder - ITEM_KEY = 'order' - - queryset = report.models.SalesOrderReport.objects.all() - serializer_class = report.serializers.SalesOrderReportSerializer - - -class SalesOrderReportList(SalesOrderReportMixin, ReportListView): - """API list endpoint for the SalesOrderReport model.""" - - pass - - -class SalesOrderReportDetail(SalesOrderReportMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single SalesOrderReport object.""" - - pass - - -class SalesOrderReportPrint(SalesOrderReportMixin, ReportPrintMixin, RetrieveAPI): - """API endpoint for printing a PurchaseOrderReport object.""" - - pass - - -class ReturnOrderReportMixin(ReportFilterMixin): - """Mixin for the ReturnOrderReport report template.""" - - ITEM_MODEL = order.models.ReturnOrder - ITEM_KEY = 'order' - - queryset = report.models.ReturnOrderReport.objects.all() - serializer_class = report.serializers.ReturnOrderReportSerializer - - -class ReturnOrderReportList(ReturnOrderReportMixin, ReportListView): - """API list endpoint for the ReturnOrderReport model.""" - - pass - - -class ReturnOrderReportDetail(ReturnOrderReportMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single ReturnOrderReport object.""" - - pass - - -class ReturnOrderReportPrint(ReturnOrderReportMixin, ReportPrintMixin, RetrieveAPI): - """API endpoint for printing a ReturnOrderReport object.""" - - pass - - -class StockLocationReportMixin(ReportFilterMixin): - """Mixin for StockLocation report template.""" - - ITEM_MODEL = StockLocation - ITEM_KEY = 'location' - queryset = report.models.StockLocationReport.objects.all() - serializer_class = report.serializers.StockLocationReportSerializer - - -class StockLocationReportList(StockLocationReportMixin, ReportListView): - """API list endpoint for the StockLocationReportList model.""" + # Generate a report output object + # TODO: This should be moved to a separate function + # TODO: Allow background printing of reports, with progress reporting + output = report.models.ReportOutput.objects.create( + template=template, + items=len(items_to_print), + user=request.user, + progress=100, + complete=True, + output=ContentFile(data, report_name), + ) - pass + return Response( + report.serializers.ReportOutputSerializer(output).data, status=201 + ) -class StockLocationReportDetail(StockLocationReportMixin, RetrieveUpdateDestroyAPI): - """API endpoint for a single StockLocationReportDetail object.""" +class ReportTemplateList(ListCreateAPI): + """API endpoint for viewing list of ReportTemplate objects.""" - pass + queryset = report.models.ReportTemplate.objects.all() + serializer_class = report.serializers.ReportTemplateSerializer + filterset_class = ReportFilter + filter_backends = [DjangoFilterBackend, InvenTreeSearchFilter] + search_fields = ['name', 'description'] + ordering_fields = ['name', 'enabled'] -class StockLocationReportPrint(StockLocationReportMixin, ReportPrintMixin, RetrieveAPI): - """API endpoint for printing a StockLocationReportPrint object.""" +class ReportTemplateDetail(RetrieveUpdateDestroyAPI): + """Detail API endpoint for report template model.""" - pass + queryset = report.models.ReportTemplate.objects.all() + serializer_class = report.serializers.ReportTemplateSerializer class ReportSnippetList(ListCreateAPI): @@ -527,238 +480,104 @@ class ReportAssetDetail(RetrieveUpdateDestroyAPI): serializer_class = report.serializers.ReportAssetSerializer -report_api_urls = [ - # Report assets - path( - 'asset/', - include([ - path( - '/', ReportAssetDetail.as_view(), name='api-report-asset-detail' - ), - path('', ReportAssetList.as_view(), name='api-report-asset-list'), - ]), - ), - # Report snippets - path( - 'snippet/', - include([ - path( - '/', - ReportSnippetDetail.as_view(), - name='api-report-snippet-detail', - ), - path('', ReportSnippetList.as_view(), name='api-report-snippet-list'), - ]), - ), - # Purchase order reports +class LabelOutputList(BulkDeleteMixin, ListAPI): + """List endpoint for LabelOutput objects.""" + + queryset = report.models.LabelOutput.objects.all() + serializer_class = report.serializers.LabelOutputSerializer + + +class ReportOutputList(BulkDeleteMixin, ListAPI): + """List endpoint for ReportOutput objects.""" + + queryset = report.models.ReportOutput.objects.all() + serializer_class = report.serializers.ReportOutputSerializer + + +label_api_urls = [ + # Printing endpoint + path('print/', LabelPrint.as_view(), name='api-label-print'), + # Label templates path( - 'po/', + 'template/', include([ - # Detail views path( '/', include([ - re_path( - r'print/?', - PurchaseOrderReportPrint.as_view(), - name='api-po-report-print', - ), path( 'metadata/', MetadataView.as_view(), - {'model': report.models.PurchaseOrderReport}, - name='api-po-report-metadata', + {'model': report.models.LabelTemplate}, + name='api-label-template-metadata', ), path( '', - PurchaseOrderReportDetail.as_view(), - name='api-po-report-detail', + LabelTemplateDetail.as_view(), + name='api-label-template-detail', ), ]), ), - # List view - path('', PurchaseOrderReportList.as_view(), name='api-po-report-list'), + path('', LabelTemplateList.as_view(), name='api-label-template-list'), ]), ), - # Sales order reports + # Label outputs path( - 'so/', - include([ - # Detail views - path( - '/', - include([ - re_path( - r'print/?', - SalesOrderReportPrint.as_view(), - name='api-so-report-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'model': report.models.SalesOrderReport}, - name='api-so-report-metadata', - ), - path( - '', - SalesOrderReportDetail.as_view(), - name='api-so-report-detail', - ), - ]), - ), - path('', SalesOrderReportList.as_view(), name='api-so-report-list'), - ]), + 'output/', + include([path('', LabelOutputList.as_view(), name='api-label-output-list')]), ), - # Return order reports +] + +report_api_urls = [ + # Printing endpoint + path('print/', ReportPrint.as_view(), name='api-report-print'), + # Report templates path( - 'ro/', + 'template/', include([ path( '/', include([ - path( - r'print/', - ReturnOrderReportPrint.as_view(), - name='api-return-order-report-print', - ), path( 'metadata/', MetadataView.as_view(), - {'model': report.models.ReturnOrderReport}, - name='api-so-report-metadata', + {'model': report.models.ReportTemplate}, + name='api-report-template-metadata', ), path( '', - ReturnOrderReportDetail.as_view(), - name='api-return-order-report-detail', - ), - ]), - ), - path( - '', ReturnOrderReportList.as_view(), name='api-return-order-report-list' - ), - ]), - ), - # Build reports - path( - 'build/', - include([ - # Detail views - path( - '/', - include([ - re_path( - r'print/?', - BuildReportPrint.as_view(), - name='api-build-report-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'model': report.models.BuildReport}, - name='api-build-report-metadata', - ), - path( - '', BuildReportDetail.as_view(), name='api-build-report-detail' + ReportTemplateDetail.as_view(), + name='api-report-template-detail', ), ]), ), - # List view - path('', BuildReportList.as_view(), name='api-build-report-list'), + path('', ReportTemplateList.as_view(), name='api-report-template-list'), ]), ), - # Bill of Material reports + # Generated report outputs path( - 'bom/', - include([ - # Detail views - path( - '/', - include([ - re_path( - r'print/?', - BOMReportPrint.as_view(), - name='api-bom-report-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'model': report.models.BillOfMaterialsReport}, - name='api-bom-report-metadata', - ), - path('', BOMReportDetail.as_view(), name='api-bom-report-detail'), - ]), - ), - # List view - path('', BOMReportList.as_view(), name='api-bom-report-list'), - ]), + 'output/', + include([path('', ReportOutputList.as_view(), name='api-report-output-list')]), ), - # Stock item test reports + # Report assets path( - 'test/', + 'asset/', include([ - # Detail views - path( - '/', - include([ - re_path( - r'print/?', - StockItemTestReportPrint.as_view(), - name='api-stockitem-testreport-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'report': report.models.TestReport}, - name='api-stockitem-testreport-metadata', - ), - path( - '', - StockItemTestReportDetail.as_view(), - name='api-stockitem-testreport-detail', - ), - ]), - ), - # List view path( - '', - StockItemTestReportList.as_view(), - name='api-stockitem-testreport-list', + '/', ReportAssetDetail.as_view(), name='api-report-asset-detail' ), + path('', ReportAssetList.as_view(), name='api-report-asset-list'), ]), ), - # Stock Location reports (Stock Location Reports -> sir) + # Report snippets path( - 'slr/', + 'snippet/', include([ - # Detail views path( '/', - include([ - re_path( - r'print/?', - StockLocationReportPrint.as_view(), - name='api-stocklocation-report-print', - ), - path( - 'metadata/', - MetadataView.as_view(), - {'report': report.models.StockLocationReport}, - name='api-stocklocation-report-metadata', - ), - path( - '', - StockLocationReportDetail.as_view(), - name='api-stocklocation-report-detail', - ), - ]), - ), - # List view - path( - '', - StockLocationReportList.as_view(), - name='api-stocklocation-report-list', + ReportSnippetDetail.as_view(), + name='api-report-snippet-detail', ), + path('', ReportSnippetList.as_view(), name='api-report-snippet-list'), ]), ), ] diff --git a/src/backend/InvenTree/report/apps.py b/src/backend/InvenTree/report/apps.py index 7926d4f76a95..c5c874f79ea5 100644 --- a/src/backend/InvenTree/report/apps.py +++ b/src/backend/InvenTree/report/apps.py @@ -1,18 +1,25 @@ """Config options for the report app.""" import logging +import os from pathlib import Path from django.apps import AppConfig +from django.core.exceptions import AppRegistryNotReady +from django.core.files.base import ContentFile +from django.db.utils import IntegrityError, OperationalError, ProgrammingError -from generic.templating.apps import TemplatingMixin +from maintenance_mode.core import maintenance_mode_on, set_maintenance_mode +import InvenTree.ready -class ReportConfig(TemplatingMixin, AppConfig): +logger = logging.getLogger('inventree') + + +class ReportConfig(AppConfig): """Configuration class for the "report" app.""" name = 'report' - db = 'template' def ready(self): """This function is called whenever the app is loaded.""" @@ -22,103 +29,192 @@ def ready(self): super().ready() - def create_defaults(self): - """Create all default templates.""" + # skip loading if plugin registry is not loaded or we run in a background thread + if ( + not InvenTree.ready.isPluginRegistryLoaded() + or not InvenTree.ready.isInMainThread() + ): + return + + if not InvenTree.ready.canAppAccessDatabase(allow_test=False): + return # pragma: no cover + + with maintenance_mode_on(): + try: + self.create_default_labels() + self.create_default_reports() + except ( + AppRegistryNotReady, + IntegrityError, + OperationalError, + ProgrammingError, + ): + logger.warning( + 'Database not ready for creating default report templates' + ) + + set_maintenance_mode(False) + + def create_default_labels(self): + """Create default label templates.""" + # Test if models are ready + try: + import report.models + except Exception: # pragma: no cover + # Database is not ready yet + return + + assert bool(report.models.LabelTemplate is not None) + + label_templates = [ + { + 'file': 'part_label.html', + 'name': 'InvenTree Part Label', + 'description': 'Sample part label', + 'model_type': 'part', + }, + { + 'file': 'part_label_code128.html', + 'name': 'InvenTree Part Label (Code128)', + 'description': 'Sample part label with Code128 barcode', + 'model_type': 'part', + }, + { + 'file': 'stockitem_qr.html', + 'name': 'InvenTree Stock Item Label (QR)', + 'description': 'Sample stock item label with QR code', + 'model_type': 'stockitem', + }, + { + 'file': 'stocklocation_qr_and_text.html', + 'name': 'InvenTree Stock Location Label (QR + Text)', + 'description': 'Sample stock item label with QR code and text', + 'model_type': 'stocklocation', + }, + { + 'file': 'stocklocation_qr.html', + 'name': 'InvenTree Stock Location Label (QR)', + 'description': 'Sample stock location label with QR code', + 'model_type': 'stocklocation', + }, + { + 'file': 'buildline_label.html', + 'name': 'InvenTree Build Line Label', + 'description': 'Sample build line label', + 'model_type': 'buildline', + }, + ] + + for template in label_templates: + # Ignore matching templates which are already in the database + if report.models.LabelTemplate.objects.filter( + name=template['name'] + ).exists(): + continue + + filename = template.pop('file') + + template_file = Path(__file__).parent.joinpath( + 'templates', 'label', filename + ) + + if not template_file.exists(): + logger.warning("Missing template file: '%s'", template['name']) + continue + + # Read the existing template file + data = template_file.open('r').read() + + logger.info("Creating new label template: '%s'", template['name']) + + # Create a new entry + report.models.LabelTemplate.objects.create( + **template, template=ContentFile(data, os.path.basename(filename)) + ) + + def create_default_reports(self): + """Create default report templates.""" # Test if models are ready try: import report.models except Exception: # pragma: no cover # Database is not ready yet return - assert bool(report.models.TestReport is not None) - - # Create the categories - self.create_template_dir( - report.models.TestReport, - [ - { - 'file': 'inventree_test_report.html', - 'name': 'InvenTree Test Report', - 'description': 'Stock item test report', - } - ], - ) - - self.create_template_dir( - report.models.BuildReport, - [ - { - 'file': 'inventree_build_order.html', - 'name': 'InvenTree Build Order', - 'description': 'Build Order job sheet', - } - ], - ) - - self.create_template_dir( - report.models.BillOfMaterialsReport, - [ - { - 'file': 'inventree_bill_of_materials_report.html', - 'name': 'Bill of Materials', - 'description': 'Bill of Materials report', - } - ], - ) - - self.create_template_dir( - report.models.PurchaseOrderReport, - [ - { - 'file': 'inventree_po_report.html', - 'name': 'InvenTree Purchase Order', - 'description': 'Purchase Order example report', - } - ], - ) - - self.create_template_dir( - report.models.SalesOrderReport, - [ - { - 'file': 'inventree_so_report.html', - 'name': 'InvenTree Sales Order', - 'description': 'Sales Order example report', - } - ], - ) - - self.create_template_dir( - report.models.ReturnOrderReport, - [ - { - 'file': 'inventree_return_order_report.html', - 'name': 'InvenTree Return Order', - 'description': 'Return Order example report', - } - ], - ) - - self.create_template_dir( - report.models.StockLocationReport, - [ - { - 'file': 'inventree_slr_report.html', - 'name': 'InvenTree Stock Location', - 'description': 'Stock Location example report', - } - ], - ) - - def get_src_dir(self, ref_name): - """Get the source directory.""" - return Path(__file__).parent.joinpath('templates', self.name) - - def get_new_obj_data(self, data, filename): - """Get the data for a new template db object.""" - return { - 'name': data['name'], - 'description': data['description'], - 'template': filename, - 'enabled': True, - } + + assert bool(report.models.ReportTemplate is not None) + + # Construct a set of default ReportTemplate instances + report_templates = [ + { + 'file': 'inventree_bill_of_materials_report.html', + 'name': 'InvenTree Bill of Materials', + 'description': 'Sample bill of materials report', + 'model_type': 'part', + }, + { + 'file': 'inventree_build_order_report.html', + 'name': 'InvenTree Build Order', + 'description': 'Sample build order report', + 'model_type': 'build', + }, + { + 'file': 'inventree_purchase_order_report.html', + 'name': 'InvenTree Purchase Order', + 'description': 'Sample purchase order report', + 'model_type': 'purchaseorder', + 'filename_pattern': 'PurchaseOrder-{{ reference }}.pdf', + }, + { + 'file': 'inventree_sales_order_report.html', + 'name': 'InvenTree Sales Order', + 'description': 'Sample sales order report', + 'model_type': 'salesorder', + 'filename_pattern': 'SalesOrder-{{ reference }}.pdf', + }, + { + 'file': 'inventree_return_order_report.html', + 'name': 'InvenTree Return Order', + 'description': 'Sample return order report', + 'model_type': 'returnorder', + 'filename_pattern': 'ReturnOrder-{{ reference }}.pdf', + }, + { + 'file': 'inventree_test_report.html', + 'name': 'InvenTree Test Report', + 'description': 'Sample stock item test report', + 'model_type': 'stockitem', + }, + { + 'file': 'inventree_stock_location_report.html', + 'name': 'InvenTree Stock Location Report', + 'description': 'Sample stock location report', + 'model_type': 'stocklocation', + }, + ] + + for template in report_templates: + # Ignore matching templates which are already in the database + if report.models.ReportTemplate.objects.filter( + name=template['name'] + ).exists(): + continue + + filename = template.pop('file') + + template_file = Path(__file__).parent.joinpath( + 'templates', 'report', filename + ) + + if not template_file.exists(): + logger.warning("Missing template file: '%s'", template['name']) + continue + + # Read the existing template file + data = template_file.open('r').read() + + logger.info("Creating new report template: '%s'", template['name']) + + # Create a new entry + report.models.ReportTemplate.objects.create( + **template, template=ContentFile(data, os.path.basename(filename)) + ) diff --git a/src/backend/InvenTree/report/helpers.py b/src/backend/InvenTree/report/helpers.py index 43f2baab722c..c0720ce348d9 100644 --- a/src/backend/InvenTree/report/helpers.py +++ b/src/backend/InvenTree/report/helpers.py @@ -9,6 +9,32 @@ logger = logging.getLogger('inventree') +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)) + + +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 + + +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() + ] + + def report_page_size_options(): """Returns a list of page size options for PDF reports.""" return [ diff --git a/src/backend/InvenTree/report/migrations/0001_initial.py b/src/backend/InvenTree/report/migrations/0001_initial.py index 8b5c2af09f39..60b199c44c3e 100644 --- a/src/backend/InvenTree/report/migrations/0001_initial.py +++ b/src/backend/InvenTree/report/migrations/0001_initial.py @@ -17,7 +17,7 @@ class Migration(migrations.Migration): name='ReportAsset', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('asset', models.FileField(help_text='Report asset file', upload_to=report.models.rename_asset)), + ('asset', models.FileField(help_text='Report asset file', upload_to='report/assets')), ('description', models.CharField(help_text='Asset file description', max_length=250)), ], ), @@ -26,7 +26,7 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='Template name', max_length=100, unique=True)), - ('template', models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm', 'tex'])])), + ('template', models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm', 'tex'])])), ('description', models.CharField(help_text='Report template description', max_length=250)), ], options={ @@ -38,9 +38,9 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='Template name', max_length=100, unique=True)), - ('template', models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm', 'tex'])])), + ('template', models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm', 'tex'])])), ('description', models.CharField(help_text='Report template description', max_length=250)), - ('part_filters', models.CharField(blank=True, help_text='Part query filters (comma-separated list of key=value pairs)', max_length=250, validators=[report.models.validateFilterString])), + ('part_filters', models.CharField(blank=True, help_text='Part query filters (comma-separated list of key=value pairs)', max_length=250)), ], options={ 'abstract': False, diff --git a/src/backend/InvenTree/report/migrations/0005_auto_20210119_0815.py b/src/backend/InvenTree/report/migrations/0005_auto_20210119_0815.py index 717176e39090..714267e6fdbd 100644 --- a/src/backend/InvenTree/report/migrations/0005_auto_20210119_0815.py +++ b/src/backend/InvenTree/report/migrations/0005_auto_20210119_0815.py @@ -2,7 +2,6 @@ import django.core.validators from django.db import migrations, models -import report.models class Migration(migrations.Migration): @@ -20,7 +19,7 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='testreport', name='filters', - field=models.CharField(blank=True, help_text='Part query filters (comma-separated list of key=value pairs)', max_length=250, validators=[report.models.validate_stock_item_report_filters], verbose_name='Filters'), + field=models.CharField(blank=True, help_text='Part query filters (comma-separated list of key=value pairs)', max_length=250, verbose_name='Filters'), ), migrations.AlterField( model_name='testreport', @@ -30,6 +29,6 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='testreport', name='template', - field=models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm', 'tex'])], verbose_name='Template'), + field=models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm', 'tex'])], verbose_name='Template'), ), ] diff --git a/src/backend/InvenTree/report/migrations/0006_reportsnippet.py b/src/backend/InvenTree/report/migrations/0006_reportsnippet.py index 6875ebb5306a..8a550b1b3fce 100644 --- a/src/backend/InvenTree/report/migrations/0006_reportsnippet.py +++ b/src/backend/InvenTree/report/migrations/0006_reportsnippet.py @@ -2,7 +2,6 @@ import django.core.validators from django.db import migrations, models -import report.models class Migration(migrations.Migration): @@ -16,7 +15,7 @@ class Migration(migrations.Migration): name='ReportSnippet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('snippet', models.FileField(help_text='Report snippet file', upload_to=report.models.rename_snippet, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])])), + ('snippet', models.FileField(help_text='Report snippet file', upload_to='report/snippets', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])])), ('description', models.CharField(help_text='Snippet file description', max_length=250)), ], ), diff --git a/src/backend/InvenTree/report/migrations/0007_auto_20210204_1617.py b/src/backend/InvenTree/report/migrations/0007_auto_20210204_1617.py index b110f63365fa..5cdcb3c18964 100644 --- a/src/backend/InvenTree/report/migrations/0007_auto_20210204_1617.py +++ b/src/backend/InvenTree/report/migrations/0007_auto_20210204_1617.py @@ -15,6 +15,6 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='testreport', name='template', - field=models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template'), + field=models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template'), ), ] diff --git a/src/backend/InvenTree/report/migrations/0011_auto_20210212_2024.py b/src/backend/InvenTree/report/migrations/0011_auto_20210212_2024.py index b1a93656cfe4..9545e0fae60a 100644 --- a/src/backend/InvenTree/report/migrations/0011_auto_20210212_2024.py +++ b/src/backend/InvenTree/report/migrations/0011_auto_20210212_2024.py @@ -2,7 +2,6 @@ import django.core.validators from django.db import migrations, models -import report.models class Migration(migrations.Migration): @@ -17,11 +16,11 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='Template name', max_length=100, verbose_name='Name')), - ('template', models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), + ('template', models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), ('description', models.CharField(help_text='Report template description', max_length=250, verbose_name='Description')), ('revision', models.PositiveIntegerField(default=1, editable=False, help_text='Report revision number (auto-increments)', verbose_name='Revision')), ('enabled', models.BooleanField(default=True, help_text='Report template is enabled', verbose_name='Enabled')), - ('filters', models.CharField(blank=True, help_text='Part query filters (comma-separated list of key=value pairs', max_length=250, validators=[report.models.validate_part_report_filters], verbose_name='Part Filters')), + ('filters', models.CharField(blank=True, help_text='Part query filters (comma-separated list of key=value pairs', max_length=250, verbose_name='Part Filters')), ], options={ 'abstract': False, @@ -30,6 +29,6 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='testreport', name='filters', - field=models.CharField(blank=True, help_text='StockItem query filters (comma-separated list of key=value pairs)', max_length=250, validators=[report.models.validate_stock_item_report_filters], verbose_name='Filters'), + field=models.CharField(blank=True, help_text='StockItem query filters (comma-separated list of key=value pairs)', max_length=250, verbose_name='Filters'), ), ] diff --git a/src/backend/InvenTree/report/migrations/0012_buildreport.py b/src/backend/InvenTree/report/migrations/0012_buildreport.py index b2d36034809e..900ef3d2fce9 100644 --- a/src/backend/InvenTree/report/migrations/0012_buildreport.py +++ b/src/backend/InvenTree/report/migrations/0012_buildreport.py @@ -2,7 +2,6 @@ import django.core.validators from django.db import migrations, models -import report.models class Migration(migrations.Migration): @@ -17,11 +16,11 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='Template name', max_length=100, verbose_name='Name')), - ('template', models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), + ('template', models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), ('description', models.CharField(help_text='Report template description', max_length=250, verbose_name='Description')), ('revision', models.PositiveIntegerField(default=1, editable=False, help_text='Report revision number (auto-increments)', verbose_name='Revision')), ('enabled', models.BooleanField(default=True, help_text='Report template is enabled', verbose_name='Enabled')), - ('filters', models.CharField(blank=True, help_text='Build query filters (comma-separated list of key=value pairs', max_length=250, validators=[report.models.validate_build_report_filters], verbose_name='Build Filters')), + ('filters', models.CharField(blank=True, help_text='Build query filters (comma-separated list of key=value pairs', max_length=250, verbose_name='Build Filters')), ], options={ 'abstract': False, diff --git a/src/backend/InvenTree/report/migrations/0014_purchaseorderreport_salesorderreport.py b/src/backend/InvenTree/report/migrations/0014_purchaseorderreport_salesorderreport.py index ab734b7b4839..58504048a372 100644 --- a/src/backend/InvenTree/report/migrations/0014_purchaseorderreport_salesorderreport.py +++ b/src/backend/InvenTree/report/migrations/0014_purchaseorderreport_salesorderreport.py @@ -2,7 +2,6 @@ import django.core.validators from django.db import migrations, models -import report.models class Migration(migrations.Migration): @@ -17,11 +16,11 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='Template name', max_length=100, verbose_name='Name')), - ('template', models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), + ('template', models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), ('description', models.CharField(help_text='Report template description', max_length=250, verbose_name='Description')), ('revision', models.PositiveIntegerField(default=1, editable=False, help_text='Report revision number (auto-increments)', verbose_name='Revision')), ('enabled', models.BooleanField(default=True, help_text='Report template is enabled', verbose_name='Enabled')), - ('filters', models.CharField(blank=True, help_text='Purchase order query filters', max_length=250, validators=[report.models.validate_purchase_order_filters], verbose_name='Filters')), + ('filters', models.CharField(blank=True, help_text='Purchase order query filters', max_length=250, verbose_name='Filters')), ], options={ 'abstract': False, @@ -32,11 +31,11 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='Template name', max_length=100, verbose_name='Name')), - ('template', models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), + ('template', models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), ('description', models.CharField(help_text='Report template description', max_length=250, verbose_name='Description')), ('revision', models.PositiveIntegerField(default=1, editable=False, help_text='Report revision number (auto-increments)', verbose_name='Revision')), ('enabled', models.BooleanField(default=True, help_text='Report template is enabled', verbose_name='Enabled')), - ('filters', models.CharField(blank=True, help_text='Sales order query filters', max_length=250, validators=[report.models.validate_sales_order_filters], verbose_name='Filters')), + ('filters', models.CharField(blank=True, help_text='Sales order query filters', max_length=250, verbose_name='Filters')), ], options={ 'abstract': False, diff --git a/src/backend/InvenTree/report/migrations/0015_auto_20210403_1837.py b/src/backend/InvenTree/report/migrations/0015_auto_20210403_1837.py index 0348db5b35d9..ceb0ff9baaff 100644 --- a/src/backend/InvenTree/report/migrations/0015_auto_20210403_1837.py +++ b/src/backend/InvenTree/report/migrations/0015_auto_20210403_1837.py @@ -15,7 +15,7 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='reportasset', name='asset', - field=models.FileField(help_text='Report asset file', upload_to=report.models.rename_asset, verbose_name='Asset'), + field=models.FileField(help_text='Report asset file', upload_to='report/assets', verbose_name='Asset'), ), migrations.AlterField( model_name='reportasset', @@ -30,6 +30,6 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='reportsnippet', name='snippet', - field=models.FileField(help_text='Report snippet file', upload_to=report.models.rename_snippet, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Snippet'), + field=models.FileField(help_text='Report snippet file', upload_to='report/snippets', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Snippet'), ), ] diff --git a/src/backend/InvenTree/report/migrations/0018_returnorderreport.py b/src/backend/InvenTree/report/migrations/0018_returnorderreport.py index 8bdbb6ebe8b7..04822b4a7876 100644 --- a/src/backend/InvenTree/report/migrations/0018_returnorderreport.py +++ b/src/backend/InvenTree/report/migrations/0018_returnorderreport.py @@ -2,7 +2,6 @@ import django.core.validators from django.db import migrations, models -import report.models class Migration(migrations.Migration): @@ -17,12 +16,12 @@ class Migration(migrations.Migration): fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='Template name', max_length=100, verbose_name='Name')), - ('template', models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), + ('template', models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), ('description', models.CharField(help_text='Report template description', max_length=250, verbose_name='Description')), ('revision', models.PositiveIntegerField(default=1, editable=False, help_text='Report revision number (auto-increments)', verbose_name='Revision')), ('filename_pattern', models.CharField(default='report.pdf', help_text='Pattern for generating report filenames', max_length=100, verbose_name='Filename Pattern')), ('enabled', models.BooleanField(default=True, help_text='Report template is enabled', verbose_name='Enabled')), - ('filters', models.CharField(blank=True, help_text='Return order query filters', max_length=250, validators=[report.models.validate_return_order_filters], verbose_name='Filters')), + ('filters', models.CharField(blank=True, help_text='Return order query filters', max_length=250, verbose_name='Filters')), ], options={ 'abstract': False, diff --git a/src/backend/InvenTree/report/migrations/0020_stocklocationreport.py b/src/backend/InvenTree/report/migrations/0020_stocklocationreport.py index b43c414e3bea..048d5455cf60 100644 --- a/src/backend/InvenTree/report/migrations/0020_stocklocationreport.py +++ b/src/backend/InvenTree/report/migrations/0020_stocklocationreport.py @@ -2,7 +2,6 @@ import django.core.validators from django.db import migrations, models -import report.models class Migration(migrations.Migration): @@ -18,12 +17,12 @@ class Migration(migrations.Migration): ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('metadata', models.JSONField(blank=True, help_text='JSON metadata field, for use by external plugins', null=True, verbose_name='Plugin Metadata')), ('name', models.CharField(help_text='Template name', max_length=100, verbose_name='Name')), - ('template', models.FileField(help_text='Report template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), + ('template', models.FileField(help_text='Report template file', upload_to='report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), ('description', models.CharField(help_text='Report template description', max_length=250, verbose_name='Description')), ('revision', models.PositiveIntegerField(default=1, editable=False, help_text='Report revision number (auto-increments)', verbose_name='Revision')), ('filename_pattern', models.CharField(default='report.pdf', help_text='Pattern for generating report filenames', max_length=100, verbose_name='Filename Pattern')), ('enabled', models.BooleanField(default=True, help_text='Report template is enabled', verbose_name='Enabled')), - ('filters', models.CharField(blank=True, help_text='stock location query filters (comma-separated list of key=value pairs)', max_length=250, validators=[report.models.validate_stock_location_report_filters], verbose_name='Filters')), + ('filters', models.CharField(blank=True, help_text='stock location query filters (comma-separated list of key=value pairs)', max_length=250, verbose_name='Filters')), ], options={ 'abstract': False, diff --git a/src/backend/InvenTree/report/migrations/0022_reporttemplate.py b/src/backend/InvenTree/report/migrations/0022_reporttemplate.py new file mode 100644 index 000000000000..9d3677c99913 --- /dev/null +++ b/src/backend/InvenTree/report/migrations/0022_reporttemplate.py @@ -0,0 +1,40 @@ +# Generated by Django 4.2.11 on 2024-04-21 03:11 + +import InvenTree.models +import django.core.validators +from django.db import migrations, models +import report.helpers +import report.models +import report.validators + + +class Migration(migrations.Migration): + + dependencies = [ + ('report', '0021_auto_20231009_0144'), + ] + + operations = [ + migrations.CreateModel( + name='ReportTemplate', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('metadata', models.JSONField(blank=True, help_text='JSON metadata field, for use by external plugins', null=True, verbose_name='Plugin Metadata')), + ('name', models.CharField(help_text='Template name', unique=True, max_length=100, verbose_name='Name')), + ('template', models.FileField(help_text='Template file', upload_to='report/report', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), + ('description', models.CharField(help_text='Template description', max_length=250, verbose_name='Description')), + ('revision', models.PositiveIntegerField(default=1, editable=False, help_text='Revision number (auto-increments)', verbose_name='Revision')), + ('page_size', models.CharField(default=report.helpers.report_page_size_default, help_text='Page size for PDF reports', max_length=20, verbose_name='Page Size')), + ('landscape', models.BooleanField(default=False, help_text='Render report in landscape orientation', verbose_name='Landscape')), + ('filename_pattern', models.CharField(default='output.pdf', help_text='Pattern for generating filenames', max_length=100, verbose_name='Filename Pattern')), + ('enabled', models.BooleanField(default=True, help_text='Template is enabled', verbose_name='Enabled')), + ('model_type', models.CharField(max_length=100, help_text='Target model type for template', validators=[report.validators.validate_report_model_type])), + ('filters', models.CharField(blank=True, help_text='Template query filters (comma-separated list of key=value pairs)', max_length=250, validators=[report.validators.validate_filters], verbose_name='Filters')), + ], + options={ + 'abstract': False, + 'unique_together': [('name', 'model_type')] + }, + bases=(InvenTree.models.PluginValidationMixin, models.Model), + ), + ] diff --git a/src/backend/InvenTree/report/migrations/0023_auto_20240421_0455.py b/src/backend/InvenTree/report/migrations/0023_auto_20240421_0455.py new file mode 100644 index 000000000000..f33ca0f98a9f --- /dev/null +++ b/src/backend/InvenTree/report/migrations/0023_auto_20240421_0455.py @@ -0,0 +1,102 @@ +# Generated by Django 4.2.11 on 2024-04-21 04:55 + +import os + +from django.db import migrations +from django.core.files.base import ContentFile + + +def report_model_map(): + """Return a map of model_type: report_type keys.""" + + return { + 'stockitem': 'testreport', + 'stocklocation': 'stocklocationreport', + 'build': 'buildreport', + 'part': 'billofmaterialsreport', + 'purchaseorder': 'purchaseorderreport', + 'salesorder': 'salesorderreport', + 'returnorder': 'returnorderreport' + } + + +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_map().items(): + + model = apps.get_model('report', report_model) + + for template in model.objects.all(): + # Construct a new ReportTemplate instance + + filename = template.template.path + + if '/report/inventree/' in filename: + # Do not migrate internal report templates + continue + + filename = os.path.basename(filename) + filedata = template.template.open('r').read() + + name = template.name + offset = 1 + + # Prevent duplicate names during migration + while ReportTemplate.objects.filter(name=name, model_type=model_type).exists(): + name = template.name + f"_{offset}" + offset += 1 + + ReportTemplate.objects.create( + name=name, + template=ContentFile(filedata, filename), + model_type=model_type, + description=template.description, + revision=template.revision, + filters=template.filters, + filename_pattern=template.filename_pattern, + enabled=template.enabled, + page_size=template.page_size, + landscape=template.landscape, + ) + + count += 1 + + if count > 0: + print(f"Migrated {count} report templates to new ReportTemplate model.") + + +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.template.delete() + item.delete() + + print(f"Deleted {n} ReportTemplate objects and templates") + + +class Migration(migrations.Migration): + + dependencies = [ + ('report', '0022_reporttemplate'), + ] + + operations = [ + migrations.RunPython(forward, reverse_code=reverse) + ] diff --git a/src/backend/InvenTree/report/migrations/0024_delete_billofmaterialsreport_delete_buildreport_and_more.py b/src/backend/InvenTree/report/migrations/0024_delete_billofmaterialsreport_delete_buildreport_and_more.py new file mode 100644 index 000000000000..429a8c2a788b --- /dev/null +++ b/src/backend/InvenTree/report/migrations/0024_delete_billofmaterialsreport_delete_buildreport_and_more.py @@ -0,0 +1,34 @@ +# Generated by Django 4.2.11 on 2024-04-21 14:03 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('report', '0023_auto_20240421_0455'), + ] + + operations = [ + migrations.DeleteModel( + name='BillOfMaterialsReport', + ), + migrations.DeleteModel( + name='BuildReport', + ), + migrations.DeleteModel( + name='PurchaseOrderReport', + ), + migrations.DeleteModel( + name='ReturnOrderReport', + ), + migrations.DeleteModel( + name='SalesOrderReport', + ), + migrations.DeleteModel( + name='StockLocationReport', + ), + migrations.DeleteModel( + name='TestReport', + ), + ] diff --git a/src/backend/InvenTree/report/migrations/0025_labeltemplate.py b/src/backend/InvenTree/report/migrations/0025_labeltemplate.py new file mode 100644 index 000000000000..eaeb54daf6f1 --- /dev/null +++ b/src/backend/InvenTree/report/migrations/0025_labeltemplate.py @@ -0,0 +1,39 @@ +# Generated by Django 4.2.11 on 2024-04-22 12:48 + +import InvenTree.models +import django.core.validators +from django.db import migrations, models +import report.models +import report.validators + + +class Migration(migrations.Migration): + + dependencies = [ + ('report', '0024_delete_billofmaterialsreport_delete_buildreport_and_more'), + ] + + operations = [ + migrations.CreateModel( + name='LabelTemplate', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('metadata', models.JSONField(blank=True, help_text='JSON metadata field, for use by external plugins', null=True, verbose_name='Plugin Metadata')), + ('name', models.CharField(help_text='Template name', max_length=100, unique=True, verbose_name='Name')), + ('description', models.CharField(help_text='Template description', max_length=250, verbose_name='Description')), + ('template', models.FileField(help_text='Template file', upload_to='report/label', validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template')), + ('revision', models.PositiveIntegerField(default=1, editable=False, help_text='Revision number (auto-increments)', verbose_name='Revision')), + ('filename_pattern', models.CharField(default='output.pdf', help_text='Pattern for generating filenames', max_length=100, verbose_name='Filename Pattern')), + ('enabled', models.BooleanField(default=True, help_text='Template is enabled', verbose_name='Enabled')), + ('model_type', models.CharField(max_length=100, validators=[report.validators.validate_report_model_type])), + ('filters', models.CharField(blank=True, help_text='Template query filters (comma-separated list of key=value pairs)', max_length=250, validators=[report.validators.validate_filters], verbose_name='Filters')), + ('width', models.FloatField(default=50, help_text='Label width, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Width [mm]')), + ('height', models.FloatField(default=20, help_text='Label height, specified in mm', validators=[django.core.validators.MinValueValidator(2)], verbose_name='Height [mm]')), + ], + options={ + 'abstract': False, + 'unique_together': {('name', 'model_type')}, + }, + bases=(InvenTree.models.PluginValidationMixin, models.Model), + ), + ] diff --git a/src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py b/src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py new file mode 100644 index 000000000000..036fc62faa1b --- /dev/null +++ b/src/backend/InvenTree/report/migrations/0026_auto_20240422_1301.py @@ -0,0 +1,136 @@ +# Generated by Django 4.2.11 on 2024-04-22 13:01 + +import os + +from django.db import connection, migrations +from django.core.files.base import ContentFile +from django.core.files.storage import default_storage + + +def label_model_map(): + """Map legacy label template models to model_type values.""" + + return { + "stockitemlabel": "stockitem", + "stocklocationlabel": "stocklocation", + "partlabel": "part", + "buildlinelabel": "buildline", + } + + +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 + + Note: We use raw SQL queries here, as the original 'label' app has been removed entirely. + """ + count = 0 + + fields = [ + 'name', 'description', 'label', 'enabled', 'height', 'width', 'filename_pattern', 'filters' + ] + + fieldnames = ', '.join(fields) + + query = f"SELECT {fieldnames} FROM {table_name};" + + with connection.cursor() as cursor: + try: + cursor.execute(query) + except Exception: + # Table likely does not exist + print(f"Legacy label table {table_name} not found - skipping migration") + return 0 + + rows = cursor.fetchall() + + for row in rows: + data = { + fields[idx]: row[idx] for idx in range(len(fields)) + } + + # Skip any "builtin" labels + if 'label/inventree/' in data['label']: + continue + + print(f"Creating new LabelTemplate for {model_name} - {data['name']}") + + if template_model.objects.filter(name=data['name'], model_type=model_name).exists(): + print(f"LabelTemplate {data['name']} already exists for {model_name} - skipping") + continue + + + if not default_storage.exists(data['label']): + print(f"Label template file {data['label']} does not exist - skipping") + continue + + # Create a new template file object + filedata = default_storage.open(data['label']).read() + filename = os.path.basename(data['label']) + + # Remove the 'label' key from the data dictionary + data.pop('label') + + data['template'] = ContentFile(filedata, filename) + data['model_type'] = model_name + + template_model.objects.create(**data) + + count += 1 + + return count + + +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_name = f'label_{template_class}' + + count += convert_legacy_labels(table_name, model_type, LabelTemplate) or 0 + + if count > 0: + print(f"Migrated {count} report templates to new LabelTemplate model.") + +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.template.delete() + item.delete() + + print(f"Deleted {n} LabelTemplate objects and templates") + +class Migration(migrations.Migration): + + atomic = False + + dependencies = [ + ('report', '0025_labeltemplate'), + ] + + operations = [ + migrations.RunPython(forward, reverse_code=reverse) + ] + diff --git a/src/backend/InvenTree/report/migrations/0027_alter_labeltemplate_model_type_and_more.py b/src/backend/InvenTree/report/migrations/0027_alter_labeltemplate_model_type_and_more.py new file mode 100644 index 000000000000..4fa5b23aff12 --- /dev/null +++ b/src/backend/InvenTree/report/migrations/0027_alter_labeltemplate_model_type_and_more.py @@ -0,0 +1,77 @@ +# Generated by Django 4.2.11 on 2024-04-30 09:50 + +from django.conf import settings +import django.core.validators +from django.db import migrations, models +import django.db.models.deletion +import report.models +import report.validators + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('report', '0026_auto_20240422_1301'), + ] + + operations = [ + migrations.AlterField( + model_name='labeltemplate', + name='model_type', + field=models.CharField(help_text='Target model type for template', max_length=100, validators=[report.validators.validate_report_model_type]), + ), + migrations.AlterField( + model_name='labeltemplate', + name='template', + field=models.FileField(help_text='Template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template'), + ), + migrations.AlterField( + model_name='reportasset', + name='asset', + field=models.FileField(help_text='Report asset file', upload_to=report.models.rename_template, verbose_name='Asset'), + ), + migrations.AlterField( + model_name='reportsnippet', + name='snippet', + field=models.FileField(help_text='Report snippet file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Snippet'), + ), + migrations.AlterField( + model_name='reporttemplate', + name='template', + field=models.FileField(help_text='Template file', upload_to=report.models.rename_template, validators=[django.core.validators.FileExtensionValidator(allowed_extensions=['html', 'htm'])], verbose_name='Template'), + ), + migrations.CreateModel( + name='ReportOutput', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created', models.DateField(auto_now_add=True)), + ('items', models.PositiveIntegerField(default=0, help_text='Number of items to process', verbose_name='Items')), + ('complete', models.BooleanField(default=False, help_text='Report generation is complete', verbose_name='Complete')), + ('progress', models.PositiveIntegerField(default=0, help_text='Report generation progress', verbose_name='Progress')), + ('output', models.FileField(blank=True, help_text='Generated output file', null=True, upload_to='report/output', verbose_name='Output File')), + ('template', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='report.reporttemplate', verbose_name='Report Template')), + ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='LabelOutput', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created', models.DateField(auto_now_add=True)), + ('items', models.PositiveIntegerField(default=0, help_text='Number of items to process', verbose_name='Items')), + ('complete', models.BooleanField(default=False, help_text='Report generation is complete', verbose_name='Complete')), + ('progress', models.PositiveIntegerField(default=0, help_text='Report generation progress', verbose_name='Progress')), + ('output', models.FileField(blank=True, help_text='Generated output file', null=True, upload_to='label/output', verbose_name='Output File')), + ('plugin', models.CharField(blank=True, help_text='Label output plugin', max_length=100, verbose_name='Plugin')), + ('template', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='report.labeltemplate', verbose_name='Label Template')), + ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'abstract': False, + }, + ), + ] diff --git a/src/backend/InvenTree/report/mixins.py b/src/backend/InvenTree/report/mixins.py new file mode 100644 index 000000000000..12142dc16209 --- /dev/null +++ b/src/backend/InvenTree/report/mixins.py @@ -0,0 +1,23 @@ +"""Report mixin classes.""" + +from django.db import models + + +class InvenTreeReportMixin(models.Model): + """A mixin class for adding report generation functionality to a model class. + + In addition to exposing the model to the report generation interface, + this mixin provides a hook for providing extra context information to the reports. + """ + + class Meta: + """Metaclass options for this mixin.""" + + abstract = True + + def report_context(self) -> dict: + """Generate a dict of context data to provide to the reporting framework. + + The default implementation returns an empty dict object. + """ + return {} diff --git a/src/backend/InvenTree/report/models.py b/src/backend/InvenTree/report/models.py index 6575b494cb10..692ed7553049 100644 --- a/src/backend/InvenTree/report/models.py +++ b/src/backend/InvenTree/report/models.py @@ -1,30 +1,26 @@ """Report template model definitions.""" -import datetime import logging import os import sys from django.conf import settings -from django.core.cache import cache +from django.contrib.auth.models import User from django.core.exceptions import ValidationError -from django.core.validators import FileExtensionValidator +from django.core.files.storage import default_storage +from django.core.validators import FileExtensionValidator, MinValueValidator from django.db import models from django.template import Context, Template from django.template.loader import render_to_string from django.urls import reverse from django.utils.translation import gettext_lazy as _ -import build.models import common.models import InvenTree.exceptions import InvenTree.helpers import InvenTree.models -import order.models -import part.models import report.helpers -import stock.models -from InvenTree.helpers import validateFilterString +import report.validators from InvenTree.helpers_model import get_base_url from InvenTree.models import MetadataMixin from plugin.registry import registry @@ -33,6 +29,7 @@ from django_weasyprint import WeasyTemplateResponseMixin except OSError as err: # pragma: no cover print(f'OSError: {err}') + print("Unable to import 'django_weasyprint' module.") print('You may require some further system packages to be installed.') sys.exit(1) @@ -40,78 +37,104 @@ logger = logging.getLogger('inventree') +class WeasyprintReport(WeasyTemplateResponseMixin): + """Class for rendering a HTML template to a PDF.""" + + def __init__(self, request, template, **kwargs): + """Initialize the report mixin with some standard attributes.""" + self.request = request + self.template_name = template + self.pdf_filename = kwargs.get('filename', 'output.pdf') + + def rename_template(instance, filename): - """Helper function for 'renaming' uploaded report files. + """Function to rename a report template once uploaded. - Pass responsibility back to the calling class, - to ensure that files are uploaded to the correct directory. + - Retains the original uploaded filename + - Checks for duplicate filenames across instance class """ - return instance.rename_file(filename) + path = instance.get_upload_path(filename) + # Throw error if any other model instances reference this path + instance.check_existing_file(path, raise_error=True) -def validate_stock_item_report_filters(filters): - """Validate filter string against StockItem model.""" - return validateFilterString(filters, model=stock.models.StockItem) + # Delete file with this name if it already exists + if default_storage.exists(path): + logger.info(f'Deleting existing template file: {path}') + default_storage.delete(path) + return path -def validate_part_report_filters(filters): - """Validate filter string against Part model.""" - return validateFilterString(filters, model=part.models.Part) +class TemplateUploadMixin: + """Mixin class for providing template pathing functions. -def validate_build_report_filters(filters): - """Validate filter string against Build model.""" - return validateFilterString(filters, model=build.models.Build) + - Provides generic method for determining the upload path for a template + - Provides generic method for checking for duplicate filenames + Classes which inherit this mixin can guarantee that uploaded templates are unique, + and that the same filename will be retained when uploaded. + """ -def validate_purchase_order_filters(filters): - """Validate filter string against PurchaseOrder model.""" - return validateFilterString(filters, model=order.models.PurchaseOrder) + # Directory in which to store uploaded templates + SUBDIR = '' + # Name of the template field + TEMPLATE_FIELD = 'template' -def validate_sales_order_filters(filters): - """Validate filter string against SalesOrder model.""" - return validateFilterString(filters, model=order.models.SalesOrder) + def __str__(self) -> str: + """String representation of a TemplateUploadMixin instance.""" + return str(os.path.basename(self.template_name)) + @property + 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) -def validate_return_order_filters(filters): - """Validate filter string against ReturnOrder model.""" - return validateFilterString(filters, model=order.models.ReturnOrder) + template = settings.MEDIA_ROOT.joinpath(template) + return str(template) -def validate_stock_location_report_filters(filters): - """Validate filter string against StockLocation model.""" - return validateFilterString(filters, model=stock.models.StockLocation) + @property + def extension(self): + """Return the filename extension of the associated template file.""" + return os.path.splitext(self.template.name)[1].lower() + 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) -class WeasyprintReportMixin(WeasyTemplateResponseMixin): - """Class for rendering a HTML template to a PDF.""" + 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)} - pdf_filename = 'report.pdf' - pdf_attachment = True + exists = self.__class__.objects.filter(**filters).exclude(pk=self.pk).exists() - def __init__(self, request, template, **kwargs): - """Initialize the report mixin with some standard attributes.""" - self.request = request - self.template_name = template - self.pdf_filename = kwargs.get('filename', 'report.pdf') + if exists and raise_error: + raise ValidationError({ + self.TEMPLATE_FIELD: _('Template file with this name already exists') + }) + return exists -class ReportBase(InvenTree.models.InvenTreeModel): - """Base class for uploading html templates.""" + 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) - class Meta: - """Metaclass options. Abstract ensures no database table is created.""" - abstract = True +class ReportTemplateBase(MetadataMixin, InvenTree.models.InvenTreeModel): + """Base class for reports, labels.""" - def __init__(self, *args, **kwargs): - """Initialize the particular report instance.""" - super().__init__(*args, **kwargs) + class Meta: + """Metaclass options.""" - self._meta.get_field( - 'page_size' - ).choices = report.helpers.report_page_size_options() + abstract = True + unique_together = ('name', 'model_type') def save(self, *args, **kwargs): """Perform additional actions when the report is saved.""" @@ -120,531 +143,364 @@ def save(self, *args, **kwargs): super().save() - def __str__(self): - """Format a string representation of a report instance.""" - return f'{self.name} - {self.description}' - - @classmethod - def getSubdir(cls): - """Return the subdirectory where template files for this report model will be located.""" - return '' - - def rename_file(self, filename): - """Function for renaming uploaded file.""" - filename = os.path.basename(filename) - - path = os.path.join('report', 'report_template', self.getSubdir(), filename) - - fullpath = settings.MEDIA_ROOT.joinpath(path).resolve() - - # If the report file is the *same* filename as the one being uploaded, - # remove the original one from the media directory - if str(filename) == str(self.template): - if fullpath.exists(): - logger.info("Deleting existing report template: '%s'", filename) - os.remove(fullpath) - - # Ensure that the cache is cleared for this template! - cache.delete(fullpath) - - return path - - @property - def extension(self): - """Return the filename extension of the associated template file.""" - return os.path.splitext(self.template.name)[1].lower() - - @property - def template_name(self): - """Returns the file system path to the template file. - - Required for passing the file to an external process - """ - template = self.template.name - - # TODO @matmair change to using new file objects - template = template.replace('/', os.path.sep) - template = template.replace('\\', os.path.sep) - - template = settings.MEDIA_ROOT.joinpath(template) - - return template - name = models.CharField( blank=False, max_length=100, verbose_name=_('Name'), help_text=_('Template name'), - ) - - template = models.FileField( - upload_to=rename_template, - verbose_name=_('Template'), - help_text=_('Report template file'), - validators=[FileExtensionValidator(allowed_extensions=['html', 'htm'])], + unique=True, ) description = models.CharField( max_length=250, verbose_name=_('Description'), - help_text=_('Report template description'), + help_text=_('Template description'), ) revision = models.PositiveIntegerField( default=1, verbose_name=_('Revision'), - help_text=_('Report revision number (auto-increments)'), + help_text=_('Revision number (auto-increments)'), editable=False, ) - page_size = models.CharField( - max_length=20, - default=report.helpers.report_page_size_default, - verbose_name=_('Page Size'), - help_text=_('Page size for PDF reports'), - ) - - landscape = models.BooleanField( - default=False, - verbose_name=_('Landscape'), - help_text=_('Render report in landscape orientation'), - ) - - -class ReportTemplateBase(MetadataMixin, ReportBase): - """Reporting template model. - - Able to be passed context data - """ - - class Meta: - """Metaclass options. Abstract ensures no database table is created.""" - - abstract = True - - # Pass a single top-level object to the report template - object_to_print = None - - def get_context_data(self, request): - """Supply context data to the template for rendering.""" - return {} - - def get_report_size(self): - """Return the printable page size for this report.""" - try: - page_size_default = common.models.InvenTreeSetting.get_setting( - 'REPORT_DEFAULT_PAGE_SIZE', 'A4' - ) - except Exception: - page_size_default = 'A4' - - page_size = self.page_size or page_size_default - - if self.landscape: - page_size = page_size + ' landscape' - - return page_size - - def context(self, request): - """All context to be passed to the renderer.""" - # Generate custom context data based on the particular report subclass - context = self.get_context_data(request) - - context['base_url'] = get_base_url(request=request) - context['date'] = InvenTree.helpers.current_date() - context['datetime'] = InvenTree.helpers.current_time() - context['page_size'] = self.get_report_size() - context['report_template'] = self - context['report_description'] = self.description - context['report_name'] = self.name - context['report_revision'] = self.revision - context['request'] = request - context['user'] = request.user - - # Pass the context through to any active reporting plugins - plugins = registry.with_mixin('report') - - for plugin in plugins: - # Let each plugin add its own context data - try: - plugin.add_report_context(self, self.object_to_print, request, context) - except Exception: - InvenTree.exceptions.log_error( - f'plugins.{plugin.slug}.add_report_context' - ) - - return context - - def generate_filename(self, request, **kwargs): + def generate_filename(self, context, **kwargs): """Generate a filename for this report.""" template_string = Template(self.filename_pattern) - ctx = self.context(request) - - context = Context(ctx) + return template_string.render(Context(context)) - return template_string.render(context) - - def render_as_string(self, request, **kwargs): + def render_as_string(self, instance, request=None, **kwargs): """Render the report to a HTML string. Useful for debug mode (viewing generated code) """ - return render_to_string(self.template_name, self.context(request), request) + context = self.get_context(instance, request, **kwargs) + + return render_to_string(self.template_name, context, request) - def render(self, request, **kwargs): + def render(self, instance, request=None, **kwargs): """Render the template to a PDF file. Uses django-weasyprint plugin to render HTML template against Weasyprint """ - # TODO: Support custom filename generation! - # filename = kwargs.get('filename', 'report.pdf') + context = self.get_context(instance, request) # Render HTML template to PDF - wp = WeasyprintReportMixin( + wp = WeasyprintReport( request, self.template_name, base_url=request.build_absolute_uri('/'), presentational_hints=True, - filename=self.generate_filename(request), + filename=self.generate_filename(context), **kwargs, ) - return wp.render_to_response(self.context(request), **kwargs) + return wp.render_to_response(context, **kwargs) filename_pattern = models.CharField( - default='report.pdf', + default='output.pdf', verbose_name=_('Filename Pattern'), - help_text=_('Pattern for generating report filenames'), + help_text=_('Pattern for generating filenames'), max_length=100, ) enabled = models.BooleanField( - default=True, - verbose_name=_('Enabled'), - help_text=_('Report template is enabled'), + default=True, verbose_name=_('Enabled'), help_text=_('Template is enabled') ) + model_type = models.CharField( + max_length=100, + validators=[report.validators.validate_report_model_type], + help_text=_('Target model type for template'), + ) -class TestReport(ReportTemplateBase): - """Render a TestReport against a StockItem object.""" + def clean(self): + """Clean model instance, and ensure validity.""" + super().clean() - @staticmethod - def get_api_url(): - """Return the API URL associated with the TestReport model.""" - return reverse('api-stockitem-testreport-list') + model = self.get_model() + filters = self.filters + + if model and filters: + report.validators.validate_filters(filters, model=model) - @classmethod - def getSubdir(cls): - """Return the subdirectory where TestReport templates are located.""" - return 'test' + def get_model(self): + """Return the database model class associated with this report template.""" + return report.helpers.report_model_from_name(self.model_type) filters = models.CharField( blank=True, max_length=250, verbose_name=_('Filters'), - help_text=_( - 'StockItem query filters (comma-separated list of key=value pairs)' - ), - validators=[validate_stock_item_report_filters], + help_text=_('Template query filters (comma-separated list of key=value pairs)'), + validators=[report.validators.validate_filters], ) - include_installed = models.BooleanField( - default=False, - verbose_name=_('Include Installed Tests'), - help_text=_( - 'Include test results for stock items installed inside assembled item' - ), - ) + def get_filters(self): + """Return a filter dict which can be applied to the target model.""" + return report.validators.validate_filters(self.filters, model=self.get_model()) - def get_test_keys(self, stock_item): - """Construct a flattened list of test 'keys' for this StockItem. + def base_context(self, request=None): + """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(), + 'request': request, + 'template': self, + 'template_description': self.description, + 'template_name': self.name, + 'template_revision': self.revision, + 'user': request.user if request else None, + } + + def get_context(self, instance, request=None, **kwargs): + """Supply context data to the generic template for rendering. - The list is constructed as follows: - - First, any 'required' tests - - Second, any 'non required' tests - - Finally, any test results which do not match a test + Arguments: + instance: The model instance we are printing against + request: The request object (optional) """ - keys = [] + # Provide base context information to all templates + base_context = self.base_context(request=request) - for test in stock_item.part.getTestTemplates(required=True): - if test.key not in keys: - keys.append(test.key) + # Add in an context information provided by the model instance itself + context = {**base_context, **instance.report_context()} - for test in stock_item.part.getTestTemplates(required=False): - if test.key not in keys: - keys.append(test.key) + return context - for result in stock_item.testResultList( - include_installed=self.include_installed - ): - if result.key not in keys: - keys.append(result.key) - return list(keys) +class ReportTemplate(TemplateUploadMixin, ReportTemplateBase): + """Class representing the ReportTemplate database model.""" - def get_context_data(self, request): - """Return custom context data for the TestReport template.""" - stock_item = self.object_to_print + SUBDIR = 'report' + TEMPLATE_FIELD = 'template' - return { - 'stock_item': stock_item, - 'serial': stock_item.serial, - 'part': stock_item.part, - 'parameters': stock_item.part.parameters_map(), - 'test_keys': self.get_test_keys(stock_item), - 'test_template_list': stock_item.part.getTestTemplates(), - 'test_template_map': stock_item.part.getTestTemplateMap(), - 'results': stock_item.testResultMap( - include_installed=self.include_installed - ), - 'result_list': stock_item.testResultList( - include_installed=self.include_installed - ), - 'installed_items': stock_item.get_installed_items(cascade=True), - } + @staticmethod + def get_api_url(): + """Return the API endpoint for the ReportTemplate model.""" + return reverse('api-report-template-list') + def __init__(self, *args, **kwargs): + """Initialize the particular report instance.""" + super().__init__(*args, **kwargs) -class BuildReport(ReportTemplateBase): - """Build order / work order report.""" + self._meta.get_field( + 'page_size' + ).choices = report.helpers.report_page_size_options() - @staticmethod - def get_api_url(): - """Return the API URL associated with the BuildReport model.""" - return reverse('api-build-report-list') + template = models.FileField( + upload_to=rename_template, + verbose_name=_('Template'), + help_text=_('Template file'), + validators=[FileExtensionValidator(allowed_extensions=['html', 'htm'])], + ) - @classmethod - def getSubdir(cls): - """Return the subdirectory where BuildReport templates are located.""" - return 'build' + page_size = models.CharField( + max_length=20, + default=report.helpers.report_page_size_default, + verbose_name=_('Page Size'), + help_text=_('Page size for PDF reports'), + ) - filters = models.CharField( - blank=True, - max_length=250, - verbose_name=_('Build Filters'), - help_text=_('Build query filters (comma-separated list of key=value pairs'), - validators=[validate_build_report_filters], + landscape = models.BooleanField( + default=False, + verbose_name=_('Landscape'), + help_text=_('Render report in landscape orientation'), ) - def get_context_data(self, request): - """Custom context data for the build report.""" - my_build = self.object_to_print + def get_report_size(self): + """Return the printable page size for this report.""" + try: + page_size_default = common.models.InvenTreeSetting.get_setting( + 'REPORT_DEFAULT_PAGE_SIZE', 'A4' + ) + except Exception: + page_size_default = 'A4' - if not isinstance(my_build, build.models.Build): - raise TypeError('Provided model is not a Build object') + page_size = self.page_size or page_size_default - return { - 'build': my_build, - 'part': my_build.part, - 'build_outputs': my_build.build_outputs.all(), - 'line_items': my_build.build_lines.all(), - 'bom_items': my_build.part.get_bom_items(), - 'reference': my_build.reference, - 'quantity': my_build.quantity, - 'title': str(my_build), + if self.landscape: + page_size = page_size + ' landscape' + + return page_size + + def get_context(self, instance, request=None, **kwargs): + """Supply context data to the report template for rendering.""" + context = { + **super().get_context(instance, request), + 'page_size': self.get_report_size(), + 'landscape': self.landscape, } + # Pass the context through to the plugin registry for any additional information + for plugin in registry.with_mixin('report'): + try: + plugin.add_report_context(self, instance, request, context) + except Exception: + InvenTree.exceptions.log_error( + f'plugins.{plugin.slug}.add_report_context' + ) + + return context + + +class LabelTemplate(TemplateUploadMixin, ReportTemplateBase): + """Class representing the LabelTemplate database model.""" -class BillOfMaterialsReport(ReportTemplateBase): - """Render a Bill of Materials against a Part object.""" + SUBDIR = 'label' + TEMPLATE_FIELD = 'template' @staticmethod def get_api_url(): - """Return the API URL associated with the BillOfMaterialsReport model.""" - return reverse('api-bom-report-list') + """Return the API endpoint for the LabelTemplate model.""" + return reverse('api-label-template-list') - @classmethod - def getSubdir(cls): - """Return the directory where BillOfMaterialsReport templates are located.""" - return 'bom' + template = models.FileField( + upload_to=rename_template, + verbose_name=_('Template'), + help_text=_('Template file'), + validators=[FileExtensionValidator(allowed_extensions=['html', 'htm'])], + ) - filters = models.CharField( - blank=True, - max_length=250, - verbose_name=_('Part Filters'), - help_text=_('Part query filters (comma-separated list of key=value pairs'), - validators=[validate_part_report_filters], + width = models.FloatField( + default=50, + verbose_name=_('Width [mm]'), + help_text=_('Label width, specified in mm'), + validators=[MinValueValidator(2)], ) - def get_context_data(self, request): - """Return custom context data for the BillOfMaterialsReport template.""" - part = self.object_to_print + height = models.FloatField( + default=20, + verbose_name=_('Height [mm]'), + help_text=_('Label height, specified in mm'), + validators=[MinValueValidator(2)], + ) - return { - 'part': part, - 'category': part.category, - 'bom_items': part.get_bom_items(), + 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', 0) + + return f""" + @page {{ + size: {width}mm {height}mm; + margin: {margin}mm; + }} + """ + + def get_context(self, instance, request=None, **kwargs): + """Supply context data to the label template for rendering.""" + context = { + **super().get_context(instance, request, **kwargs), + 'width': self.width, + 'height': self.height, } + if kwargs.pop('insert_page_style', True): + context['page_style'] = self.generate_page_style() -class PurchaseOrderReport(ReportTemplateBase): - """Render a report against a PurchaseOrder object.""" + # Pass the context through to any registered plugins + plugins = registry.with_mixin('report') - @staticmethod - def get_api_url(): - """Return the API URL associated with the PurchaseOrderReport model.""" - return reverse('api-po-report-list') + for plugin in plugins: + # Let each plugin add its own context data + plugin.add_label_context(self, self.object_to_print, request, context) - @classmethod - def getSubdir(cls): - """Return the directory where PurchaseOrderReport templates are stored.""" - return 'purchaseorder' + return context - filters = models.CharField( - blank=True, - max_length=250, - verbose_name=_('Filters'), - help_text=_('Purchase order query filters'), - validators=[validate_purchase_order_filters], - ) - def get_context_data(self, request): - """Return custom context data for the PurchaseOrderReport template.""" - order = self.object_to_print +class TemplateOutput(models.Model): + """Base class representing a generated file from a template. - return { - 'description': order.description, - 'lines': order.lines, - 'extra_lines': order.extra_lines, - 'order': order, - 'reference': order.reference, - 'supplier': order.supplier, - 'title': str(order), - } + As reports (or labels) may take a long time to render, + this process is offloaded to the background worker process. + The result is either a file made available for download, + or a message indicating that the output is handled externally. + """ -class SalesOrderReport(ReportTemplateBase): - """Render a report against a SalesOrder object.""" + class Meta: + """Metaclass options.""" - @staticmethod - def get_api_url(): - """Return the API URL associated with the SalesOrderReport model.""" - return reverse('api-so-report-list') + abstract = True - @classmethod - def getSubdir(cls): - """Return the subdirectory where SalesOrderReport templates are located.""" - return 'salesorder' + created = models.DateField(auto_now_add=True, editable=False) - filters = models.CharField( - blank=True, - max_length=250, - verbose_name=_('Filters'), - help_text=_('Sales order query filters'), - validators=[validate_sales_order_filters], + user = models.ForeignKey( + User, on_delete=models.SET_NULL, blank=True, null=True, related_name='+' ) - def get_context_data(self, request): - """Return custom context data for a SalesOrderReport template.""" - order = self.object_to_print + items = models.PositiveIntegerField( + default=0, verbose_name=_('Items'), help_text=_('Number of items to process') + ) - return { - 'customer': order.customer, - 'description': order.description, - 'lines': order.lines, - 'extra_lines': order.extra_lines, - 'order': order, - 'reference': order.reference, - 'title': str(order), - } + complete = models.BooleanField( + default=False, + verbose_name=_('Complete'), + help_text=_('Report generation is complete'), + ) + progress = models.PositiveIntegerField( + default=0, verbose_name=_('Progress'), help_text=_('Report generation progress') + ) -class ReturnOrderReport(ReportTemplateBase): - """Render a custom report against a ReturnOrder object.""" - @staticmethod - def get_api_url(): - """Return the API URL associated with the ReturnOrderReport model.""" - return reverse('api-return-order-report-list') +class ReportOutput(TemplateOutput): + """Class representing a generated report output file.""" - @classmethod - def getSubdir(cls): - """Return the directory where the ReturnOrderReport templates are stored.""" - return 'returnorder' + template = models.ForeignKey( + ReportTemplate, on_delete=models.CASCADE, verbose_name=_('Report Template') + ) - filters = models.CharField( + output = models.FileField( + upload_to='report/output', blank=True, - max_length=250, - verbose_name=_('Filters'), - help_text=_('Return order query filters'), - validators=[validate_return_order_filters], + null=True, + verbose_name=_('Output File'), + help_text=_('Generated output file'), ) - def get_context_data(self, request): - """Return custom context data for the ReturnOrderReport template.""" - order = self.object_to_print - - return { - 'order': order, - 'description': order.description, - 'reference': order.reference, - 'customer': order.customer, - 'lines': order.lines, - 'extra_lines': order.extra_lines, - 'title': str(order), - } +class LabelOutput(TemplateOutput): + """Class representing a generated label output file.""" -def rename_snippet(instance, filename): - """Function to rename a report snippet once uploaded.""" - path = ReportSnippet.snippet_path(filename) - fullpath = settings.MEDIA_ROOT.joinpath(path).resolve() - - # If the snippet file is the *same* filename as the one being uploaded, - # delete the original one from the media directory - if str(filename) == str(instance.snippet): - if fullpath.exists(): - logger.info("Deleting existing snippet file: '%s'", filename) - os.remove(fullpath) + plugin = models.CharField( + max_length=100, + blank=True, + verbose_name=_('Plugin'), + help_text=_('Label output plugin'), + ) - # Ensure that the cache is deleted for this snippet - cache.delete(fullpath) + template = models.ForeignKey( + LabelTemplate, on_delete=models.CASCADE, verbose_name=_('Label Template') + ) - return path + output = models.FileField( + upload_to='label/output', + blank=True, + null=True, + verbose_name=_('Output File'), + help_text=_('Generated output file'), + ) -class ReportSnippet(models.Model): +class ReportSnippet(TemplateUploadMixin, models.Model): """Report template 'snippet' which can be used to make templates that can then be included in other reports. Useful for 'common' template actions, sub-templates, etc """ - def __str__(self) -> str: - """String representation of a ReportSnippet instance.""" - return f'snippets/{self.filename}' - - @property - def filename(self): - """Return the filename of the asset.""" - path = self.snippet.name - if path: - return os.path.basename(path) - else: - return '-' - - @staticmethod - def snippet_path(filename): - """Return the fully-qualified snippet path for the given filename.""" - return os.path.join('report', 'snippets', os.path.basename(str(filename))) - - def validate_unique(self, exclude=None): - """Validate that this report asset is unique.""" - proposed_path = self.snippet_path(self.snippet) - - if ( - ReportSnippet.objects.filter(snippet=proposed_path) - .exclude(pk=self.pk) - .count() - > 0 - ): - raise ValidationError({ - 'snippet': _('Snippet file with this name already exists') - }) - - return super().validate_unique(exclude) + SUBDIR = 'snippets' + TEMPLATE_FIELD = 'snippet' snippet = models.FileField( - upload_to=rename_snippet, + upload_to=rename_template, verbose_name=_('Snippet'), help_text=_('Report snippet file'), validators=[FileExtensionValidator(allowed_extensions=['html', 'htm'])], @@ -657,26 +513,7 @@ def validate_unique(self, exclude=None): ) -def rename_asset(instance, filename): - """Function to rename an asset file when uploaded.""" - path = ReportAsset.asset_path(filename) - fullpath = settings.MEDIA_ROOT.joinpath(path).resolve() - - # If the asset file is the *same* filename as the one being uploaded, - # delete the original one from the media directory - if str(filename) == str(instance.asset): - if fullpath.exists(): - # Check for existing asset file with the same name - logger.info("Deleting existing asset file: '%s'", filename) - os.remove(fullpath) - - # Ensure the cache is deleted for this asset - cache.delete(fullpath) - - return path - - -class ReportAsset(models.Model): +class ReportAsset(TemplateUploadMixin, models.Model): """Asset file for use in report templates. For example, an image to use in a header file. @@ -684,41 +521,12 @@ class ReportAsset(models.Model): and can be loaded in a template using the {% report_asset %} tag. """ - def __str__(self): - """String representation of a ReportAsset instance.""" - return f'assets/{self.filename}' - - @property - def filename(self): - """Return the filename of the asset.""" - path = self.asset.name - if path: - return os.path.basename(path) - else: - return '-' - - @staticmethod - def asset_path(filename): - """Return the fully-qualified asset path for the given filename.""" - return os.path.join('report', 'assets', os.path.basename(str(filename))) - - def validate_unique(self, exclude=None): - """Validate that this report asset is unique.""" - proposed_path = self.asset_path(self.asset) - - if ( - ReportAsset.objects.filter(asset=proposed_path).exclude(pk=self.pk).count() - > 0 - ): - raise ValidationError({ - 'asset': _('Asset file with this name already exists') - }) - - return super().validate_unique(exclude) + SUBDIR = 'assets' + TEMPLATE_FIELD = 'asset' # Asset file asset = models.FileField( - upload_to=rename_asset, + upload_to=rename_template, verbose_name=_('Asset'), help_text=_('Report asset file'), ) @@ -729,42 +537,3 @@ def validate_unique(self, exclude=None): verbose_name=_('Description'), help_text=_('Asset file description'), ) - - -class StockLocationReport(ReportTemplateBase): - """Render a StockLocationReport against a StockLocation object.""" - - @staticmethod - def get_api_url(): - """Return the API URL associated with the StockLocationReport model.""" - return reverse('api-stocklocation-report-list') - - @classmethod - def getSubdir(cls): - """Return the subdirectory where StockLocationReport templates are located.""" - return 'slr' - - filters = models.CharField( - blank=True, - max_length=250, - verbose_name=_('Filters'), - help_text=_( - 'stock location query filters (comma-separated list of key=value pairs)' - ), - validators=[validate_stock_location_report_filters], - ) - - def get_context_data(self, request): - """Return custom context data for the StockLocationReport template.""" - stock_location = self.object_to_print - - if not isinstance(stock_location, stock.models.StockLocation): - raise TypeError( - 'Provided model is not a StockLocation object -> ' - + str(type(stock_location)) - ) - - return { - 'stock_location': stock_location, - 'stock_items': stock_location.get_stock_items(), - } diff --git a/src/backend/InvenTree/report/serializers.py b/src/backend/InvenTree/report/serializers.py index 320c489a3733..1dadc7114ff8 100644 --- a/src/backend/InvenTree/report/serializers.py +++ b/src/backend/InvenTree/report/serializers.py @@ -1,102 +1,208 @@ """API serializers for the reporting models.""" +from django.utils.translation import gettext_lazy as _ + from rest_framework import serializers +import plugin.models +import plugin.serializers +import report.helpers import report.models from InvenTree.serializers import ( InvenTreeAttachmentSerializerField, InvenTreeModelSerializer, + UserSerializer, ) class ReportSerializerBase(InvenTreeModelSerializer): - """Base class for report serializer.""" + """Base serializer class for report and label templates.""" - template = InvenTreeAttachmentSerializerField(required=True) + 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_type'].choices) == 0: + self.fields['model_type'].choices = report.helpers.report_model_options() @staticmethod - def report_fields(): - """Generic serializer fields for a report template.""" + def base_fields(): + """Base serializer field set.""" return [ 'pk', 'name', 'description', + 'model_type', 'template', 'filters', - 'page_size', - 'landscape', + 'filename_pattern', 'enabled', + 'revision', ] + template = InvenTreeAttachmentSerializerField(required=True) + + revision = serializers.IntegerField(read_only=True) -class TestReportSerializer(ReportSerializerBase): - """Serializer class for the TestReport model.""" + # Note: The choices are overridden at run-time + model_type = serializers.ChoiceField( + label=_('Model Type'), + choices=report.helpers.report_model_options(), + required=True, + allow_blank=False, + allow_null=False, + ) + + +class ReportTemplateSerializer(ReportSerializerBase): + """Serializer class for report template model.""" class Meta: """Metaclass options.""" - model = report.models.TestReport - fields = ReportSerializerBase.report_fields() + model = report.models.ReportTemplate + fields = [*ReportSerializerBase.base_fields(), 'page_size', 'landscape'] + + page_size = serializers.ChoiceField( + required=False, + default=report.helpers.report_page_size_default(), + choices=report.helpers.report_page_size_options(), + ) -class BuildReportSerializer(ReportSerializerBase): - """Serializer class for the BuildReport model.""" +class ReportPrintSerializer(serializers.Serializer): + """Serializer class for printing a report.""" class Meta: """Metaclass options.""" - model = report.models.BuildReport - fields = ReportSerializerBase.report_fields() + fields = ['template', 'items'] + template = serializers.PrimaryKeyRelatedField( + queryset=report.models.ReportTemplate.objects.all(), + many=False, + required=True, + allow_null=False, + label=_('Template'), + help_text=_('Select report template'), + ) -class BOMReportSerializer(ReportSerializerBase): - """Serializer class for the BillOfMaterialsReport model.""" + items = serializers.ListField( + child=serializers.IntegerField(), + required=True, + allow_empty=False, + label=_('Items'), + help_text=_('List of item primary keys to include in the report'), + ) - class Meta: - """Metaclass options.""" - model = report.models.BillOfMaterialsReport - fields = ReportSerializerBase.report_fields() +class LabelPrintSerializer(serializers.Serializer): + """Serializer class for printing a label.""" + # List of extra plugin field names + plugin_fields = [] -class PurchaseOrderReportSerializer(ReportSerializerBase): - """Serializer class for the PurchaseOrdeReport model.""" + class Meta: + """Metaclass options.""" + + fields = ['template', 'items', 'plugin'] + + 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.fields.items(): + self.Meta.fields.append(key) + setattr(self, key, field) + + super().__init__(*args, **kwargs) + + template = serializers.PrimaryKeyRelatedField( + queryset=report.models.LabelTemplate.objects.all(), + many=False, + required=True, + allow_null=False, + label=_('Template'), + help_text=_('Select label template'), + ) + + # Plugin field - note that we use the 'key' (not the pk) for lookup + plugin = plugin.serializers.PluginRelationSerializer( + many=False, + required=False, + allow_null=False, + label=_('Printing Plugin'), + help_text=_('Select plugin to use for label printing'), + ) + + items = serializers.ListField( + child=serializers.IntegerField(), + required=True, + allow_empty=False, + label=_('Items'), + help_text=_('List of item primary keys to include in the report'), + ) + + +class LabelTemplateSerializer(ReportSerializerBase): + """Serializer class for label template model.""" class Meta: """Metaclass options.""" - model = report.models.PurchaseOrderReport - fields = ReportSerializerBase.report_fields() + model = report.models.LabelTemplate + fields = [*ReportSerializerBase.base_fields(), 'width', 'height'] -class SalesOrderReportSerializer(ReportSerializerBase): - """Serializer class for the SalesOrderReport model.""" +class BaseOutputSerializer(InvenTreeModelSerializer): + """Base serializer class for template output.""" - class Meta: - """Metaclass options.""" + @staticmethod + def base_fields(): + """Basic field set.""" + return [ + 'pk', + 'created', + 'user', + 'user_detail', + 'model_type', + 'items', + 'complete', + 'progress', + 'output', + 'template', + ] + + output = InvenTreeAttachmentSerializerField() + model_type = serializers.CharField(source='template.model_type', read_only=True) - model = report.models.SalesOrderReport - fields = ReportSerializerBase.report_fields() + user_detail = UserSerializer(source='user', read_only=True, many=False) -class ReturnOrderReportSerializer(ReportSerializerBase): - """Serializer class for the ReturnOrderReport model.""" +class LabelOutputSerializer(BaseOutputSerializer): + """Serializer class for the LabelOutput model.""" class Meta: """Metaclass options.""" - model = report.models.ReturnOrderReport - fields = ReportSerializerBase.report_fields() + model = report.models.LabelOutput + fields = [*BaseOutputSerializer.base_fields(), 'plugin'] -class StockLocationReportSerializer(ReportSerializerBase): - """Serializer class for the StockLocationReport model.""" +class ReportOutputSerializer(BaseOutputSerializer): + """Serializer class for the ReportOutput model.""" class Meta: """Metaclass options.""" - model = report.models.StockLocationReport - fields = ReportSerializerBase.report_fields() + model = report.models.ReportOutput + fields = BaseOutputSerializer.base_fields() class ReportSnippetSerializer(InvenTreeModelSerializer): diff --git a/src/backend/InvenTree/report/tasks.py b/src/backend/InvenTree/report/tasks.py new file mode 100644 index 000000000000..606cd7130461 --- /dev/null +++ b/src/backend/InvenTree/report/tasks.py @@ -0,0 +1,17 @@ +"""Background tasks for the report app.""" + +from datetime import timedelta + +from InvenTree.helpers import current_time +from InvenTree.tasks import ScheduledTask, scheduled_task +from report.models import LabelOutput, ReportOutput + + +@scheduled_task(ScheduledTask.DAILY) +def cleanup_old_report_outputs(): + """Remove old report/label outputs from the database.""" + # Remove any outputs which are older than 5 days + threshold = current_time() - timedelta(days=5) + + LabelOutput.objects.filter(created__lte=threshold).delete() + ReportOutput.objects.filter(created__lte=threshold).delete() diff --git a/src/backend/InvenTree/label/templates/label/buildline/buildline_label_base.html b/src/backend/InvenTree/report/templates/label/buildline_label.html similarity index 100% rename from src/backend/InvenTree/label/templates/label/buildline/buildline_label_base.html rename to src/backend/InvenTree/report/templates/label/buildline_label.html diff --git a/src/backend/InvenTree/label/templates/label/label_base.html b/src/backend/InvenTree/report/templates/label/label_base.html similarity index 100% rename from src/backend/InvenTree/label/templates/label/label_base.html rename to src/backend/InvenTree/report/templates/label/label_base.html diff --git a/src/backend/InvenTree/label/templates/label/part/part_label.html b/src/backend/InvenTree/report/templates/label/part_label.html similarity index 100% rename from src/backend/InvenTree/label/templates/label/part/part_label.html rename to src/backend/InvenTree/report/templates/label/part_label.html diff --git a/src/backend/InvenTree/label/templates/label/part/part_label_code128.html b/src/backend/InvenTree/report/templates/label/part_label_code128.html similarity index 100% rename from src/backend/InvenTree/label/templates/label/part/part_label_code128.html rename to src/backend/InvenTree/report/templates/label/part_label_code128.html diff --git a/src/backend/InvenTree/label/templates/label/stockitem/qr.html b/src/backend/InvenTree/report/templates/label/stockitem_qr.html similarity index 100% rename from src/backend/InvenTree/label/templates/label/stockitem/qr.html rename to src/backend/InvenTree/report/templates/label/stockitem_qr.html diff --git a/src/backend/InvenTree/label/templates/label/stocklocation/qr.html b/src/backend/InvenTree/report/templates/label/stocklocation_qr.html similarity index 100% rename from src/backend/InvenTree/label/templates/label/stocklocation/qr.html rename to src/backend/InvenTree/report/templates/label/stocklocation_qr.html diff --git a/src/backend/InvenTree/label/templates/label/stocklocation/qr_and_text.html b/src/backend/InvenTree/report/templates/label/stocklocation_qr_and_text.html similarity index 100% rename from src/backend/InvenTree/label/templates/label/stocklocation/qr_and_text.html rename to src/backend/InvenTree/report/templates/label/stocklocation_qr_and_text.html diff --git a/src/backend/InvenTree/report/templates/report/inventree_build_order.html b/src/backend/InvenTree/report/templates/report/inventree_build_order.html deleted file mode 100644 index 72e52a889ad9..000000000000 --- a/src/backend/InvenTree/report/templates/report/inventree_build_order.html +++ /dev/null @@ -1,3 +0,0 @@ -{% extends "report/inventree_build_order_base.html" %} - - diff --git a/src/backend/InvenTree/report/templates/report/inventree_build_order_base.html b/src/backend/InvenTree/report/templates/report/inventree_build_order_report.html similarity index 100% rename from src/backend/InvenTree/report/templates/report/inventree_build_order_base.html rename to src/backend/InvenTree/report/templates/report/inventree_build_order_report.html diff --git a/src/backend/InvenTree/report/templates/report/inventree_order_report_base.html b/src/backend/InvenTree/report/templates/report/inventree_order_report_base.html index 6f936681dc3f..f099b8425df3 100644 --- a/src/backend/InvenTree/report/templates/report/inventree_order_report_base.html +++ b/src/backend/InvenTree/report/templates/report/inventree_order_report_base.html @@ -12,7 +12,7 @@ {% endblock page_margin %} {% block bottom_left %} -content: "v{{ report_revision }} - {% format_date date %}"; +content: "v{{ template_revision }} - {% format_date date %}"; {% endblock bottom_left %} {% block bottom_center %} diff --git a/src/backend/InvenTree/report/templates/report/inventree_po_report.html b/src/backend/InvenTree/report/templates/report/inventree_po_report.html deleted file mode 100644 index 184ea896e19b..000000000000 --- a/src/backend/InvenTree/report/templates/report/inventree_po_report.html +++ /dev/null @@ -1 +0,0 @@ -{% extends "report/inventree_po_report_base.html" %} diff --git a/src/backend/InvenTree/report/templates/report/inventree_po_report_base.html b/src/backend/InvenTree/report/templates/report/inventree_purchase_order_report.html similarity index 100% rename from src/backend/InvenTree/report/templates/report/inventree_po_report_base.html rename to src/backend/InvenTree/report/templates/report/inventree_purchase_order_report.html diff --git a/src/backend/InvenTree/report/templates/report/inventree_return_order_report.html b/src/backend/InvenTree/report/templates/report/inventree_return_order_report.html index cece937a0e15..0dbc062e7114 100644 --- a/src/backend/InvenTree/report/templates/report/inventree_return_order_report.html +++ b/src/backend/InvenTree/report/templates/report/inventree_return_order_report.html @@ -1 +1,62 @@ -{% extends "report/inventree_return_order_report_base.html" %} +{% extends "report/inventree_order_report_base.html" %} + +{% load i18n %} +{% load report %} +{% load barcode %} +{% load inventree_extras %} +{% load markdownify %} + +{% block header_content %} + + +
+

{% trans "Return Order" %} {{ prefix }}{{ reference }}

+ {% if customer %}{{ customer.name }}{% endif %} +
+{% endblock header_content %} + +{% block page_content %} +

{% trans "Line Items" %}

+ + + + + + + + + + + + {% for line in lines.all %} + + + + + + + {% endfor %} + + {% if extra_lines %} + + {% for line in extra_lines.all %} + + + + + + + {% endfor %} + {% endif %} + + +
{% trans "Part" %}{% trans "Serial Number" %}{% trans "Reference" %}{% trans "Note" %}
+
+ {% trans "Image" %} +
+
+ {{ line.item.part.full_name }} +
+
{{ line.item.serial }}{{ line.reference }}{{ line.notes }}
{% trans "Extra Line Items" %}
{{ line.reference }}{{ line.notes }}
+ +{% endblock page_content %} diff --git a/src/backend/InvenTree/report/templates/report/inventree_return_order_report_base.html b/src/backend/InvenTree/report/templates/report/inventree_return_order_report_base.html deleted file mode 100644 index 0dbc062e7114..000000000000 --- a/src/backend/InvenTree/report/templates/report/inventree_return_order_report_base.html +++ /dev/null @@ -1,62 +0,0 @@ -{% extends "report/inventree_order_report_base.html" %} - -{% load i18n %} -{% load report %} -{% load barcode %} -{% load inventree_extras %} -{% load markdownify %} - -{% block header_content %} - - -
-

{% trans "Return Order" %} {{ prefix }}{{ reference }}

- {% if customer %}{{ customer.name }}{% endif %} -
-{% endblock header_content %} - -{% block page_content %} -

{% trans "Line Items" %}

- - - - - - - - - - - - {% for line in lines.all %} - - - - - - - {% endfor %} - - {% if extra_lines %} - - {% for line in extra_lines.all %} - - - - - - - {% endfor %} - {% endif %} - - -
{% trans "Part" %}{% trans "Serial Number" %}{% trans "Reference" %}{% trans "Note" %}
-
- {% trans "Image" %} -
-
- {{ line.item.part.full_name }} -
-
{{ line.item.serial }}{{ line.reference }}{{ line.notes }}
{% trans "Extra Line Items" %}
{{ line.reference }}{{ line.notes }}
- -{% endblock page_content %} diff --git a/src/backend/InvenTree/report/templates/report/inventree_so_report_base.html b/src/backend/InvenTree/report/templates/report/inventree_sales_order_report.html similarity index 100% rename from src/backend/InvenTree/report/templates/report/inventree_so_report_base.html rename to src/backend/InvenTree/report/templates/report/inventree_sales_order_report.html diff --git a/src/backend/InvenTree/report/templates/report/inventree_so_report.html b/src/backend/InvenTree/report/templates/report/inventree_so_report.html deleted file mode 100644 index dbb4543bf39f..000000000000 --- a/src/backend/InvenTree/report/templates/report/inventree_so_report.html +++ /dev/null @@ -1 +0,0 @@ -{% extends "report/inventree_so_report_base.html" %} diff --git a/src/backend/InvenTree/report/templates/report/inventree_slr_report.html b/src/backend/InvenTree/report/templates/report/inventree_stock_location_report.html similarity index 100% rename from src/backend/InvenTree/report/templates/report/inventree_slr_report.html rename to src/backend/InvenTree/report/templates/report/inventree_stock_location_report.html diff --git a/src/backend/InvenTree/report/templates/report/inventree_test_report.html b/src/backend/InvenTree/report/templates/report/inventree_test_report.html index 4607494f8f9d..4e25b4598fca 100644 --- a/src/backend/InvenTree/report/templates/report/inventree_test_report.html +++ b/src/backend/InvenTree/report/templates/report/inventree_test_report.html @@ -1,3 +1,184 @@ -{% extends "report/inventree_test_report_base.html" %} +{% extends "report/inventree_report_base.html" %} - +{% load i18n %} +{% load report %} +{% load inventree_extras %} + +{% block style %} +.test-table { + width: 100%; +} + +{% block bottom_left %} +content: "{% format_date date %}"; +{% endblock bottom_left %} + +{% block bottom_center %} +content: "{% inventree_version shortstring=True %}"; +{% endblock bottom_center %} + +{% block top_center %} +content: "{% trans 'Stock Item Test Report' %}"; +{% endblock top_center %} + +.test-row { + padding: 3px; +} + +.test-pass { + color: #5f5; +} + +.test-fail { + color: #F55; +} + +.test-not-found { + color: #33A; +} + +.required-test-not-found { + color: #EEE; + background-color: #F55; +} + +.container { + padding: 5px; + border: 1px solid; +} + +.text-left { + display: inline-block; + width: 50%; +} + +.img-right { + display: inline; + align-content: right; + align-items: right; + width: 50%; +} + +.part-img { + height: 4cm; +} + +{% endblock style %} + +{% block pre_page_content %} + +{% endblock pre_page_content %} + +{% block page_content %} + +
+
+

+ {{ part.full_name }} +

+

{{ part.description }}

+

{{ stock_item.location }}

+

Stock Item ID: {{ stock_item.pk }}

+
+
+ {% trans "Part image" %} +
+

+ {% if stock_item.is_serialized %} + {% trans "Serial Number" %}: {{ stock_item.serial }} + {% else %} + {% trans "Quantity" %}: {% decimal stock_item.quantity %} + {% endif %} +

+
+
+ +{% if test_keys|length > 0 %} +

{% trans "Test Results" %}

+ + + + + + + + + + + + + + + + {% for key in test_keys %} + + {% getkey test_template_map key as test_template %} + {% getkey results key as test_result %} + + + {% if test_result %} + {% if test_result.result %} + + {% else %} + + {% endif %} + + + + {% else %} + {% if test_template.required %} + + {% else %} + + {% endif %} + {% endif %} + + {% endfor %} + + +
{% trans "Test" %}{% trans "Result" %}{% trans "Value" %}{% trans "User" %}{% trans "Date" %}

+ {% if test_template %} + {% render_html_text test_template.test_name bold=test_template.required %} + {% elif test_result %} + {% render_html_text test_result.test italic=True %} + {% else %} + + {{ key }} + {% endif %} + {% trans "Pass" %}{% trans "Fail" %}{{ test_result.value }}{{ test_result.user.username }}{% format_date test_result.date.date %}{% trans "No result (required)" %}{% trans "No result" %}
+{% else %} +No tests defined for this stock item +{% endif %} + +{% if installed_items|length > 0 %} +

{% trans "Installed Items" %}

+ + + + + + {% for sub_item in installed_items %} + + + + + {% endfor %} + +
+ {% trans "Part image" %} + {{ sub_item.part.full_name }} + + {% if sub_item.serialized %} + {% trans "Serial" %}: {{ sub_item.serial }} + {% else %} + {% trans "Quantity" %}: {% decimal sub_item.quantity %} + {% endif %} +
+ +{% endif %} + +{% endblock page_content %} + +{% block post_page_content %} + +{% endblock post_page_content %} diff --git a/src/backend/InvenTree/report/templates/report/inventree_test_report_base.html b/src/backend/InvenTree/report/templates/report/inventree_test_report_base.html deleted file mode 100644 index 4e25b4598fca..000000000000 --- a/src/backend/InvenTree/report/templates/report/inventree_test_report_base.html +++ /dev/null @@ -1,184 +0,0 @@ -{% extends "report/inventree_report_base.html" %} - -{% load i18n %} -{% load report %} -{% load inventree_extras %} - -{% block style %} -.test-table { - width: 100%; -} - -{% block bottom_left %} -content: "{% format_date date %}"; -{% endblock bottom_left %} - -{% block bottom_center %} -content: "{% inventree_version shortstring=True %}"; -{% endblock bottom_center %} - -{% block top_center %} -content: "{% trans 'Stock Item Test Report' %}"; -{% endblock top_center %} - -.test-row { - padding: 3px; -} - -.test-pass { - color: #5f5; -} - -.test-fail { - color: #F55; -} - -.test-not-found { - color: #33A; -} - -.required-test-not-found { - color: #EEE; - background-color: #F55; -} - -.container { - padding: 5px; - border: 1px solid; -} - -.text-left { - display: inline-block; - width: 50%; -} - -.img-right { - display: inline; - align-content: right; - align-items: right; - width: 50%; -} - -.part-img { - height: 4cm; -} - -{% endblock style %} - -{% block pre_page_content %} - -{% endblock pre_page_content %} - -{% block page_content %} - -
-
-

- {{ part.full_name }} -

-

{{ part.description }}

-

{{ stock_item.location }}

-

Stock Item ID: {{ stock_item.pk }}

-
-
- {% trans "Part image" %} -
-

- {% if stock_item.is_serialized %} - {% trans "Serial Number" %}: {{ stock_item.serial }} - {% else %} - {% trans "Quantity" %}: {% decimal stock_item.quantity %} - {% endif %} -

-
-
- -{% if test_keys|length > 0 %} -

{% trans "Test Results" %}

- - - - - - - - - - - - - - - - {% for key in test_keys %} - - {% getkey test_template_map key as test_template %} - {% getkey results key as test_result %} - - - {% if test_result %} - {% if test_result.result %} - - {% else %} - - {% endif %} - - - - {% else %} - {% if test_template.required %} - - {% else %} - - {% endif %} - {% endif %} - - {% endfor %} - - -
{% trans "Test" %}{% trans "Result" %}{% trans "Value" %}{% trans "User" %}{% trans "Date" %}

- {% if test_template %} - {% render_html_text test_template.test_name bold=test_template.required %} - {% elif test_result %} - {% render_html_text test_result.test italic=True %} - {% else %} - - {{ key }} - {% endif %} - {% trans "Pass" %}{% trans "Fail" %}{{ test_result.value }}{{ test_result.user.username }}{% format_date test_result.date.date %}{% trans "No result (required)" %}{% trans "No result" %}
-{% else %} -No tests defined for this stock item -{% endif %} - -{% if installed_items|length > 0 %} -

{% trans "Installed Items" %}

- - - - - - {% for sub_item in installed_items %} - - - - - {% endfor %} - -
- {% trans "Part image" %} - {{ sub_item.part.full_name }} - - {% if sub_item.serialized %} - {% trans "Serial" %}: {{ sub_item.serial }} - {% else %} - {% trans "Quantity" %}: {% decimal sub_item.quantity %} - {% endif %} -
- -{% endif %} - -{% endblock page_content %} - -{% block post_page_content %} - -{% endblock post_page_content %} diff --git a/src/backend/InvenTree/report/tests.py b/src/backend/InvenTree/report/tests.py index 4d40a2c460fd..eeec4f80ea55 100644 --- a/src/backend/InvenTree/report/tests.py +++ b/src/backend/InvenTree/report/tests.py @@ -1,12 +1,10 @@ """Unit testing for the various report models.""" -import os -import shutil from io import StringIO +from django.apps import apps from django.conf import settings from django.core.cache import cache -from django.http.response import StreamingHttpResponse from django.test import TestCase, override_settings from django.urls import reverse from django.utils import timezone @@ -17,9 +15,11 @@ import report.models as report_models from build.models import Build -from common.models import InvenTreeSetting, InvenTreeUserSetting -from InvenTree.files import MEDIA_STORAGE_DIR, TEMPLATES_DIR +from common.models import InvenTreeSetting from InvenTree.unit_test import InvenTreeAPITestCase +from order.models import ReturnOrder, SalesOrder +from plugin.registry import registry +from report.models import LabelTemplate, ReportTemplate from report.templatetags import barcode as barcode_tags from report.templatetags import report as report_tags from stock.models import StockItem, StockItemAttachment @@ -233,64 +233,29 @@ class ReportTest(InvenTreeAPITestCase): 'stock_tests', 'bom', 'build', + 'order', + 'return_order', + 'sales_order', ] superuser = True - model = None - list_url = None - detail_url = None - print_url = None - def setUp(self): """Ensure cache is cleared as part of test setup.""" cache.clear() - return super().setUp() - - def copyReportTemplate(self, filename, description): - """Copy the provided report template into the required media directory.""" - src_dir = TEMPLATES_DIR.joinpath('report', 'templates', 'report') - template_dir = os.path.join('report', 'inventree', self.model.getSubdir()) - dst_dir = MEDIA_STORAGE_DIR.joinpath(template_dir) - - if not dst_dir.exists(): # pragma: no cover - dst_dir.mkdir(parents=True, exist_ok=True) - - src_file = src_dir.joinpath(filename) - dst_file = dst_dir.joinpath(filename) - - if not dst_file.exists(): # pragma: no cover - shutil.copyfile(src_file, dst_file) - - # Convert to an "internal" filename - db_filename = os.path.join(template_dir, filename) - # Create a database entry for this report template! - self.model.objects.create( - name=os.path.splitext(filename)[0], - description=description, - template=db_filename, - enabled=True, - ) - - def test_api_url(self): - """Test returned API Url against URL tag defined in this file.""" - if not self.list_url: - return + apps.get_app_config('report').create_default_reports() - self.assertEqual(reverse(self.list_url), self.model.get_api_url()) + return super().setUp() def test_list_endpoint(self): """Test that the LIST endpoint works for each report.""" - if not self.list_url: - return - - url = reverse(self.list_url) + url = reverse('api-report-template-list') response = self.get(url) self.assertEqual(response.status_code, 200) - reports = self.model.objects.all() + reports = ReportTemplate.objects.all() n = len(reports) # API endpoint must return correct number of reports @@ -317,10 +282,7 @@ def test_list_endpoint(self): def test_create_endpoint(self): """Test that creating a new report works for each report.""" - if not self.list_url: - return - - url = reverse(self.list_url) + 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, @@ -330,16 +292,23 @@ def test_create_endpoint(self): ) filestr.name = 'ExampleTemplate.html' - response = self.post( - url, - data={ - 'name': 'New report', - 'description': 'A fancy new report created through API test', - 'template': filestr, - }, - format=None, - expected_code=201, - ) + data = { + 'name': 'New report', + 'description': 'A fancy new report created through API test', + 'template': filestr, + 'model_type': 'part2', + } + + # Test with invalid model type + response = self.post(url, data=data, expected_code=400) + + self.assertIn('"part2" is not a valid choice', str(response.data['model_type'])) + + # With valid model type + data['model_type'] = 'part' + filestr.seek(0) + + response = self.post(url, data=data, format=None, expected_code=201) # Make sure the expected keys are in the response self.assertIn('pk', response.data) @@ -357,10 +326,7 @@ def test_create_endpoint(self): def test_detail_endpoint(self): """Test that the DETAIL endpoint works for each report.""" - if not self.detail_url: - return - - reports = self.model.objects.all() + reports = ReportTemplate.objects.all() n = len(reports) @@ -369,7 +335,8 @@ def test_detail_endpoint(self): # Check detail page for first report response = self.get( - reverse(self.detail_url, kwargs={'pk': reports[0].pk}), expected_code=200 + reverse('api-report-template-detail', kwargs={'pk': reports[0].pk}), + expected_code=200, ) # Make sure the expected keys are in the response @@ -387,7 +354,7 @@ def test_detail_endpoint(self): # Check PATCH method response = self.patch( - reverse(self.detail_url, kwargs={'pk': reports[0].pk}), + reverse('api-report-template-detail', kwargs={'pk': reports[0].pk}), { 'name': 'Changed name during test', 'description': 'New version of the template', @@ -414,218 +381,142 @@ def test_detail_endpoint(self): # Delete the last report response = self.delete( - reverse(self.detail_url, kwargs={'pk': reports[n - 1].pk}), + reverse('api-report-template-detail', kwargs={'pk': reports[n - 1].pk}), expected_code=204, ) def test_metadata(self): """Unit tests for the metadata field.""" - if self.model is not None: - p = self.model.objects.first() + p = ReportTemplate.objects.first() + + self.assertEqual(p.metadata, {}) + + self.assertIsNone(p.get_metadata('test')) + self.assertEqual(p.get_metadata('test', backup_value=123), 123) + + # Test update via the set_metadata() method + p.set_metadata('test', 3) + self.assertEqual(p.get_metadata('test'), 3) - self.assertEqual(p.metadata, {}) + for k in ['apple', 'banana', 'carrot', 'carrot', 'banana']: + p.set_metadata(k, k) - self.assertIsNone(p.get_metadata('test')) - self.assertEqual(p.get_metadata('test', backup_value=123), 123) + self.assertEqual(len(p.metadata.keys()), 4) - # Test update via the set_metadata() method - p.set_metadata('test', 3) - self.assertEqual(p.get_metadata('test'), 3) - for k in ['apple', 'banana', 'carrot', 'carrot', 'banana']: - p.set_metadata(k, k) +class PrintTestMixins: + """Mixin that enables e2e printing tests.""" - self.assertEqual(len(p.metadata.keys()), 4) + plugin_ref = 'samplelabelprinter' + def do_activate_plugin(self): + """Activate the 'samplelabel' plugin.""" + config = registry.get_plugin(self.plugin_ref).plugin_config() + config.active = True + config.save() -class TestReportTest(ReportTest): + 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 = LabelTemplate if label else ReportTemplate + url = reverse('api-label-print' if label else 'api-report-print') + + qs = qs.objects.all() + template = mdl.objects.filter(enabled=True, model_type=model_type).first() + plugin = registry.get_plugin(self.plugin_ref) + + # Single page printing + self.post( + url, + {'template': template.pk, 'plugin': plugin.pk, 'items': [qs[0].pk]}, + expected_code=201, + ) + + # Multi page printing + self.post( + url, + { + 'template': template.pk, + 'plugin': plugin.pk, + 'items': [item.pk for item in qs], + }, + expected_code=201, + ) + + +class TestReportTest(PrintTestMixins, ReportTest): """Unit testing class for the stock item TestReport model.""" - model = report_models.TestReport + model = report_models.ReportTemplate - list_url = 'api-stockitem-testreport-list' - detail_url = 'api-stockitem-testreport-detail' - print_url = 'api-stockitem-testreport-print' + list_url = 'api-report-template-list' + detail_url = 'api-report-template-detail' + print_url = 'api-report-print' def setUp(self): """Setup function for the stock item TestReport.""" - self.copyReportTemplate('inventree_test_report.html', 'stock item test report') + apps.get_app_config('report').create_default_reports() + self.do_activate_plugin() return super().setUp() def test_print(self): """Printing tests for the TestReport.""" - report = self.model.objects.first() + template = ReportTemplate.objects.filter( + enabled=True, model_type='stockitem' + ).first() + self.assertIsNotNone(template) - url = reverse(self.print_url, kwargs={'pk': report.pk}) + url = reverse(self.print_url) # Try to print without providing a valid StockItem - response = self.get(url, expected_code=400) + self.post(url, {'template': template.pk}, expected_code=400) # Try to print with an invalid StockItem - response = self.get(url, {'item': 9999}, expected_code=400) + self.post(url, {'template': template.pk, 'items': [9999]}, expected_code=400) # Now print with a valid StockItem item = StockItem.objects.first() - response = self.get(url, {'item': item.pk}, expected_code=200) - - # Response should be a StreamingHttpResponse (PDF file) - self.assertEqual(type(response), StreamingHttpResponse) + response = self.post( + url, {'template': template.pk, 'items': [item.pk]}, expected_code=201 + ) - headers = response.headers - self.assertEqual(headers['Content-Type'], 'application/pdf') + # There should be a link to the generated PDF + self.assertEqual(response.data['output'].startswith('/media/report/'), True) # By default, this should *not* have created an attachment against this stockitem self.assertFalse(StockItemAttachment.objects.filter(stock_item=item).exists()) + return + # TODO @matmair - Re-add this test after https://github.com/inventree/InvenTree/pull/7074/files#r1600694356 is resolved # Change the setting, now the test report should be attached automatically InvenTreeSetting.set_setting('REPORT_ATTACH_TEST_REPORT', True, None) - response = self.get(url, {'item': item.pk}, expected_code=200) + response = self.post( + url, {'template': report.pk, 'items': [item.pk]}, expected_code=201 + ) - headers = response.headers - self.assertEqual(headers['Content-Type'], 'application/pdf') + # There should be a link to the generated PDF + self.assertEqual(response.data['output'].startswith('/media/report/'), True) # Check that a report has been uploaded attachment = StockItemAttachment.objects.filter(stock_item=item).first() self.assertIsNotNone(attachment) + def test_mdl_build(self): + """Test the Build model.""" + self.run_print_test(Build, 'build', label=False) -class BuildReportTest(ReportTest): - """Unit test class for the BuildReport model.""" - - model = report_models.BuildReport - - list_url = 'api-build-report-list' - detail_url = 'api-build-report-detail' - print_url = 'api-build-report-print' - - def setUp(self): - """Setup unit testing functions.""" - self.copyReportTemplate('inventree_build_order.html', 'build order template') - - return super().setUp() - - def test_print(self): - """Printing tests for the BuildReport.""" - report = self.model.objects.first() + def test_mdl_returnorder(self): + """Test the ReturnOrder model.""" + self.run_print_test(ReturnOrder, 'returnorder', label=False) - url = reverse(self.print_url, kwargs={'pk': report.pk}) - - # Try to print without providing a valid BuildOrder - response = self.get(url, expected_code=400) - - # Try to print with an invalid BuildOrder - response = self.get(url, {'build': 9999}, expected_code=400) - - # Now print with a valid BuildOrder - - build = Build.objects.first() - - response = self.get(url, {'build': build.pk}) - - self.assertEqual(type(response), StreamingHttpResponse) - - headers = response.headers - - self.assertEqual(headers['Content-Type'], 'application/pdf') - self.assertEqual( - headers['Content-Disposition'], 'attachment; filename="report.pdf"' - ) - - # Now, set the download type to be "inline" - inline = InvenTreeUserSetting.get_setting_object( - 'REPORT_INLINE', cache=False, user=self.user - ) - inline.value = True - inline.save() - - response = self.get(url, {'build': 1}) - headers = response.headers - self.assertEqual(headers['Content-Type'], 'application/pdf') - self.assertEqual( - headers['Content-Disposition'], 'inline; filename="report.pdf"' - ) - - -class BOMReportTest(ReportTest): - """Unit test class for the BillOfMaterialsReport model.""" - - model = report_models.BillOfMaterialsReport - - list_url = 'api-bom-report-list' - detail_url = 'api-bom-report-detail' - print_url = 'api-bom-report-print' - - def setUp(self): - """Setup function for the bill of materials Report.""" - self.copyReportTemplate( - 'inventree_bill_of_materials_report.html', 'bill of materials report' - ) - - return super().setUp() - - -class PurchaseOrderReportTest(ReportTest): - """Unit test class for the PurchaseOrderReport model.""" - - model = report_models.PurchaseOrderReport - - list_url = 'api-po-report-list' - detail_url = 'api-po-report-detail' - print_url = 'api-po-report-print' - - def setUp(self): - """Setup function for the purchase order Report.""" - self.copyReportTemplate('inventree_po_report.html', 'purchase order report') - - return super().setUp() - - -class SalesOrderReportTest(ReportTest): - """Unit test class for the SalesOrderReport model.""" - - model = report_models.SalesOrderReport - - list_url = 'api-so-report-list' - detail_url = 'api-so-report-detail' - print_url = 'api-so-report-print' - - def setUp(self): - """Setup function for the sales order Report.""" - self.copyReportTemplate('inventree_so_report.html', 'sales order report') - - return super().setUp() - - -class ReturnOrderReportTest(ReportTest): - """Unit tests for the ReturnOrderReport model.""" - - model = report_models.ReturnOrderReport - list_url = 'api-return-order-report-list' - detail_url = 'api-return-order-report-detail' - print_url = 'api-return-order-report-print' - - def setUp(self): - """Setup function for the ReturnOrderReport tests.""" - self.copyReportTemplate( - 'inventree_return_order_report.html', 'return order report' - ) - - return super().setUp() - - -class StockLocationReportTest(ReportTest): - """Unit tests for the StockLocationReport model.""" - - model = report_models.StockLocationReport - list_url = 'api-stocklocation-report-list' - detail_url = 'api-stocklocation-report-detail' - print_url = 'api-stocklocation-report-print' - - def setUp(self): - """Setup function for the StockLocationReport tests.""" - self.copyReportTemplate('inventree_slr_report.html', 'stock location report') - - return super().setUp() + def test_mdl_salesorder(self): + """Test the SalesOrder model.""" + self.run_print_test(SalesOrder, 'salesorder', label=False) diff --git a/src/backend/InvenTree/report/validators.py b/src/backend/InvenTree/report/validators.py new file mode 100644 index 000000000000..ad9e8e0d3345 --- /dev/null +++ b/src/backend/InvenTree/report/validators.py @@ -0,0 +1,20 @@ +"""Validators for report models.""" + +from django.core.exceptions import ValidationError + +import report.helpers + + +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') + + +def validate_filters(value, model=None): + """Validate that the provided model filters are valid.""" + from InvenTree.helpers import validateFilterString + + return validateFilterString(value, model=model) diff --git a/src/backend/InvenTree/stock/migrations/0001_initial.py b/src/backend/InvenTree/stock/migrations/0001_initial.py index 09c033c06b84..040a48efeb3f 100644 --- a/src/backend/InvenTree/stock/migrations/0001_initial.py +++ b/src/backend/InvenTree/stock/migrations/0001_initial.py @@ -35,6 +35,9 @@ class Migration(migrations.Migration): ('belongs_to', models.ForeignKey(blank=True, help_text='Is this item installed in another item?', null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='owned_parts', to='stock.StockItem')), ('customer', models.ForeignKey(blank=True, help_text='Item assigned to customer?', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='stockitems', to='company.Company')), ], + options={ + 'verbose_name': 'Stock Item', + } ), migrations.CreateModel( name='StockLocation', diff --git a/src/backend/InvenTree/stock/models.py b/src/backend/InvenTree/stock/models.py index ab20bc59aa3f..17a4385a39a0 100644 --- a/src/backend/InvenTree/stock/models.py +++ b/src/backend/InvenTree/stock/models.py @@ -30,7 +30,7 @@ import InvenTree.models import InvenTree.ready import InvenTree.tasks -import label.models +import report.mixins import report.models from company import models as CompanyModels from InvenTree.fields import InvenTreeModelMoneyField, InvenTreeURLField @@ -107,7 +107,9 @@ def get_queryset(self): class StockLocation( - InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models.InvenTreeTree + InvenTree.models.InvenTreeBarcodeMixin, + report.mixins.InvenTreeReportMixin, + InvenTree.models.InvenTreeTree, ): """Organization tree for StockItem objects. @@ -142,6 +144,16 @@ def get_api_url(): """Return API url.""" return reverse('api-location-list') + def report_context(self): + """Return report context data for this StockLocation.""" + return { + 'location': self, + 'qr_data': self.format_barcode(brief=True), + 'parent': self.parent, + 'stock_location': self, + 'stock_items': self.get_stock_items(), + } + custom_icon = models.CharField( blank=True, max_length=100, @@ -313,6 +325,7 @@ def default_delete_on_deplete(): class StockItem( InvenTree.models.InvenTreeBarcodeMixin, InvenTree.models.InvenTreeNotesMixin, + report.mixins.InvenTreeReportMixin, InvenTree.models.MetadataMixin, InvenTree.models.PluginValidationMixin, common.models.MetaMixin, @@ -345,6 +358,11 @@ class StockItem( packaging: Description of how the StockItem is packaged (e.g. "reel", "loose", "tape" etc) """ + class Meta: + """Model meta options.""" + + verbose_name = _('Stock Item') + @staticmethod def get_api_url(): """Return API url.""" @@ -354,6 +372,50 @@ def api_instance_filters(self): """Custom API instance filters.""" return {'parent': {'exclude_tree': self.pk}} + def get_test_keys(self, include_installed=True): + """Construct a flattened list of test 'keys' for this StockItem.""" + keys = [] + + for test in self.part.getTestTemplates(required=True): + if test.key not in keys: + keys.append(test.key) + + for test in self.part.getTestTemplates(required=False): + if test.key not in keys: + keys.append(test.key) + + for result in self.testResultList(include_installed=include_installed): + if result.key not in keys: + keys.append(result.key) + + return list(keys) + + def report_context(self): + """Generate custom report context data for this StockItem.""" + return { + 'barcode_data': self.barcode_data, + 'barcode_hash': self.barcode_hash, + 'batch': self.batch, + 'child_items': self.get_children(), + 'ipn': self.part.IPN, + 'installed_items': self.get_installed_items(cascade=True), + 'item': self, + 'name': self.part.full_name, + 'part': self.part, + 'qr_data': self.format_barcode(brief=True), + 'qr_url': self.get_absolute_url(), + 'parameters': self.part.parameters_map(), + 'quantity': InvenTree.helpers.normalize(self.quantity), + 'result_list': self.testResultList(include_installed=True), + 'results': self.testResultMap(include_installed=True), + 'serial': self.serial, + 'stock_item': self, + 'tests': self.testResultMap(), + 'test_keys': self.get_test_keys(), + 'test_template_list': self.part.getTestTemplates(), + 'test_templates': self.part.getTestTemplateMap(), + } + tags = TaggableManager(blank=True) # A Query filter which will be re-used in multiple places to determine if a StockItem is actually "in stock" @@ -2144,50 +2206,6 @@ def passedAllRequiredTests(self): return status['passed'] >= status['total'] - def available_test_reports(self): - """Return a list of TestReport objects which match this StockItem.""" - reports = [] - - item_query = StockItem.objects.filter(pk=self.pk) - - for test_report in report.models.TestReport.objects.filter(enabled=True): - # Attempt to validate report filter (skip if invalid) - try: - filters = InvenTree.helpers.validateFilterString(test_report.filters) - if item_query.filter(**filters).exists(): - reports.append(test_report) - except (ValidationError, FieldError): - continue - - return reports - - @property - def has_test_reports(self): - """Return True if there are test reports available for this stock item.""" - return len(self.available_test_reports()) > 0 - - def available_labels(self): - """Return a list of Label objects which match this StockItem.""" - labels = [] - - item_query = StockItem.objects.filter(pk=self.pk) - - for lbl in label.models.StockItemLabel.objects.filter(enabled=True): - try: - filters = InvenTree.helpers.validateFilterString(lbl.filters) - - if item_query.filter(**filters).exists(): - labels.append(lbl) - except (ValidationError, FieldError): - continue - - return labels - - @property - def has_labels(self): - """Return True if there are any label templates available for this stock item.""" - return len(self.available_labels()) > 0 - @receiver(pre_delete, sender=StockItem, dispatch_uid='stock_item_pre_delete_log') def before_delete_stock_item(sender, instance, using, **kwargs): diff --git a/src/backend/InvenTree/stock/templates/stock/item.html b/src/backend/InvenTree/stock/templates/stock/item.html index 33810b6da659..ab647bb795f6 100644 --- a/src/backend/InvenTree/stock/templates/stock/item.html +++ b/src/backend/InvenTree/stock/templates/stock/item.html @@ -242,11 +242,7 @@

{% trans "Installed Stock Items" %}

); $("#test-report").click(function() { - printReports({ - items: [{{ item.pk }}], - key: 'item', - url: '{% url "api-stockitem-testreport-list" %}', - }); + printReports('stockitem', [{{ item.pk }}]); }); {% if user.is_staff %} diff --git a/src/backend/InvenTree/stock/templates/stock/item_base.html b/src/backend/InvenTree/stock/templates/stock/item_base.html index c0e12b172ca8..05107cac28f5 100644 --- a/src/backend/InvenTree/stock/templates/stock/item_base.html +++ b/src/backend/InvenTree/stock/templates/stock/item_base.html @@ -494,19 +494,14 @@
{% if item.quantity != available %}{% decimal available %} / {% endif %}{% d }); $("#stock-test-report").click(function() { - printReports({ - items: [{{ item.pk }}], - key: 'item', - url: '{% url "api-stockitem-testreport-list" %}', - }); + printReports('stockitem', [{{ item.pk }}]); }); $("#print-label").click(function() { printLabels({ items: [{{ item.pk }}], + model_type: 'stockitem', singular_name: '{% trans "stock item" escape %}', - url: '{% url "api-stockitem-label-list" %}', - key: 'item', }); }); diff --git a/src/backend/InvenTree/stock/templates/stock/location.html b/src/backend/InvenTree/stock/templates/stock/location.html index 5cce5657cd11..50483ab0a3db 100644 --- a/src/backend/InvenTree/stock/templates/stock/location.html +++ b/src/backend/InvenTree/stock/templates/stock/location.html @@ -291,9 +291,8 @@

{% trans "Sublocations" %}

printLabels({ items: locs, + model_type: 'stocklocation', singular_name: '{% trans "stock location" escape %}', - key: 'location', - url: '{% url "api-stocklocation-label-list" %}', }); }); {% endif %} @@ -301,11 +300,7 @@

{% trans "Sublocations" %}

{% if report_enabled %} $('#print-location-report').click(function() { - printReports({ - items: [{{ location.pk }}], - key: 'location', - url: '{% url "api-stocklocation-report-list" %}', - }); + printReports('stocklocation', [{{ location.pk }}]); }); {% endif %} diff --git a/src/backend/InvenTree/templates/js/translated/api.js b/src/backend/InvenTree/templates/js/translated/api.js index c9bd3dbd1a30..58f001bdbf45 100644 --- a/src/backend/InvenTree/templates/js/translated/api.js +++ b/src/backend/InvenTree/templates/js/translated/api.js @@ -60,7 +60,7 @@ function inventreeGet(url, filters={}, options={}) { xhr.setRequestHeader('X-CSRFToken', csrftoken); }, url: url, - type: 'GET', + type: options.method ?? 'GET', data: filters, dataType: options.dataType || 'json', contentType: options.contentType || 'application/json', diff --git a/src/backend/InvenTree/templates/js/translated/filters.js b/src/backend/InvenTree/templates/js/translated/filters.js index 51fcc265b6a5..a6ad9e505c96 100644 --- a/src/backend/InvenTree/templates/js/translated/filters.js +++ b/src/backend/InvenTree/templates/js/translated/filters.js @@ -526,11 +526,7 @@ function setupFilterList(tableKey, table, target, options={}) { items.push(row.pk); }); - printReports({ - items: items, - url: options.report.url, - key: options.report.key - }); + printReports(options.report.key, items); }); } @@ -548,8 +544,7 @@ function setupFilterList(tableKey, table, target, options={}) { items: items, singular_name: options.singular_name, plural_name: options.plural_name, - url: options.labels.url, - key: options.labels.key, + model_type: options.labels?.model_type ?? options.model_type, }); }); } diff --git a/src/backend/InvenTree/templates/js/translated/forms.js b/src/backend/InvenTree/templates/js/translated/forms.js index 3f5539b7d8f8..dd187dc82905 100644 --- a/src/backend/InvenTree/templates/js/translated/forms.js +++ b/src/backend/InvenTree/templates/js/translated/forms.js @@ -1178,6 +1178,10 @@ function getFormFieldValue(name, field={}, options={}) { return null; } + if (field.hidden && !!field.value) { + return field.value; + } + var value = null; let guessed_type = guessFieldType(el); diff --git a/src/backend/InvenTree/templates/js/translated/label.js b/src/backend/InvenTree/templates/js/translated/label.js index a9a75f0f5698..0366f5b8b1ff 100644 --- a/src/backend/InvenTree/templates/js/translated/label.js +++ b/src/backend/InvenTree/templates/js/translated/label.js @@ -41,13 +41,15 @@ const defaultLabelTemplates = { * - Request printed labels * * Required options: - * - url: The list URL for the particular template type + * - model_type: The "type" of label template to print against * - items: The list of items to be printed * - key: The key to use in the query parameters * - plural_name: The plural name of the item type */ function printLabels(options) { + let pluginId = -1; + if (!options.items || options.items.length == 0) { showAlertDialog( '{% trans "Select Items" %}', @@ -56,145 +58,103 @@ function printLabels(options) { return; } + // Join the items with a comma character + const item_string = options.items.join(','); + let params = { enabled: true, + model_type: options.model_type, + items: item_string, }; - params[options.key] = options.items; - - // Request a list of available label templates from the server - let labelTemplates = []; - inventreeGet(options.url, params, { - async: false, - success: function (response) { - if (response.length == 0) { - showAlertDialog( - '{% trans "No Labels Found" %}', - '{% trans "No label templates found which match the selected items" %}', - ); - return; + function getPrintingFields(plugin_id, callback) { + let url = '{% url "api-label-print" %}' + `?plugin=${plugin_id}`; + + inventreeGet( + url, + { + plugin: plugin_id, + }, + { + method: 'OPTIONS', + success: function(response) { + let fields = response?.actions?.POST ?? {}; + callback(fields); + } } + ); + } - labelTemplates = response; - } - }); + // Callback when a particular label printing plugin is selected + function onPluginSelected(value, name, field, formOptions) { - // Request a list of available label printing plugins from the server - let plugins = []; - inventreeGet(`/api/plugins/`, { mixin: 'labels' }, { - async: false, - success: function (response) { - plugins = response; + if (value == pluginId) { + return; } - }); - let header_html = ""; + pluginId = value; - // show how much items are selected if there is more than one item selected - if (options.items.length > 1) { - header_html += ` -
- ${options.items.length} ${options.plural_name} {% trans "selected" %} -
- `; - } + // Request new printing options for the selected plugin + getPrintingFields(value, function(fields) { + formOptions.fields = getFormFields(fields); + updateForm(formOptions); - const updateFormUrl = (formOptions) => { - const plugin = getFormFieldValue("_plugin", formOptions.fields._plugin, formOptions); - const labelTemplate = getFormFieldValue("_label_template", formOptions.fields._label_template, formOptions); - const params = $.param({ plugin, [options.key]: options.items }) - formOptions.url = `${options.url}${labelTemplate ?? "1"}/print/?${params}`; + // workaround to fix a bug where one cannot scroll after changing the plugin + // without opening and closing the select box again manually + $("#id__plugin").select2("open"); + $("#id__plugin").select2("close"); + }); } - const updatePrintingOptions = (formOptions) => { - let printingOptionsRes = null; - $.ajax({ - url: formOptions.url, - type: "OPTIONS", - contentType: "application/json", - dataType: "json", - accepts: { json: "application/json" }, - async: false, - success: (res) => { printingOptionsRes = res }, - error: (xhr) => showApiError(xhr, formOptions.url) - }); + const baseFields = { + template: {}, + plugin: {}, + items: {} + }; - const printingOptions = printingOptionsRes.actions.POST || {}; + function getFormFields(customFields={}) { + let fields = { + ...baseFields, + ...customFields, + }; - // clear all other options - formOptions.fields = { - _label_template: formOptions.fields._label_template, - _plugin: formOptions.fields._plugin, - } + fields['template'].filters = { + enabled: true, + model_type: options.model_type, + items: item_string, + }; - if (Object.keys(printingOptions).length > 0) { - formOptions.fields = { - ...formOptions.fields, - divider: { type: "candy", html: `
{% trans "Printing Options" %}
` }, - ...printingOptions, - }; - } + fields['plugin'].filters = { + active: true, + mixin: 'labels' + }; + + fields['plugin'].onEdit = onPluginSelected; - // update form - updateForm(formOptions); + fields['items'].hidden = true; + fields['items'].value = options.items; - // workaround to fix a bug where one cannot scroll after changing the plugin - // without opening and closing the select box again manually - $("#id__plugin").select2("open"); - $("#id__plugin").select2("close"); + return fields; } - const printingFormOptions = { - title: options.items.length === 1 ? `{% trans "Print label" %}` : `{% trans "Print labels" %}`, - submitText: `{% trans "Print" %}`, - method: "POST", - disableSuccessMessage: true, - header_html, - fields: { - _label_template: { - label: `{% trans "Select label template" %}`, - type: "choice", - localOnly: true, - value: defaultLabelTemplates[options.key], - choices: labelTemplates.map(t => ({ - value: t.pk, - display_name: `${t.name} - ${t.description}`, - })), - onEdit: (_value, _name, _field, formOptions) => { - updateFormUrl(formOptions); - } - }, - _plugin: { - label: `{% trans "Select plugin" %}`, - type: "choice", - localOnly: true, - value: user_settings.LABEL_DEFAULT_PRINTER || plugins[0].key, - choices: plugins.map(p => ({ - value: p.key, - display_name: `${p.name} - ${p.meta.human_name}`, - })), - onEdit: (_value, _name, _field, formOptions) => { - updateFormUrl(formOptions); - updatePrintingOptions(formOptions); + constructForm('{% url "api-label-print" %}', { + method: 'POST', + title: '{% trans "Print Label" %}', + fields: getFormFields(), + onSuccess: function(response) { + if (response.complete) { + if (response.output) { + window.open(response.output, '_blank'); + } else { + showMessage('{% trans "Labels sent to printer" %}', { + style: 'success' + }); } - }, - }, - onSuccess: (response) => { - if (response.file) { - // Download the generated file - window.open(response.file); } else { - showMessage('{% trans "Labels sent to printer" %}', { - style: 'success', + showMessage('{% trans "Label printing failed" %}', { + style: 'warning', }); } } - }; - - // construct form - constructForm(null, printingFormOptions); - - // fetch the options for the default plugin - updateFormUrl(printingFormOptions); - updatePrintingOptions(printingFormOptions); + }); } diff --git a/src/backend/InvenTree/templates/js/translated/model_renderers.js b/src/backend/InvenTree/templates/js/translated/model_renderers.js index 66b05bf44d51..d2d0573ab8bc 100644 --- a/src/backend/InvenTree/templates/js/translated/model_renderers.js +++ b/src/backend/InvenTree/templates/js/translated/model_renderers.js @@ -92,6 +92,12 @@ function getModelRenderer(model) { return renderGroup; case 'projectcode': return renderProjectCode; + case 'labeltemplate': + return renderLabelTemplate; + case 'reporttemplate': + return renderReportTemplate; + case 'pluginconfig': + return renderPluginConfig; default: // Un-handled model type console.error(`Rendering not implemented for model '${model}'`); @@ -540,3 +546,42 @@ function renderProjectCode(data, parameters={}) { parameters ); } + + +// Renderer for "LabelTemplate" model +function renderLabelTemplate(data, parameters={}) { + + return renderModel( + { + text: data.name, + textSecondary: data.description, + }, + parameters + ); +} + + +// Renderer for "ReportTemplate" model +function renderReportTemplate(data, parameters={}) { + + return renderModel( + { + text: data.name, + textSecondary: data.description, + }, + parameters + ); +} + + +// Renderer for "PluginConfig" model +function renderPluginConfig(data, parameters={}) { + + return renderModel( + { + text: data.name, + textSecondary: data.meta?.description, + }, + parameters + ); +} diff --git a/src/backend/InvenTree/templates/js/translated/part.js b/src/backend/InvenTree/templates/js/translated/part.js index ffcea223d372..48b3dcfdbb6a 100644 --- a/src/backend/InvenTree/templates/js/translated/part.js +++ b/src/backend/InvenTree/templates/js/translated/part.js @@ -2281,8 +2281,7 @@ function loadPartTable(table, url, options={}) { setupFilterList('parts', $(table), options.filterTarget, { download: true, labels: { - url: '{% url "api-part-label-list" %}', - key: 'part', + model_type: 'part', }, singular_name: '{% trans "part" %}', plural_name: '{% trans "parts" %}', diff --git a/src/backend/InvenTree/templates/js/translated/purchase_order.js b/src/backend/InvenTree/templates/js/translated/purchase_order.js index c829fed14004..eb0571f763b0 100644 --- a/src/backend/InvenTree/templates/js/translated/purchase_order.js +++ b/src/backend/InvenTree/templates/js/translated/purchase_order.js @@ -1568,8 +1568,7 @@ function loadPurchaseOrderTable(table, options) { setupFilterList('purchaseorder', $(table), '#filter-list-purchaseorder', { download: true, report: { - url: '{% url "api-po-report-list" %}', - key: 'order', + key: 'purchaseorder', } }); diff --git a/src/backend/InvenTree/templates/js/translated/report.js b/src/backend/InvenTree/templates/js/translated/report.js index a6d124a3cd29..65dee7479c21 100644 --- a/src/backend/InvenTree/templates/js/translated/report.js +++ b/src/backend/InvenTree/templates/js/translated/report.js @@ -3,6 +3,7 @@ /* globals attachSelect, closeModal, + constructForm, inventreeGet, openModal, makeOptionsList, @@ -11,98 +12,13 @@ modalSetTitle, modalSubmit, showAlertDialog, + showMessage, */ /* exported printReports, */ -/** - * Present the user with the available reports, - * and allow them to select which report to print. - * - * The intent is that the available report templates have been requested - * (via AJAX) from the server. - */ -function selectReport(reports, items, options={}) { - - // If there is only a single report available, just print! - if (reports.length == 1) { - if (options.success) { - options.success(reports[0].pk); - } - - return; - } - - var modal = options.modal || '#modal-form'; - - var report_list = makeOptionsList( - reports, - function(item) { - var text = item.name; - - if (item.description) { - text += ` - ${item.description}`; - } - - return text; - }, - function(item) { - return item.pk; - } - ); - - // Construct form - var html = ''; - - if (items.length > 0) { - - html += ` -
- ${items.length} {% trans "items selected" %} -
`; - } - - html += ` -
-
- -
- -
-
-
`; - - openModal({ - modal: modal, - }); - - modalEnable(modal, true); - modalSetTitle(modal, '{% trans "Select Test Report Template" %}'); - modalSetContent(modal, html); - - attachSelect(modal); - - modalSubmit(modal, function() { - - var label = $(modal).find('#id_report'); - - var pk = label.val(); - - closeModal(modal); - - if (options.success) { - options.success(pk); - } - }); - -} - /* * Print report(s) for the selected items: @@ -112,49 +28,52 @@ function selectReport(reports, items, options={}) { * - Request printed document * * Required options: - * - url: The list URL for the particular template type + * - model_type: The "type" of report template to print against * - items: The list of objects to print - * - key: The key to use in the query parameters */ -function printReports(options) { +function printReports(model_type, items) { - if (!options.items || options.items.length == 0) { + if (!items || items.length == 0) { showAlertDialog( '{% trans "Select Items" %}', - '{% trans "No items selected for printing" }', + '{% trans "No items selected for printing" %}', ); return; } - let params = { - enabled: true, - }; - - params[options.key] = options.items; - - // Request a list of available report templates - inventreeGet(options.url, params, { - success: function(response) { - if (response.length == 0) { - showAlertDialog( - '{% trans "No Reports Found" %}', - '{% trans "No report templates found which match the selected items" %}', - ); - return; + // Join the items with a comma character + const item_string = items.join(','); + + constructForm('{% url "api-report-print" %}', { + method: 'POST', + title: '{% trans "Print Report" %}', + fields: { + template: { + filters: { + enabled: true, + model_type: model_type, + items: item_string, + } + }, + items: { + hidden: true, + value: items, } - - // Select report template for printing - selectReport(response, options.items, { - success: function(pk) { - let href = `${options.url}${pk}/print/?`; - - options.items.forEach(function(item) { - href += `${options.key}=${item}&`; + }, + onSuccess: function(response) { + if (response.complete) { + if (response.output) { + window.open(response.output, '_blank'); + } else { + showMessage('{% trans "Report print successful" %}', { + style: 'success' }); - - window.open(href); } - }); + } else { + showMessage('{% trans "Report printing failed" %}', { + style: 'warning', + }); + } } - }); + }) } diff --git a/src/backend/InvenTree/templates/js/translated/return_order.js b/src/backend/InvenTree/templates/js/translated/return_order.js index 5163b9696d16..23c921dfc2b1 100644 --- a/src/backend/InvenTree/templates/js/translated/return_order.js +++ b/src/backend/InvenTree/templates/js/translated/return_order.js @@ -242,8 +242,7 @@ function loadReturnOrderTable(table, options={}) { setupFilterList('returnorder', $(table), '#filter-list-returnorder', { download: true, report: { - url: '{% url "api-return-order-report-list" %}', - key: 'order', + key: 'returnorder', } }); diff --git a/src/backend/InvenTree/templates/js/translated/sales_order.js b/src/backend/InvenTree/templates/js/translated/sales_order.js index f7c6eea8a314..358c91b2ae93 100644 --- a/src/backend/InvenTree/templates/js/translated/sales_order.js +++ b/src/backend/InvenTree/templates/js/translated/sales_order.js @@ -682,8 +682,7 @@ function loadSalesOrderTable(table, options) { setupFilterList('salesorder', $(table), '#filter-list-salesorder', { download: true, report: { - url: '{% url "api-so-report-list" %}', - key: 'order' + key: 'salesorder' } }); diff --git a/src/backend/InvenTree/templates/js/translated/stock.js b/src/backend/InvenTree/templates/js/translated/stock.js index e88f0602bbdc..d5d9e15e4bec 100644 --- a/src/backend/InvenTree/templates/js/translated/stock.js +++ b/src/backend/InvenTree/templates/js/translated/stock.js @@ -1944,12 +1944,10 @@ function loadStockTable(table, options) { setupFilterList(filterKey, table, filterTarget, { download: true, report: { - url: '{% url "api-stockitem-testreport-list" %}', - key: 'item', + key: 'stockitem', }, labels: { - url: '{% url "api-stockitem-label-list" %}', - key: 'item', + model_type: 'stockitem', }, singular_name: '{% trans "stock item" %}', plural_name: '{% trans "stock items" %}', @@ -2569,8 +2567,7 @@ function loadStockLocationTable(table, options) { setupFilterList(filterKey, table, filterListElement, { download: true, labels: { - url: '{% url "api-stocklocation-label-list" %}', - key: 'location' + model_type: 'stocklocation', }, singular_name: '{% trans "stock location" %}', plural_name: '{% trans "stock locations" %}', diff --git a/src/backend/InvenTree/users/models.py b/src/backend/InvenTree/users/models.py index a816bde6e2a9..7c4ee8434957 100644 --- a/src/backend/InvenTree/users/models.py +++ b/src/backend/InvenTree/users/models.py @@ -224,11 +224,12 @@ def get_ruleset_models(): 'auth_permission', 'users_apitoken', 'users_ruleset', + 'report_labeloutput', + 'report_labeltemplate', 'report_reportasset', + 'report_reportoutput', 'report_reportsnippet', - 'report_billofmaterialsreport', - 'report_purchaseorderreport', - 'report_salesorderreport', + 'report_reporttemplate', 'account_emailaddress', 'account_emailconfirmation', 'socialaccount_socialaccount', @@ -270,22 +271,14 @@ def get_ruleset_models(): 'company_manufacturerpart', 'company_manufacturerpartparameter', 'company_manufacturerpartattachment', - 'label_partlabel', ], 'stocktake': ['part_partstocktake', 'part_partstocktakereport'], - 'stock_location': [ - 'stock_stocklocation', - 'stock_stocklocationtype', - 'label_stocklocationlabel', - 'report_stocklocationreport', - ], + 'stock_location': ['stock_stocklocation', 'stock_stocklocationtype'], 'stock': [ 'stock_stockitem', 'stock_stockitemattachment', 'stock_stockitemtracking', 'stock_stockitemtestresult', - 'report_testreport', - 'label_stockitemlabel', ], 'build': [ 'part_part', @@ -298,8 +291,6 @@ def get_ruleset_models(): 'build_buildorderattachment', 'stock_stockitem', 'stock_stocklocation', - 'report_buildreport', - 'label_buildlinelabel', ], 'purchase_order': [ 'company_company', @@ -314,7 +305,6 @@ def get_ruleset_models(): 'order_purchaseorderattachment', 'order_purchaseorderlineitem', 'order_purchaseorderextraline', - 'report_purchaseorderreport', ], 'sales_order': [ 'company_company', @@ -327,7 +317,6 @@ def get_ruleset_models(): 'order_salesorderlineitem', 'order_salesorderextraline', 'order_salesordershipment', - 'report_salesorderreport', ], 'return_order': [ 'company_company', @@ -338,7 +327,6 @@ def get_ruleset_models(): 'order_returnorderlineitem', 'order_returnorderextraline', 'order_returnorderattachment', - 'report_returnorderreport', ], } @@ -366,7 +354,6 @@ def get_ruleset_ignore(): 'common_projectcode', 'common_webhookendpoint', 'common_webhookmessage', - 'label_labeloutput', 'users_owner', # Third-party tables 'error_report_error', diff --git a/src/frontend/src/components/buttons/PrintingActions.tsx b/src/frontend/src/components/buttons/PrintingActions.tsx new file mode 100644 index 000000000000..81c5d8ddd69e --- /dev/null +++ b/src/frontend/src/components/buttons/PrintingActions.tsx @@ -0,0 +1,191 @@ +import { t } from '@lingui/macro'; +import { notifications } from '@mantine/notifications'; +import { IconPrinter, IconReport, IconTags } from '@tabler/icons-react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; + +import { api } from '../../App'; +import { ApiEndpoints } from '../../enums/ApiEndpoints'; +import { ModelType } from '../../enums/ModelType'; +import { extractAvailableFields } from '../../functions/forms'; +import { useCreateApiFormModal } from '../../hooks/UseForm'; +import { apiUrl } from '../../states/ApiState'; +import { useLocalState } from '../../states/LocalState'; +import { ApiFormFieldSet } from '../forms/fields/ApiFormField'; +import { ActionDropdown } from '../items/ActionDropdown'; + +export function PrintingActions({ + items, + enableLabels, + enableReports, + modelType +}: { + items: number[]; + enableLabels?: boolean; + enableReports?: boolean; + modelType?: ModelType; +}) { + const { host } = useLocalState.getState(); + + const enabled = useMemo(() => items.length > 0, [items]); + + const [pluginKey, setPluginKey] = useState(''); + + const loadFields = useCallback(() => { + if (!enableLabels) { + return; + } + + api + .options(apiUrl(ApiEndpoints.label_print), { + params: { + plugin: pluginKey || undefined + } + }) + .then((response: any) => { + setExtraFields(extractAvailableFields(response, 'POST') || {}); + }) + .catch(() => {}); + }, [enableLabels, pluginKey]); + + useEffect(() => { + loadFields(); + }, [loadFields, pluginKey]); + + const [extraFields, setExtraFields] = useState({}); + + const labelFields: ApiFormFieldSet = useMemo(() => { + let fields: ApiFormFieldSet = extraFields; + + // Override field values + fields['template'] = { + ...fields['template'], + filters: { + enabled: true, + model_type: modelType, + items: items.join(',') + } + }; + + fields['items'] = { + ...fields['items'], + value: items, + hidden: true + }; + + fields['plugin'] = { + ...fields['plugin'], + filters: { + active: true, + mixin: 'labels' + }, + onValueChange: (value: string, record?: any) => { + console.log('onValueChange:', value, record); + + if (record?.key && record?.key != pluginKey) { + setPluginKey(record.key); + } + } + }; + + return fields; + }, [extraFields, items, loadFields]); + + const labelModal = useCreateApiFormModal({ + url: apiUrl(ApiEndpoints.label_print), + title: t`Print Label`, + fields: labelFields, + timeout: (items.length + 1) * 1000, + onClose: () => { + setPluginKey(''); + }, + successMessage: t`Label printing completed successfully`, + onFormSuccess: (response: any) => { + if (!response.complete) { + // TODO: Periodically check for completion (requires server-side changes) + notifications.show({ + title: t`Error`, + message: t`The label could not be generated`, + color: 'red' + }); + return; + } + + if (response.output) { + // An output file was generated + const url = `${host}${response.output}`; + window.open(url, '_blank'); + } + } + }); + + const reportModal = useCreateApiFormModal({ + title: t`Print Report`, + url: apiUrl(ApiEndpoints.report_print), + timeout: (items.length + 1) * 1000, + fields: { + template: { + filters: { + enabled: true, + model_type: modelType, + items: items.join(',') + } + }, + items: { + hidden: true, + value: items + } + }, + successMessage: t`Report printing completed successfully`, + onFormSuccess: (response: any) => { + if (!response.complete) { + // TODO: Periodically check for completion (requires server-side changes) + notifications.show({ + title: t`Error`, + message: t`The report could not be generated`, + color: 'red' + }); + return; + } + + if (response.output) { + // An output file was generated + const url = `${host}${response.output}`; + window.open(url, '_blank'); + } + } + }); + + if (!modelType) { + return null; + } + + if (!enableLabels && !enableReports) { + return null; + } + + return ( + <> + {reportModal.modal} + {labelModal.modal} + } + disabled={!enabled} + actions={[ + { + name: t`Print Labels`, + icon: , + onClick: () => labelModal.open(), + hidden: !enableLabels + }, + { + name: t`Print Reports`, + icon: , + onClick: () => reportModal.open(), + hidden: !enableReports + } + ]} + /> + + ); +} diff --git a/src/frontend/src/components/buttons/SplitButton.tsx b/src/frontend/src/components/buttons/SplitButton.tsx index 8bb73882bdd3..ae497bb6dd0b 100644 --- a/src/frontend/src/components/buttons/SplitButton.tsx +++ b/src/frontend/src/components/buttons/SplitButton.tsx @@ -10,6 +10,7 @@ import { import { IconChevronDown } from '@tabler/icons-react'; import { useEffect, useMemo, useState } from 'react'; +import { identifierString } from '../../functions/conversion'; import { TablerIconType } from '../../functions/icons'; import * as classes from './SplitButton.css'; @@ -25,6 +26,7 @@ interface SplitButtonOption { interface SplitButtonProps { options: SplitButtonOption[]; defaultSelected: string; + name: string; selected?: string; setSelected?: (value: string) => void; loading?: boolean; @@ -34,6 +36,7 @@ export function SplitButton({ options, defaultSelected, selected, + name, setSelected, loading }: Readonly) { @@ -61,6 +64,7 @@ export function SplitButton({ disabled={loading ? false : currentOption?.disabled} className={classes.button} loading={loading} + aria-label={`split-button-${name}`} > {currentOption?.name} @@ -75,6 +79,7 @@ export function SplitButton({ color={theme.primaryColor} size={36} className={classes.icon} + aria-label={`split-button-${name}-action`} > @@ -88,6 +93,9 @@ export function SplitButton({ setCurrent(option.key); option.onClick(); }} + aria-label={`split-button-${name}-item-${identifierString( + option.key + )}`} disabled={option.disabled} leftSection={} > diff --git a/src/frontend/src/components/editors/TemplateEditor/PdfPreview/PdfPreview.tsx b/src/frontend/src/components/editors/TemplateEditor/PdfPreview/PdfPreview.tsx index a732935a93a0..c38e65f8a033 100644 --- a/src/frontend/src/components/editors/TemplateEditor/PdfPreview/PdfPreview.tsx +++ b/src/frontend/src/components/editors/TemplateEditor/PdfPreview/PdfPreview.tsx @@ -1,4 +1,4 @@ -import { Trans, t } from '@lingui/macro'; +import { Trans } from '@lingui/macro'; import { forwardRef, useImperativeHandle, useState } from 'react'; import { api } from '../../../../App'; @@ -13,54 +13,53 @@ export const PdfPreviewComponent: PreviewAreaComponent = forwardRef( code, previewItem, saveTemplate, - { uploadKey, uploadUrl, preview: { itemKey }, templateType } + { templateUrl, printingUrl, template } ) => { if (saveTemplate) { const formData = new FormData(); - formData.append(uploadKey, new File([code], 'template.html')); - const res = await api.patch(uploadUrl, formData); + const filename = + template.template?.split('/').pop() ?? 'template.html'; + + formData.append('template', new File([code], filename)); + + const res = await api.patch(templateUrl, formData); if (res.status !== 200) { throw new Error(res.data); } } - // ---- TODO: Fix this when implementing the new API ---- - let preview = await api.get( - uploadUrl + `print/?plugin=inventreelabel&${itemKey}=${previewItem}`, + let preview = await api.post( + printingUrl, + { + items: [previewItem], + template: template.pk + }, { - responseType: templateType === 'label' ? 'json' : 'blob', + responseType: 'json', timeout: 30000, validateStatus: () => true } ); - if (preview.status !== 200) { - if (templateType === 'report') { - let data; - try { - data = JSON.parse(await preview.data.text()); - } catch (err) { - throw new Error(t`Failed to parse error response from server.`); - } - - throw new Error(data.detail?.join(', ')); - } else if (preview.data?.non_field_errors) { + if (preview.status !== 200 && preview.status !== 201) { + if (preview.data?.non_field_errors) { throw new Error(preview.data?.non_field_errors.join(', ')); } throw new Error(preview.data); } - if (templateType === 'label') { - preview = await api.get(preview.data.file, { + if (preview?.data?.output) { + preview = await api.get(preview.data.output, { responseType: 'blob' }); } - // ---- + let pdf = new Blob([preview.data], { type: preview.headers['content-type'] }); + let srcUrl = URL.createObjectURL(pdf); setPdfUrl(srcUrl + '#view=fitH'); diff --git a/src/frontend/src/components/editors/TemplateEditor/TemplateEditor.tsx b/src/frontend/src/components/editors/TemplateEditor/TemplateEditor.tsx index 01bc7796450b..f1eac290a486 100644 --- a/src/frontend/src/components/editors/TemplateEditor/TemplateEditor.tsx +++ b/src/frontend/src/components/editors/TemplateEditor/TemplateEditor.tsx @@ -9,7 +9,7 @@ import { Tabs } from '@mantine/core'; import { openConfirmModal } from '@mantine/modals'; -import { showNotification } from '@mantine/notifications'; +import { notifications, showNotification } from '@mantine/notifications'; import { IconAlertTriangle, IconDeviceFloppy, @@ -70,25 +70,16 @@ export type PreviewArea = { component: PreviewAreaComponent; }; -export type TemplatePreviewProps = { - itemKey: string; - model: ModelType; - filters?: Record; -}; - -type TemplateEditorProps = { - downloadUrl: string; - uploadUrl: string; - uploadKey: string; - preview: TemplatePreviewProps; - templateType: 'label' | 'report'; +export type TemplateEditorProps = { + templateUrl: string; + printingUrl: string; editors: Editor[]; previewAreas: PreviewArea[]; template: TemplateI; }; export function TemplateEditor(props: Readonly) { - const { downloadUrl, editors, previewAreas, preview } = props; + const { templateUrl, editors, previewAreas, template } = props; const editorRef = useRef(); const previewRef = useRef(); @@ -131,13 +122,17 @@ export function TemplateEditor(props: Readonly) { }, []); useEffect(() => { - if (!downloadUrl) return; + if (!templateUrl) return; - api.get(downloadUrl).then((res) => { - codeRef.current = res.data; - loadCodeToEditor(res.data); + api.get(templateUrl).then((response: any) => { + if (response.data?.template) { + api.get(response.data.template).then((res) => { + codeRef.current = res.data; + loadCodeToEditor(res.data); + }); + } }); - }, [downloadUrl]); + }, [templateUrl]); useEffect(() => { if (codeRef.current === undefined) return; @@ -148,7 +143,7 @@ export function TemplateEditor(props: Readonly) { async (confirmed: boolean, saveTemplate: boolean = true) => { if (!confirmed) { openConfirmModal({ - title: t`Save & Reload preview?`, + title: t`Save & Reload Preview`, children: ( ) { ) .then(() => { setErrorOverlay(null); + + notifications.hide('template-preview'); + showNotification({ title: t`Preview updated`, message: t`The preview has been updated successfully.`, - color: 'green' + color: 'green', + id: 'template-preview' }); }) .catch((error) => { @@ -204,18 +203,25 @@ export function TemplateEditor(props: Readonly) { ); const previewApiUrl = useMemo( - () => ModelInformationDict[preview.model].api_endpoint, - [preview.model] + () => + ModelInformationDict[template.model_type ?? ModelType.stockitem] + .api_endpoint, + [template] ); + const templateFilters: Record = useMemo(() => { + // TODO: Extract custom filters from template + return {}; + }, [template]); + useEffect(() => { api - .get(apiUrl(previewApiUrl), { params: { limit: 1, ...preview.filters } }) + .get(apiUrl(previewApiUrl), { params: { limit: 1, ...templateFilters } }) .then((res) => { if (res.data.results.length === 0) return; setPreviewItem(res.data.results[0].pk); }); - }, [previewApiUrl, preview.filters]); + }, [previewApiUrl, templateFilters]); return ( @@ -249,6 +255,7 @@ export function TemplateEditor(props: Readonly) { ) { }, { key: 'preview_save', - name: t`Save & Reload preview`, + name: t`Save & Reload Preview`, tooltip: t`Save the current template and reload the preview`, icon: IconDeviceFloppy, onClick: () => updatePreview(hasSaveConfirmed), @@ -319,10 +326,10 @@ export function TemplateEditor(props: Readonly) { field_type: 'related field', api_url: apiUrl(previewApiUrl), description: '', - label: t`Select` + ' ' + preview.model + ' ' + t`to preview`, - model: preview.model, + label: t`Select instance to preview`, + model: template.model_type, value: previewItem, - filters: preview.filters, + filters: templateFilters, onValueChange: (value) => setPreviewItem(value) }} /> diff --git a/src/frontend/src/components/forms/fields/ApiFormField.tsx b/src/frontend/src/components/forms/fields/ApiFormField.tsx index 90446eef3b17..be86befa10bd 100644 --- a/src/frontend/src/components/forms/fields/ApiFormField.tsx +++ b/src/frontend/src/components/forms/fields/ApiFormField.tsx @@ -40,6 +40,7 @@ export type ApiFormAdjustFilterType = { * @param icon : An icon to display next to the field * @param field_type : The type of field to render * @param api_url : The API endpoint to fetch data from (for related fields) + * @param pk_field : The primary key field for the related field (default = "pk") * @param model : The model to use for related fields * @param filters : Optional API filters to apply to related fields * @param required : Whether the field is required @@ -74,6 +75,7 @@ export type ApiFormFieldType = { | 'nested object' | 'table'; api_url?: string; + pk_field?: string; model?: ModelType; modelRenderer?: (instance: any) => ReactNode; filters?: any; @@ -190,6 +192,7 @@ export function ApiFormField({ {...reducedDefinition} ref={field.ref} id={fieldId} + aria-label={`text-field-${field.name}`} type={definition.field_type} value={value || ''} error={error?.message} @@ -208,6 +211,7 @@ export function ApiFormField({ {...reducedDefinition} ref={ref} id={fieldId} + aria-label={`boolean-field-${field.name}`} radius="lg" size="sm" checked={isTrue(value)} @@ -228,6 +232,7 @@ export function ApiFormField({ radius="sm" ref={field.ref} id={fieldId} + aria-label={`number-field-${field.name}`} value={numericalValue} error={error?.message} decimalScale={definition.field_type == 'integer' ? 0 : 10} diff --git a/src/frontend/src/components/forms/fields/ChoiceField.tsx b/src/frontend/src/components/forms/fields/ChoiceField.tsx index 5b7757645dc0..2f47c727186e 100644 --- a/src/frontend/src/components/forms/fields/ChoiceField.tsx +++ b/src/frontend/src/components/forms/fields/ChoiceField.tsx @@ -51,6 +51,7 @@ export function ChoiceField({ return ( + {definition.headers?.map((header) => { - return ; + return {header}; })} diff --git a/src/frontend/src/components/items/ActionDropdown.tsx b/src/frontend/src/components/items/ActionDropdown.tsx index 59045bb92823..73777a9c56db 100644 --- a/src/frontend/src/components/items/ActionDropdown.tsx +++ b/src/frontend/src/components/items/ActionDropdown.tsx @@ -14,9 +14,9 @@ import { IconTrash, IconUnlink } from '@tabler/icons-react'; -import { color } from '@uiw/react-codemirror'; import { ReactNode, useMemo } from 'react'; +import { identifierString } from '../../functions/conversion'; import { InvenTreeIcon } from '../../functions/icons'; import { notYetImplemented } from '../../functions/notifications'; @@ -42,19 +42,24 @@ export function ActionDropdown({ disabled = false }: { icon: ReactNode; - tooltip?: string; + tooltip: string; actions: ActionDropdownItem[]; disabled?: boolean; }) { const hasActions = useMemo(() => { return actions.some((action) => !action.hidden); }, [actions]); + const indicatorProps = useMemo(() => { return actions.find((action) => action.indicator); }, [actions]); + const menuName: string = useMemo(() => { + return identifierString(`action-menu-${tooltip}`); + }, [tooltip]); + return hasActions ? ( - + - {actions.map((action) => - action.hidden ? null : ( + {actions.map((action) => { + const id: string = identifierString(`${menuName}-${action.name}`); + return action.hidden ? null : ( - + - ) - )} + ); + })} ) : null; @@ -108,7 +116,6 @@ export function BarcodeActionDropdown({ }) { return ( } actions={actions} diff --git a/src/frontend/src/components/render/Instance.tsx b/src/frontend/src/components/render/Instance.tsx index 905882ccfe0b..1844fe503058 100644 --- a/src/frontend/src/components/render/Instance.tsx +++ b/src/frontend/src/components/render/Instance.tsx @@ -26,6 +26,8 @@ import { RenderPartParameterTemplate, RenderPartTestTemplate } from './Part'; +import { RenderPlugin } from './Plugin'; +import { RenderLabelTemplate, RenderReportTemplate } from './Report'; import { RenderStockItem, RenderStockLocation, @@ -72,7 +74,10 @@ const RendererLookup: EnumDictionary< [ModelType.stockitem]: RenderStockItem, [ModelType.stockhistory]: RenderStockItem, [ModelType.supplierpart]: RenderSupplierPart, - [ModelType.user]: RenderUser + [ModelType.user]: RenderUser, + [ModelType.reporttemplate]: RenderReportTemplate, + [ModelType.labeltemplate]: RenderLabelTemplate, + [ModelType.pluginconfig]: RenderPlugin }; export type RenderInstanceProps = { diff --git a/src/frontend/src/components/render/ModelType.tsx b/src/frontend/src/components/render/ModelType.tsx index e4c9848f7e95..27407f3e4a05 100644 --- a/src/frontend/src/components/render/ModelType.tsx +++ b/src/frontend/src/components/render/ModelType.tsx @@ -195,6 +195,27 @@ export const ModelInformationDict: ModelDict = { url_overview: '/user', url_detail: '/user/:pk/', api_endpoint: ApiEndpoints.user_list + }, + labeltemplate: { + label: t`Label Template`, + label_multiple: t`Label Templates`, + url_overview: '/labeltemplate', + url_detail: '/labeltemplate/:pk/', + api_endpoint: ApiEndpoints.label_list + }, + reporttemplate: { + label: t`Report Template`, + label_multiple: t`Report Templates`, + url_overview: '/reporttemplate', + url_detail: '/reporttemplate/:pk/', + api_endpoint: ApiEndpoints.report_list + }, + pluginconfig: { + label: t`Plugin Configuration`, + label_multiple: t`Plugin Configurations`, + url_overview: '/pluginconfig', + url_detail: '/pluginconfig/:pk/', + api_endpoint: ApiEndpoints.plugin_list } }; diff --git a/src/frontend/src/components/render/Plugin.tsx b/src/frontend/src/components/render/Plugin.tsx new file mode 100644 index 000000000000..6ba246ef4de0 --- /dev/null +++ b/src/frontend/src/components/render/Plugin.tsx @@ -0,0 +1,21 @@ +import { t } from '@lingui/macro'; +import { Badge } from '@mantine/core'; +import { ReactNode } from 'react'; + +import { RenderInlineModel } from './Instance'; + +export function RenderPlugin({ + instance +}: { + instance: Readonly; +}): ReactNode { + return ( + {t`Inactive`} + } + /> + ); +} diff --git a/src/frontend/src/components/render/Report.tsx b/src/frontend/src/components/render/Report.tsx new file mode 100644 index 000000000000..f87fa9956f1c --- /dev/null +++ b/src/frontend/src/components/render/Report.tsx @@ -0,0 +1,29 @@ +import { ReactNode } from 'react'; + +import { RenderInlineModel } from './Instance'; + +export function RenderReportTemplate({ + instance +}: { + instance: any; +}): ReactNode { + return ( + + ); +} + +export function RenderLabelTemplate({ + instance +}: { + instance: any; +}): ReactNode { + return ( + + ); +} diff --git a/src/frontend/src/components/render/StatusRenderer.tsx b/src/frontend/src/components/render/StatusRenderer.tsx index 5c284533dcd0..2cfd2b2f2c09 100644 --- a/src/frontend/src/components/render/StatusRenderer.tsx +++ b/src/frontend/src/components/render/StatusRenderer.tsx @@ -80,7 +80,7 @@ export const StatusRenderer = ({ const statusCodes = statusCodeList[type]; if (statusCodes === undefined) { - console.log('StatusRenderer: statusCodes is undefined'); + console.warn('StatusRenderer: statusCodes is undefined'); return null; } diff --git a/src/frontend/src/enums/ApiEndpoints.tsx b/src/frontend/src/enums/ApiEndpoints.tsx index 73272cf08bbd..436f3e4697f7 100644 --- a/src/frontend/src/enums/ApiEndpoints.tsx +++ b/src/frontend/src/enums/ApiEndpoints.tsx @@ -127,8 +127,14 @@ export enum ApiEndpoints { return_order_attachment_list = 'order/ro/attachment/', // Template API endpoints - label_list = 'label/:variant/', - report_list = 'report/:variant/', + label_list = 'label/template/', + label_print = 'label/print/', + label_output = 'label/output/', + report_list = 'report/template/', + report_print = 'report/print/', + report_output = 'report/output/', + report_snippet = 'report/snippet/', + report_asset = 'report/asset/', // Plugin API endpoints plugin_list = 'plugins/', diff --git a/src/frontend/src/enums/ModelType.tsx b/src/frontend/src/enums/ModelType.tsx index 8f0574ef915a..136eded78c4e 100644 --- a/src/frontend/src/enums/ModelType.tsx +++ b/src/frontend/src/enums/ModelType.tsx @@ -24,5 +24,8 @@ export enum ModelType { address = 'address', contact = 'contact', owner = 'owner', - user = 'user' + user = 'user', + reporttemplate = 'reporttemplate', + labeltemplate = 'labeltemplate', + pluginconfig = 'pluginconfig' } diff --git a/src/frontend/src/functions/conversion.tsx b/src/frontend/src/functions/conversion.tsx index afc4e536d290..1eed5db9e77e 100644 --- a/src/frontend/src/functions/conversion.tsx +++ b/src/frontend/src/functions/conversion.tsx @@ -32,3 +32,8 @@ export function resolveItem(obj: any, path: string): any { let properties = path.split('.'); return properties.reduce((prev, curr) => prev?.[curr], obj); } + +export function identifierString(value: string): string { + // Convert an input string e.g. "Hello World" into a string that can be used as an identifier, e.g. "hello-world" + return value.toLowerCase().replace(/[^a-z0-9]/g, '-'); +} diff --git a/src/frontend/src/hooks/UseInstance.tsx b/src/frontend/src/hooks/UseInstance.tsx index c48cc8d07ead..88298cc1d004 100644 --- a/src/frontend/src/hooks/UseInstance.tsx +++ b/src/frontend/src/hooks/UseInstance.tsx @@ -27,7 +27,7 @@ export function useInstance({ updateInterval }: { endpoint: ApiEndpoints; - pk?: string | undefined; + pk?: string | number | undefined; hasPrimaryKey?: boolean; params?: any; pathParams?: PathParams; @@ -43,7 +43,12 @@ export function useInstance({ queryKey: ['instance', endpoint, pk, params, pathParams], queryFn: async () => { if (hasPrimaryKey) { - if (pk == null || pk == undefined || pk.length == 0 || pk == '-1') { + if ( + pk == null || + pk == undefined || + pk.toString().length == 0 || + pk == '-1' + ) { setInstance(defaultValue); return defaultValue; } diff --git a/src/frontend/src/hooks/UseTable.tsx b/src/frontend/src/hooks/UseTable.tsx index 48d583ccf50e..ff9362291f70 100644 --- a/src/frontend/src/hooks/UseTable.tsx +++ b/src/frontend/src/hooks/UseTable.tsx @@ -24,6 +24,7 @@ export type TableState = { expandedRecords: any[]; setExpandedRecords: (records: any[]) => void; selectedRecords: any[]; + selectedIds: number[]; hasSelectedRecords: boolean; setSelectedRecords: (records: any[]) => void; clearSelectedRecords: () => void; @@ -77,6 +78,12 @@ export function useTable(tableName: string): TableState { // Array of selected records const [selectedRecords, setSelectedRecords] = useState([]); + // Array of selected primary key values + const selectedIds = useMemo( + () => selectedRecords.map((r) => r.pk ?? r.id), + [selectedRecords] + ); + const clearSelectedRecords = useCallback(() => { setSelectedRecords([]); }, []); @@ -135,6 +142,7 @@ export function useTable(tableName: string): TableState { expandedRecords, setExpandedRecords, selectedRecords, + selectedIds, setSelectedRecords, clearSelectedRecords, hasSelectedRecords, diff --git a/src/frontend/src/pages/Index/Playground.tsx b/src/frontend/src/pages/Index/Playground.tsx index 902858b5d3d7..ec8e0ba7f8e8 100644 --- a/src/frontend/src/pages/Index/Playground.tsx +++ b/src/frontend/src/pages/Index/Playground.tsx @@ -202,7 +202,6 @@ function SpotlighPlayground() { onClick: () => console.log('Secret') } ]); - console.log('registed'); firstSpotlight.open(); }} > diff --git a/src/frontend/src/pages/Index/Scan.tsx b/src/frontend/src/pages/Index/Scan.tsx index 889eebd18bf9..f05de24f6cd2 100644 --- a/src/frontend/src/pages/Index/Scan.tsx +++ b/src/frontend/src/pages/Index/Scan.tsx @@ -684,7 +684,6 @@ function InputImageBarcode({ action }: Readonly) { useEffect(() => { if (cameraValue === null) return; if (cameraValue === camId?.id) { - console.log('matching value and id'); return; } diff --git a/src/frontend/src/pages/Index/Settings/AdminCenter/Index.tsx b/src/frontend/src/pages/Index/Settings/AdminCenter/Index.tsx index cca88e567bcc..a5d16d530a27 100644 --- a/src/frontend/src/pages/Index/Settings/AdminCenter/Index.tsx +++ b/src/frontend/src/pages/Index/Settings/AdminCenter/Index.tsx @@ -9,9 +9,10 @@ import { IconListDetails, IconPackages, IconPlugConnected, + IconReport, IconScale, IconSitemap, - IconTemplate, + IconTags, IconUsersGroup } from '@tabler/icons-react'; import { lazy, useMemo } from 'react'; @@ -22,6 +23,12 @@ import { SettingsHeader } from '../../../../components/nav/SettingsHeader'; import { GlobalSettingList } from '../../../../components/settings/SettingList'; import { Loadable } from '../../../../functions/loading'; +const ReportTemplatePanel = Loadable( + lazy(() => import('./ReportTemplatePanel')) +); + +const LabelTemplatePanel = Loadable(lazy(() => import('./LabelTemplatePanel'))); + const UserManagementPanel = Loadable( lazy(() => import('./UserManagementPanel')) ); @@ -66,10 +73,6 @@ const CurrencyTable = Loadable( lazy(() => import('../../../../tables/settings/CurrencyTable')) ); -const TemplateManagementPanel = Loadable( - lazy(() => import('./TemplateManagementPanel')) -); - export default function AdminCenter() { const adminCenterPanels: PanelType[] = useMemo(() => { return [ @@ -127,18 +130,24 @@ export default function AdminCenter() { icon: , content: }, + { + name: 'labels', + label: t`Label Templates`, + icon: , + content: + }, + { + name: 'reports', + label: t`Report Templates`, + icon: , + content: + }, { name: 'location-types', label: t`Location types`, icon: , content: }, - { - name: 'templates', - label: t`Templates`, - icon: , - content: - }, { name: 'plugin', label: t`Plugins`, diff --git a/src/frontend/src/pages/Index/Settings/AdminCenter/LabelTemplatePanel.tsx b/src/frontend/src/pages/Index/Settings/AdminCenter/LabelTemplatePanel.tsx new file mode 100644 index 000000000000..2e6e25815958 --- /dev/null +++ b/src/frontend/src/pages/Index/Settings/AdminCenter/LabelTemplatePanel.tsx @@ -0,0 +1,17 @@ +import { ApiEndpoints } from '../../../../enums/ApiEndpoints'; +import { TemplateTable } from '../../../../tables/settings/TemplateTable'; + +export default function LabelTemplatePanel() { + return ( + + ); +} diff --git a/src/frontend/src/pages/Index/Settings/AdminCenter/ReportTemplatePanel.tsx b/src/frontend/src/pages/Index/Settings/AdminCenter/ReportTemplatePanel.tsx new file mode 100644 index 000000000000..7eab843ddfc3 --- /dev/null +++ b/src/frontend/src/pages/Index/Settings/AdminCenter/ReportTemplatePanel.tsx @@ -0,0 +1,17 @@ +import { ApiEndpoints } from '../../../../enums/ApiEndpoints'; +import { TemplateTable } from '../../../../tables/settings/TemplateTable'; + +export default function ReportTemplateTable() { + return ( + + ); +} diff --git a/src/frontend/src/pages/Index/Settings/AdminCenter/TemplateManagementPanel.tsx b/src/frontend/src/pages/Index/Settings/AdminCenter/TemplateManagementPanel.tsx deleted file mode 100644 index 833caba5b50a..000000000000 --- a/src/frontend/src/pages/Index/Settings/AdminCenter/TemplateManagementPanel.tsx +++ /dev/null @@ -1,211 +0,0 @@ -import { t } from '@lingui/macro'; -import { Stack } from '@mantine/core'; -import { useMemo } from 'react'; - -import { TemplatePreviewProps } from '../../../../components/editors/TemplateEditor/TemplateEditor'; -import { ApiFormFieldSet } from '../../../../components/forms/fields/ApiFormField'; -import { PanelGroup } from '../../../../components/nav/PanelGroup'; -import { - defaultLabelTemplate, - defaultReportTemplate -} from '../../../../defaults/templates'; -import { ApiEndpoints } from '../../../../enums/ApiEndpoints'; -import { ModelType } from '../../../../enums/ModelType'; -import { InvenTreeIcon, InvenTreeIconType } from '../../../../functions/icons'; -import { TemplateTable } from '../../../../tables/settings/TemplateTable'; - -type TemplateType = { - type: 'label' | 'report'; - name: string; - singularName: string; - apiEndpoints: ApiEndpoints; - templateKey: string; - additionalFormFields?: ApiFormFieldSet; - defaultTemplate: string; - variants: { - name: string; - key: string; - icon: InvenTreeIconType; - preview: TemplatePreviewProps; - }[]; -}; - -export default function TemplateManagementPanel() { - const templateTypes = useMemo(() => { - const templateTypes: TemplateType[] = [ - { - type: 'label', - name: t`Labels`, - singularName: t`Label`, - apiEndpoints: ApiEndpoints.label_list, - templateKey: 'label', - additionalFormFields: { - width: {}, - height: {} - }, - defaultTemplate: defaultLabelTemplate, - variants: [ - { - name: t`Part`, - key: 'part', - icon: 'part', - preview: { - itemKey: 'part', - model: ModelType.part - } - }, - { - name: t`Location`, - key: 'location', - icon: 'location', - preview: { - itemKey: 'location', - model: ModelType.stocklocation - } - }, - { - name: t`Stock Item`, - key: 'stock', - icon: 'stock', - preview: { - itemKey: 'item', - model: ModelType.stockitem - } - }, - { - name: t`Build Line`, - key: 'buildline', - icon: 'builds', - preview: { - itemKey: 'line', - model: ModelType.buildline - } - } - ] - }, - { - type: 'report', - name: t`Reports`, - singularName: t`Report`, - apiEndpoints: ApiEndpoints.report_list, - templateKey: 'template', - additionalFormFields: { - page_size: {}, - landscape: {} - }, - defaultTemplate: defaultReportTemplate, - variants: [ - { - name: t`Purchase Order`, - key: 'po', - icon: 'purchase_orders', - preview: { - itemKey: 'order', - model: ModelType.purchaseorder - } - }, - { - name: t`Sales Order`, - key: 'so', - icon: 'sales_orders', - preview: { - itemKey: 'order', - model: ModelType.salesorder - } - }, - { - name: t`Return Order`, - key: 'ro', - icon: 'return_orders', - preview: { - itemKey: 'order', - model: ModelType.returnorder - } - }, - { - name: t`Build`, - key: 'build', - icon: 'builds', - preview: { - itemKey: 'build', - model: ModelType.build - } - }, - { - name: t`Bill of Materials`, - key: 'bom', - icon: 'bom', - preview: { - itemKey: 'part', - model: ModelType.part, - filters: { assembly: true } - } - }, - { - name: t`Tests`, - key: 'test', - icon: 'test_templates', - preview: { - itemKey: 'item', - model: ModelType.stockitem - } - }, - { - name: t`Stock Location`, - key: 'slr', - icon: 'default_location', - preview: { - itemKey: 'location', - model: ModelType.stocklocation - } - } - ] - } - ]; - - return templateTypes; - }, []); - - const panels = useMemo(() => { - return templateTypes.flatMap((templateType) => { - return [ - // Add panel headline - { name: templateType.type, label: templateType.name, disabled: true }, - - // Add panel for each variant - ...templateType.variants.map((variant) => { - return { - name: variant.key, - label: variant.name, - content: ( - - ), - icon: , - showHeadline: false - }; - }) - ]; - }); - }, [templateTypes]); - - return ( - - - - ); -} diff --git a/src/frontend/src/pages/build/BuildDetail.tsx b/src/frontend/src/pages/build/BuildDetail.tsx index 58c9871325e3..62e9178222f4 100644 --- a/src/frontend/src/pages/build/BuildDetail.tsx +++ b/src/frontend/src/pages/build/BuildDetail.tsx @@ -4,13 +4,11 @@ import { IconClipboardCheck, IconClipboardList, IconDots, - IconFileTypePdf, IconInfoCircle, IconList, IconListCheck, IconNotes, IconPaperclip, - IconPrinter, IconQrcode, IconSitemap } from '@tabler/icons-react'; @@ -18,6 +16,7 @@ import { useMemo } from 'react'; import { useParams } from 'react-router-dom'; import AdminButton from '../../components/buttons/AdminButton'; +import { PrintingActions } from '../../components/buttons/PrintingActions'; import { DetailsField, DetailsTable } from '../../components/details/Details'; import { DetailsImage } from '../../components/details/DetailsImage'; import { ItemDetailsGrid } from '../../components/details/ItemDetails'; @@ -358,7 +357,6 @@ export default function BuildDetail() { return [ , } actions={[ @@ -371,20 +369,12 @@ export default function BuildDetail() { }) ]} />, - } - actions={[ - { - icon: , - name: t`Report`, - tooltip: t`Print build report` - } - ]} + , } actions={[ diff --git a/src/frontend/src/pages/company/CompanyDetail.tsx b/src/frontend/src/pages/company/CompanyDetail.tsx index bdfe135f270b..57137cfe29fb 100644 --- a/src/frontend/src/pages/company/CompanyDetail.tsx +++ b/src/frontend/src/pages/company/CompanyDetail.tsx @@ -289,7 +289,6 @@ export default function CompanyDetail(props: Readonly) { return [ , } actions={[ diff --git a/src/frontend/src/pages/company/ManufacturerPartDetail.tsx b/src/frontend/src/pages/company/ManufacturerPartDetail.tsx index 708a744f704c..8865d98b7a1d 100644 --- a/src/frontend/src/pages/company/ManufacturerPartDetail.tsx +++ b/src/frontend/src/pages/company/ManufacturerPartDetail.tsx @@ -210,7 +210,6 @@ export default function ManufacturerPartDetail() { pk={manufacturerPart.pk} />, } actions={[ diff --git a/src/frontend/src/pages/company/SupplierPartDetail.tsx b/src/frontend/src/pages/company/SupplierPartDetail.tsx index 28a08425d4e3..bef8168c48f6 100644 --- a/src/frontend/src/pages/company/SupplierPartDetail.tsx +++ b/src/frontend/src/pages/company/SupplierPartDetail.tsx @@ -246,7 +246,6 @@ export default function SupplierPartDetail() { return [ , } actions={[ diff --git a/src/frontend/src/pages/part/CategoryDetail.tsx b/src/frontend/src/pages/part/CategoryDetail.tsx index 6d03903d4a5d..9ac93e71edb1 100644 --- a/src/frontend/src/pages/part/CategoryDetail.tsx +++ b/src/frontend/src/pages/part/CategoryDetail.tsx @@ -204,7 +204,6 @@ export default function CategoryDetail({}: {}) { return [ , } actions={[ diff --git a/src/frontend/src/pages/part/PartDetail.tsx b/src/frontend/src/pages/part/PartDetail.tsx index 672c4c15aa2a..e54ee8103558 100644 --- a/src/frontend/src/pages/part/PartDetail.tsx +++ b/src/frontend/src/pages/part/PartDetail.tsx @@ -761,7 +761,6 @@ export default function PartDetail() { key="action_dropdown" />, } actions={[ @@ -790,7 +789,6 @@ export default function PartDetail() { ]} />, } actions={[ diff --git a/src/frontend/src/pages/purchasing/PurchaseOrderDetail.tsx b/src/frontend/src/pages/purchasing/PurchaseOrderDetail.tsx index d90e877574ac..bb8f097da77d 100644 --- a/src/frontend/src/pages/purchasing/PurchaseOrderDetail.tsx +++ b/src/frontend/src/pages/purchasing/PurchaseOrderDetail.tsx @@ -12,6 +12,7 @@ import { ReactNode, useMemo } from 'react'; import { useParams } from 'react-router-dom'; import AdminButton from '../../components/buttons/AdminButton'; +import { PrintingActions } from '../../components/buttons/PrintingActions'; import { DetailsField, DetailsTable } from '../../components/details/Details'; import { DetailsImage } from '../../components/details/DetailsImage'; import { ItemDetailsGrid } from '../../components/details/ItemDetails'; @@ -313,8 +314,12 @@ export default function PurchaseOrderDetail() { }) ]} />, + , } actions={[ diff --git a/src/frontend/src/pages/sales/ReturnOrderDetail.tsx b/src/frontend/src/pages/sales/ReturnOrderDetail.tsx index 94e405098f0f..3cfd4f19a807 100644 --- a/src/frontend/src/pages/sales/ReturnOrderDetail.tsx +++ b/src/frontend/src/pages/sales/ReturnOrderDetail.tsx @@ -11,6 +11,7 @@ import { ReactNode, useMemo } from 'react'; import { useParams } from 'react-router-dom'; import AdminButton from '../../components/buttons/AdminButton'; +import { PrintingActions } from '../../components/buttons/PrintingActions'; import { DetailsField, DetailsTable } from '../../components/details/Details'; import { DetailsImage } from '../../components/details/DetailsImage'; import { ItemDetailsGrid } from '../../components/details/ItemDetails'; @@ -287,8 +288,12 @@ export default function ReturnOrderDetail() { const orderActions = useMemo(() => { return [ , + , } actions={[ diff --git a/src/frontend/src/pages/sales/SalesOrderDetail.tsx b/src/frontend/src/pages/sales/SalesOrderDetail.tsx index 4f540fca141d..eceba7274bec 100644 --- a/src/frontend/src/pages/sales/SalesOrderDetail.tsx +++ b/src/frontend/src/pages/sales/SalesOrderDetail.tsx @@ -14,6 +14,7 @@ import { ReactNode, useMemo } from 'react'; import { useParams } from 'react-router-dom'; import AdminButton from '../../components/buttons/AdminButton'; +import { PrintingActions } from '../../components/buttons/PrintingActions'; import { DetailsField, DetailsTable } from '../../components/details/Details'; import { DetailsImage } from '../../components/details/DetailsImage'; import { ItemDetailsGrid } from '../../components/details/ItemDetails'; @@ -299,8 +300,12 @@ export default function SalesOrderDetail() { const soActions = useMemo(() => { return [ , + , } actions={[ diff --git a/src/frontend/src/pages/stock/LocationDetail.tsx b/src/frontend/src/pages/stock/LocationDetail.tsx index a7db455cafe3..e3c83dea6d23 100644 --- a/src/frontend/src/pages/stock/LocationDetail.tsx +++ b/src/frontend/src/pages/stock/LocationDetail.tsx @@ -11,6 +11,7 @@ import { useNavigate, useParams } from 'react-router-dom'; import { ActionButton } from '../../components/buttons/ActionButton'; import AdminButton from '../../components/buttons/AdminButton'; +import { PrintingActions } from '../../components/buttons/PrintingActions'; import { DetailsField, DetailsTable } from '../../components/details/Details'; import { ItemDetailsGrid } from '../../components/details/ItemDetails'; import { @@ -290,24 +291,14 @@ export default function Stock() { } ]} />, - } - actions={[ - { - name: 'Print Label', - icon: '', - tooltip: 'Print label' - }, - { - name: 'Print Location Report', - icon: '', - tooltip: 'Print Report' - } - ]} + , } actions={[ { @@ -329,7 +320,6 @@ export default function Stock() { ]} />, } actions={[ diff --git a/src/frontend/src/pages/stock/StockDetail.tsx b/src/frontend/src/pages/stock/StockDetail.tsx index 205f419abada..8c9669e17ba1 100644 --- a/src/frontend/src/pages/stock/StockDetail.tsx +++ b/src/frontend/src/pages/stock/StockDetail.tsx @@ -16,6 +16,7 @@ import { ReactNode, useMemo, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import AdminButton from '../../components/buttons/AdminButton'; +import { PrintingActions } from '../../components/buttons/PrintingActions'; import { DetailsField, DetailsTable } from '../../components/details/Details'; import DetailsBadge from '../../components/details/DetailsBadge'; import { DetailsImage } from '../../components/details/DetailsImage'; @@ -429,8 +430,13 @@ export default function StockDetail() { }) ]} />, + , } actions={[ @@ -473,7 +479,6 @@ export default function StockDetail() { ]} />, } actions={[ diff --git a/src/frontend/src/tables/ColumnRenderers.tsx b/src/frontend/src/tables/ColumnRenderers.tsx index d4f59d9a0954..b3076954c811 100644 --- a/src/frontend/src/tables/ColumnRenderers.tsx +++ b/src/frontend/src/tables/ColumnRenderers.tsx @@ -2,7 +2,7 @@ * Common rendering functions for table column data. */ import { t } from '@lingui/macro'; -import { Anchor, Text } from '@mantine/core'; +import { Anchor, Skeleton, Text } from '@mantine/core'; import { YesNoButton } from '../components/buttons/YesNoButton'; import { Thumbnail } from '../components/images/Thumbnail'; @@ -18,11 +18,13 @@ import { ProjectCodeHoverCard } from './TableHoverCard'; // Render a Part instance within a table export function PartColumn(part: any, full_name?: boolean) { - return ( + return part ? ( + ) : ( + ); } @@ -226,8 +228,8 @@ export function CurrencyColumn({ sortable: sortable ?? true, render: (record: any) => { let currency_key = currency_accessor ?? `${accessor}_currency`; - return formatCurrency(record[accessor], { - currency: currency ?? record[currency_key] + return formatCurrency(resolveItem(record, accessor), { + currency: currency ?? resolveItem(record, currency_key) }); } }; diff --git a/src/frontend/src/tables/DownloadAction.tsx b/src/frontend/src/tables/DownloadAction.tsx index 34abdfff7fc1..1de56b9803f7 100644 --- a/src/frontend/src/tables/DownloadAction.tsx +++ b/src/frontend/src/tables/DownloadAction.tsx @@ -1,6 +1,17 @@ import { t } from '@lingui/macro'; import { ActionIcon, Menu, Tooltip } from '@mantine/core'; -import { IconDownload } from '@tabler/icons-react'; +import { + IconDownload, + IconFileSpreadsheet, + IconFileText, + IconFileTypeCsv +} from '@tabler/icons-react'; +import { useMemo } from 'react'; + +import { + ActionDropdown, + ActionDropdownItem +} from '../components/items/ActionDropdown'; export function DownloadAction({ downloadCallback @@ -8,34 +19,27 @@ export function DownloadAction({ downloadCallback: (fileFormat: string) => void; }) { const formatOptions = [ - { value: 'csv', label: t`CSV` }, - { value: 'tsv', label: t`TSV` }, - { value: 'xlsx', label: t`Excel` } + { value: 'csv', label: t`CSV`, icon: }, + { value: 'tsv', label: t`TSV`, icon: }, + { value: 'xls', label: t`Excel (.xls)`, icon: }, + { value: 'xlsx', label: t`Excel (.xlsx)`, icon: } ]; + const actions: ActionDropdownItem[] = useMemo(() => { + return formatOptions.map((format) => ({ + name: format.label, + icon: format.icon, + onClick: () => downloadCallback(format.value) + })); + }, [formatOptions, downloadCallback]); + return ( <> - - - - - - - - - - {formatOptions.map((format) => ( - { - downloadCallback(format.value); - }} - > - {format.label} - - ))} - - + } + actions={actions} + /> ); } diff --git a/src/frontend/src/tables/FilterSelectDrawer.tsx b/src/frontend/src/tables/FilterSelectDrawer.tsx index 841c420fb5c8..c159a6c59a42 100644 --- a/src/frontend/src/tables/FilterSelectDrawer.tsx +++ b/src/frontend/src/tables/FilterSelectDrawer.tsx @@ -12,7 +12,7 @@ import { Text, Tooltip } from '@mantine/core'; -import { forwardRef, useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; import { StylishText } from '../components/items/StylishText'; import { TableState } from '../hooks/UseTable'; @@ -63,18 +63,6 @@ interface FilterProps extends React.ComponentPropsWithoutRef<'div'> { description?: string; } -/* - * Custom component for the filter select - */ -const FilterSelectItem = forwardRef( - ({ label, description, ...others }, ref) => ( -
- {label} - {description} -
- ) -); - function FilterAddGroup({ tableState, availableFilters @@ -144,7 +132,6 @@ function FilterAddGroup({
{header}