[docs] Report discovery (#12449)

* Adds decorator to mark an attribute for report context discovery

* Update context variables in docs

* Include fields captured against each model type

* Expose more properties

* Image URL tags

* Add more attributes

* Rearrange docs

* Simplify docs

* Enforce type hinting for reportable properties

* Expose more properties for the Order model

* Auto-discover related / linked models

* Remove extra text

* Collapsible blocks

* Reduce boilerplate

* Remove cruft

* Enhance documentation for filename generation

* Cleanup
This commit is contained in:
Oliver
2026-07-23 21:43:55 +10:00
committed by GitHub
parent 346d7e0a70
commit 65efa51524
13 changed files with 397 additions and 263 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ The barcode is tested as follows, in decreasing order of priority:
InvenTree comes with a few builtin supplier plugins, which handle their respective barcode formats.
Scanning a supplier barcode for a supplied part will link to the corresponding supplier part if the [SKU](../report/context_variables.md#supplierpart) from the barcode could be matched.
Scanning a supplier barcode for a supplied part will link to the corresponding supplier part if the [SKU](../report/model_context.md#supplier-part) from the barcode could be matched.
The following suppliers (and barcode formats) are currently supported:
+20 -214
View File
@@ -1,9 +1,9 @@
---
title: Context Variables
title: Report Context
---
## Context Variables
## Report Context Variables
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.
@@ -13,9 +13,6 @@ In addition to the model-specific context variables, the following global contex
{{ report_context("base", "global") }}
::: report.models.ReportTemplateBase.base_context
options:
show_source: True
### Report Context
@@ -23,7 +20,7 @@ In addition to the [global context](#global-context), all *report* templates hav
{{ report_context("base", "report") }}
When using the `merge` context variable, the selected items are available in the `instances` list. {{ templatefile("report/inventree_stock_report_merge.html") }} shows a complete example. To access individual item attributes, you can either loop through the `instances` or access them by index like `instance.0.name`.
When using the `merge` context variable, the selected items are available in the `instances` list. To access individual item attributes, you can either loop through the `instances` or access them by index like `instance.0.name`.
Below is an example template that generates a single report for some selected parts. Each part occupies a row in the table
@@ -87,9 +84,8 @@ When printing a report or label against a Company instance, the following contex
{{ report_context("models", "company") }}
::: company.models.Company.report_context
options:
show_source: True
For the fields and properties available on the underlying `Company` instance, refer to the [Model Context](model_context.md#company) page.
### Build Order
@@ -97,9 +93,8 @@ When printing a report or label against a [Build Order](../manufacturing/build.m
{{ report_context("models", "build") }}
::: build.models.Build.report_context
options:
show_source: True
For the fields and properties available on the underlying `Build` instance, refer to the [Model Context](model_context.md#build-order) page.
### Build Line
@@ -107,9 +102,7 @@ When printing a report or label against a [BuildOrderLineItem](../manufacturing/
{{ report_context("models", "buildline") }}
::: build.models.BuildLine.report_context
options:
show_source: True
For the fields and properties available on the underlying `BuildLine` instance, refer to the [Model Context](model_context.md#build-order-line-item) page.
### Sales Order
@@ -117,9 +110,7 @@ When printing a report or label against a [SalesOrder](../sales/sales_order.md)
{{ report_context("models", "salesorder") }}
::: order.models.Order.report_context
options:
show_source: True
For the fields and properties available on the underlying `SalesOrder` instance, refer to the [Model Context](model_context.md#sales-order) page.
### Sales Order Shipment
@@ -127,9 +118,7 @@ When printing a report or label against a [SalesOrderShipment](../sales/sales_or
{{ report_context("models", "salesordershipment") }}
::: order.models.SalesOrderShipment.report_context
options:
show_source: True
For the fields and properties available on the underlying `SalesOrderShipment` instance, refer to the [Model Context](model_context.md#sales-order-shipment) page.
### Return Order
@@ -137,21 +126,23 @@ When printing a report or label against a [ReturnOrder](../sales/return_order.md
{{ report_context("models", "returnorder") }}
For the fields and properties available on the underlying `ReturnOrder` instance, refer to the [Model Context](model_context.md#return-order) page.
### Purchase Order
When printing a report or label against a [PurchaseOrder](../purchasing/purchase_order.md) object, the following context variables are available:
{{ report_context("models", "purchaseorder") }}
For the fields and properties available on the underlying `PurchaseOrder` instance, refer to the [Model Context](model_context.md#purchase-order) page.
### Transfer Order
When printing a report or label against a [TransferOrder](../stock/transfer_order.md) object, the following context variables are available:
{{ report_context("models", "transferorder") }}
::: order.models.TransferOrder.report_context
options:
show_source: True
For the fields and properties available on the underlying `TransferOrder` instance, refer to the [Model Context](model_context.md#transfer-order) page.
### Stock Item
@@ -159,9 +150,7 @@ When printing a report or label against a [StockItem](../stock/index.md#stock-it
{{ report_context("models", "stockitem") }}
::: stock.models.StockItem.report_context
options:
show_source: True
For the fields and properties available on the underlying `StockItem` instance, refer to the [Model Context](model_context.md#stock-item) page.
### Stock Location
@@ -169,9 +158,7 @@ When printing a report or label against a [StockLocation](../stock/index.md#stoc
{{ report_context("models", "stocklocation") }}
::: stock.models.StockLocation.report_context
options:
show_source: True
For the fields and properties available on the underlying `StockLocation` instance, refer to the [Model Context](model_context.md#stock-location) page.
### Part
@@ -179,190 +166,9 @@ When printing a report or label against a [Part](../part/index.md) object, the f
{{ report_context("models", "part") }}
::: part.models.Part.report_context
options:
show_source: True
## Model Variables
Additional to the context variables provided directly to each template, each model type has a number of attributes and methods which can be accessed 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 from within the template.
| Variable | Description |
|----------|-------------|
| name | Brief name for this part |
| full_name | Full name for this part (including IPN, if not null and including variant, if not null) |
| category | The [PartCategory](#part-category) object to which this part belongs
| description | Longer form description of the part
| keywords | Optional keywords for improving part search results
| IPN | Internal part number (optional)
| revision | Part revision
| is_template | If True, this part is a 'template' part
| link | Link to an external page with more information about this part (e.g. internal Wiki)
| image | Image of this part
| default_location | The default [StockLocation](#stock-location) object where the item is normally stored (may be null)
| default_supplier | The default [SupplierPart](#supplierpart) which should be used to procure and stock this part
| default_expiry | The default expiry duration for any StockItem instances of this part
| minimum_stock | Minimum preferred quantity to keep in stock
| units | Units of measure for this part (default='pcs')
| salable | Can this part be sold to customers?
| assembly | Can this part be build from other parts?
| component | Can this part be used to make other parts?
| purchaseable | Can this part be purchased from suppliers?
| trackable | Trackable parts can have unique serial numbers assigned, etc, etc
| active | Is this part active? Parts are deactivated instead of being deleted
| virtual | Is this part "virtual"? e.g. a software product or similar
| notes | Additional notes field for this part
| creation_date | Date that this part was added to the database
| creation_user | User who added this part to the database
| responsible | User who is responsible for this part (optional)
| starred | Whether the part is starred or not |
| disabled | Whether the part is disabled or not |
| total_stock | The total amount in stock |
| quantity_being_built | The amount being built |
| required_build_order_quantity | The amount required for build orders |
| allocated_build_order_quantity | The amount allocated for build orders |
| build_order_allocations | Query set with all build order allocations for that part |
| required_sales_order_quantity | The amount required for sales orders |
| allocated_sales_order_quantity | The amount allocated for sales orders |
| available | Whether the part is available or not |
| on_order | The amount that are on order |
| required | The total amount required for build orders and sales orders |
| allocated | The total amount allocated for build orders and sales orders |
#### Part Category
For the fields and properties available on the underlying `Part` instance, refer to the [Model Context](model_context.md#part) page.
| Variable | Description |
|----------|-------------|
| name | Name of this category |
| parent | Parent category |
| default_location | Default [StockLocation](#stock-location) object for parts in this category or child categories |
| default_keywords | Default keywords for parts created in this category |
## Model Context
### Stock
#### StockItem
| Variable | Description |
|----------|-------------|
| parent | Link to another [StockItem](#stock-item) from which this StockItem was created |
| part | Link to the master abstract [Part](#part) that this [StockItem](#stock-item) is an instance of |
| supplier_part | Link to a specific [SupplierPart](#supplierpart) (optional) |
| location | The [StockLocation](#stock-location) Where this [StockItem](#stock-item) is located |
| quantity | Number of stocked units |
| batch | Batch number for this [StockItem](#stock-item) |
| serial | Unique serial number for this [StockItem](#stock-item) |
| link | Optional URL to link to external resource |
| updated | Date that this stock item was last updated (auto) |
| expiry_date | Expiry date of the [StockItem](#stock-item) (optional) |
| stocktake_date | Date of last stocktake for this item |
| stocktake_user | User that performed the most recent stocktake |
| delete_on_deplete | If True, [StockItem](#stock-item) will be deleted when the stock level gets to zero |
| status | Status of this [StockItem](#stock-item) (ref: InvenTree.status_codes.StockStatus) |
| status_label | Textual representation of the status e.g. "OK" |
| 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](#purchase-order) (if this stock item was created from a PurchaseOrder) |
| sales_order | Link to a [SalesOrder](#sales-order) object (if the StockItem has been assigned to a SalesOrder) |
| purchase_price | The unit purchase price for this [StockItem](#stock-item) - this is the unit price at time of purchase (if this item was purchased from an external supplier) |
| packaging | Description of how the StockItem is packaged (e.g. "reel", "loose", "tape" etc) |
#### StockLocation
| Variable | Description |
|----------|-------------|
| barcode | Brief payload data (e.g. for labels). Example: `{"stocklocation": 826}` where 826 is the primary key|
| description | The description of the location |
| icon | The name of the icon if set, e.g. fas fa-warehouse |
| item_count | Simply returns the number of stock items in this location |
| name | The name of the location. This is only the name of this location, not the path |
| owner | The owner of the location if it has one |
| parent | The parent location. Returns None if it is already the top most one |
| path | A queryset of locations that contains the hierarchy starting from the top most parent |
| pathstring | A string that contains all names of the path separated by slashes e.g. A/B/C |
| structural | True if the location is structural |
### Suppliers
#### Company
| Variable | Description |
|----------|-------------|
| name | Name of the company |
| description | Longer form description |
| website | URL for the company website |
| primary_address | [Address](#address) object that is marked as primary address |
| address | String format of the primary address |
| contact | Contact Name |
| phone | Contact phone number |
| email | Contact email address |
| link | URL associated with the company |
| notes | Extra notes about the company |
| is_customer | Boolean value, is this company a customer |
| is_supplier | Boolean value, is this company a supplier |
| is_manufacturer | Boolean value, is this company a manufacturer |
| currency_code | Default currency for the company |
| parts | Query set with all parts that the company supplies |
#### Address
| Variable | Description |
|----------|-------------|
| line1 | First line of the postal address |
| line2 | Second line of the postal address |
| postal_code | ZIP code of the city |
| postal_city | City name |
| country | Country name |
#### Contact
| Variable | Description |
|----------|-------------|
| company | Company object where the contact belongs to |
| name | First and second name of the contact |
| phone | Phone number |
| email | Email address |
| role | Role of the contact |
#### SupplierPart
| Variable | Description |
|----------|-------------|
| part | Link to the master Part (Obsolete) |
| source_item | The sourcing [StockItem](#stock-item) linked to this [SupplierPart](#supplierpart) instance |
| supplier | [Company](#company) that supplies this part |
| SKU | Stock keeping unit (supplier part number) |
| link | Link to external website for this supplier part |
| description | Descriptive notes field |
| note | Longer form note field |
| base_cost | Base charge added to order independent of quantity e.g. "Reeling Fee" |
| multiple | Multiple that the part is provided in |
| packaging | packaging that the part is supplied in, e.g. "Reel" |
| pretty_name | The IPN, supplier name, supplier SKU and (if not null) manufacturer string joined by `|`. Ex. `P00037 | Company | 000021` |
| unit_pricing | The price for one unit. |
| price_breaks | Return the associated price breaks in the correct order |
| has_price_breaks | Whether this [SupplierPart](#supplierpart) has price breaks |
| manufacturer_string | Format a MPN string for this [SupplierPart](#supplierpart). Concatenates manufacture name and part number. |
### User
| Variable | Description |
|----------|-------------|
| username | the username of the user |
| first_name | The first name of the user |
| last_name | The last name of the user |
| email | The email address of the user |
| pk | The primary key of the user |
For the underlying fields and properties available on each of the model instances above (plus related model types such as `Address` or `SupplierPart`), refer to the [Model Context](model_context.md) page.
+14 -1
View File
@@ -94,10 +94,23 @@ If the *Attach to Model on Print* option is enabled, a copy of the generated rep
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/index.md#stock-item) can use the part name and serial number of the stock item when generating the report name:
The filename pattern is rendered using the same Django template syntax (`{% raw %}{{ ... }}{% endraw %}`) as the report body, using the same context data - see the [context variables](./context_variables.md) and [model context](./model_context.md) documentation for the full list of variables available to a particular template type.
!!! info "Filename Pattern Context"
The filename pattern has access to the *entire* context available to the report or label being generated - not a reduced subset.
For example, a test report for a particular [Stock Item](../stock/index.md#stock-item) can use the part name and serial number of the stock item when generating the report name:
{{ image("report/filename_pattern.png", "Report filename pattern") }}
Some further examples:
| Filename Pattern | Description |
| --- | --- |
| `{% raw %}{{ part.full_name }}-{{ serial }}.pdf{% endraw %}` | Combines the [Part](./model_context.md#part) name with the stock item serial number |
| `{% raw %}PurchaseOrder-{{ reference }}.pdf{% endraw %}` | Uses the purchase order reference (this is the default pattern for the built-in Purchase Order report) |
| `{% raw %}SalesOrder-{{ reference }}-{{ date }}.pdf{% endraw %}` | Combines the sales order reference with the current date |
### Template Filters
+24
View File
@@ -0,0 +1,24 @@
---
title: Model Context
---
## Model Context Variables
Each [report context](./context_variables.md) exposes one or more underlying model instances to the template (e.g. `order`, `part`, `item`). In addition to the explicit context variables documented on that page, templates can access any field or property of these model instances directly.
This page documents, for each reportable model type, the available:
- **Fields**: Database fields defined on the model (including those inherited from mixins / abstract base classes)
- **Properties**: `@property` attributes which have been explicitly marked with the `@report_attribute` decorator, making them discoverable here
Not every attribute or method available on a model instance is listed here - only database fields, and properties explicitly marked for discovery. For a full list of attributes and methods, refer to the source code for the particular model type.
{{ reportable_model_context() }}
## Related Model Types
Some *related* model types are not themselves directly reportable, but are referenced by a field or `@report_attribute` property on a reportable model (e.g. `PartCategory` via `part.category`, `SupplierPart` via `part.default_supplier` or `stockitem.supplier_part`).
These are discovered automatically - there is no manually-maintained list of related models here. If a reportable model gains a new field or `@report_attribute` property pointing at another model, that model will automatically appear in this section.
{{ related_model_context() }}
+69
View File
@@ -442,6 +442,75 @@ def define_env(env):
return ret_data
def render_attribute_table(attributes: dict, title: str) -> str:
"""Render a table of field/property information, in a collapsible (collapsed by default) block.
Returns an empty string (including no block) if there is nothing to display.
"""
if not attributes:
return ''
table = '| Variable | Type | Description |\n| --- | --- | --- |\n'
for k, v in sorted(attributes.items()):
description = ' '.join(v['description'].split())
table += f'| {k} | `{v["type"]}` | {description} |\n'
ret_data = f'??? note "{title}"\n\n'
ret_data += textwrap.indent(table, ' ')
# Trailing blank line, so consecutive macro calls (e.g. fields followed by
# properties) don't run together when the template places them on adjacent lines
return ret_data + '\n'
@env.macro
def reportable_model_context():
"""Render the full 'reportable model types' section.
One heading plus fields/properties tables per model which templates can be
rendered against (e.g. `Part`, `SalesOrder`, `StockItem`). The list of models
comes directly from what `export_report_context` discovered via the
`InvenTreeReportMixin`, so there is no manually-maintained per-model heading
list to keep in sync here.
"""
global REPORT_CONTEXT
models = REPORT_CONTEXT.get('models', {})
ret_data = ''
for info in sorted(models.values(), key=lambda item: item['name']):
ret_data += f'### {info["name"]}\n\n'
ret_data += render_attribute_table(info.get('fields', {}), 'Fields')
ret_data += render_attribute_table(info.get('properties', {}), 'Properties')
return ret_data
@env.macro
def related_model_context():
"""Render the full 'related model types' section.
A "related" model is one which is not itself reportable, but which is
referenced by a field or `@report_attribute` property on a reportable model
(e.g. `PartCategory` via `Part.category`, `SupplierPart` via `Part.default_supplier`).
These are discovered automatically (one hop out from the reportable models) by
the `export_report_context` management command, so there is no manually-maintained
list of related models to keep in sync here.
"""
global REPORT_CONTEXT
related = REPORT_CONTEXT.get('related_models', {})
ret_data = ''
for info in sorted(related.values(), key=lambda item: item['name']):
ret_data += f'### {info["name"]}\n\n'
ret_data += render_attribute_table(info.get('fields', {}), 'Fields')
ret_data += render_attribute_table(info.get('properties', {}), 'Properties')
return ret_data
@env.macro
def icon(
source: str,
+2 -1
View File
@@ -183,7 +183,8 @@ nav:
- Labels: report/labels.md
- Report Assets: report/assets.md
- Report Snippets: report/snippets.md
- Context Variables: report/context_variables.md
- Report Context: report/context_variables.md
- Model Context: report/model_context.md
- Helper Functions: report/helpers.md
- Barcodes: report/barcodes.md
- Sample Templates: report/samples.md