Merge branch 'master' into feat(backend)--add-throtteling-by-default
This commit is contained in:
commit
f354ace571
|
|
@ -174,7 +174,7 @@ jobs:
|
|||
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # pin@v4.0.0
|
||||
- name: Set up cosign
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: sigstore/cosign-installer@cad07c2e89fa2edd6e2d7bab4c1aa38e53f76003 # pin@v4.1.1
|
||||
uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # pin@v4.1.2
|
||||
- name: Check if Dockerhub login is required
|
||||
id: docker_login
|
||||
run: |
|
||||
|
|
|
|||
|
|
@ -222,7 +222,7 @@ jobs:
|
|||
echo "Downloaded api.yaml"
|
||||
- name: Running OpenAPI Spec diff action
|
||||
id: breaking_changes
|
||||
uses: oasdiff/oasdiff-action/diff@e7609f171f253c3e2be2a2e5c508f749ca476a07 # pin@main
|
||||
uses: oasdiff/oasdiff-action/diff@6147a58e5d1249a12f42fc864ab791d571a30015 # pin@main
|
||||
with:
|
||||
base: "api.yaml"
|
||||
revision: "src/backend/InvenTree/schema.yml"
|
||||
|
|
@ -363,7 +363,7 @@ jobs:
|
|||
pip install .
|
||||
if: needs.paths-filter.outputs.submit-performance == 'true'
|
||||
- name: Performance Reporting
|
||||
uses: CodSpeedHQ/action@c381be0bfd20e844fb45594f6aa182ffcd94545c # pin@v4.15.0
|
||||
uses: CodSpeedHQ/action@3194d9a39c4d46684cb44bf7207fc56626aad8fd # pin@v4.15.1
|
||||
# check if we are in inventree/inventree - reporting only works in that OIDC context
|
||||
if: github.repository == 'inventree/InvenTree' && needs.paths-filter.outputs.submit-performance == 'true'
|
||||
with:
|
||||
|
|
@ -454,7 +454,7 @@ jobs:
|
|||
env:
|
||||
node_version: '>=24'
|
||||
- name: Performance Reporting
|
||||
uses: CodSpeedHQ/action@c381be0bfd20e844fb45594f6aa182ffcd94545c # pin@v4.15.0
|
||||
uses: CodSpeedHQ/action@3194d9a39c4d46684cb44bf7207fc56626aad8fd # pin@v4.15.1
|
||||
with:
|
||||
mode: walltime
|
||||
run: inv dev.test --pytest
|
||||
|
|
|
|||
|
|
@ -67,6 +67,6 @@ jobs:
|
|||
|
||||
# Upload the results to GitHub's code scanning dashboard.
|
||||
- name: "Upload to code-scanning"
|
||||
uses: github/codeql-action/upload-sarif@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
|
||||
uses: github/codeql-action/upload-sarif@68bde559dea0fdcac2102bfdf6230c5f70eb485e # v4.35.4
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
|
|
|
|||
|
|
@ -9,11 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Breaking Changes
|
||||
|
||||
- [#9604](https://github.com/inventree/InvenTree/pull/9604) - refactors user API endpoint to be less ambiguous
|
||||
- [#11893](https://github.com/inventree/InvenTree/pull/11893) bumps Node environment to version 24 LTS - this is only relevant if you build the frontend assets yourself
|
||||
- [#11951](https://github.com/inventree/InvenTree/pull/11951) adds API throtteling by default to make DoS attacks more difficult. This can be disabled by setting the `INVENTREE_THROTTLE_ANON` and `INVENTREE_THROTTLE_USER` settings to `None` (either via environment variable or config file). The default throttling rates are 20 requests per minute for anonymous users, and 20 requests per second for authenticated users.
|
||||
|
||||
### Added
|
||||
|
||||
- [#11920](https://github.com/inventree/InvenTree/pull/11920) adds support for renaming attachments after they have been uploaded. This includes both backend and frontend changes, allowing users to rename attachments via the API or through the UI.
|
||||
- [#11914](https://github.com/inventree/InvenTree/pull/11914) adds a "maximum_stock" field to the Part model, allowing users to specify a maximum preferred stock level for each part. This is used in conjunction with the existing "minimum_stock" field to allow users to define a preferred stock range for each part. The "high_stock" filter has also been added to the Part API endpoint, allowing users to filter parts which are above their maximum stock level.
|
||||
- [#11631](https://github.com/inventree/InvenTree/pull/11631) adds "raw_amount" field to the BomItem model, allowing BOM quantities to account for the units of measure of the underlying part.
|
||||
- [#11872](https://github.com/inventree/InvenTree/pull/11872) adds a global setting to allow or disallow the deletion of serialized stock items.
|
||||
|
|
@ -23,14 +25,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
- [#11778](https://github.com/inventree/InvenTree/pull/11778) adds inline supplier part creation to po line item addition dialog.
|
||||
- [#11772](https://github.com/inventree/InvenTree/pull/11772) the UI now warns if you navigate away from a note panel with unsaved changes
|
||||
- [#11788](https://github.com/inventree/InvenTree/pull/11788) adds support for custom permissions checks on database models defined in plugins. If a model defines a `check_user_permission` classmethod, this will be called to determine if a user has permission to view the model. This is required for plugin models which do not have the required ruleset definitions for the standard permission system.
|
||||
- [#9570](https://github.com/inventree/InvenTree/pull/9570) adds support for defining primary actions via plugins
|
||||
|
||||
### Changed
|
||||
|
||||
- [#11990](https://github.com/inventree/InvenTree/pull/11990) build output operations performed via the API now offload the work to a background task, and now return a task ID which can be used to monitor the progress of the task. This allows for better performance and responsiveness when performing build output operations, as the work is performed asynchronously in the background.
|
||||
- [#11825](https://github.com/inventree/InvenTree/pull/11825) adds a new "bom" ruleset and associated permissions for BOM management, separate from the "part" ruleset which remains focused on part management. This allows for more granular control over user permissions, allowing users to have different levels of access to part management and BOM management functionality.
|
||||
- [#11816](https://github.com/inventree/InvenTree/pull/11816) makes the `issued_by` field on the `Build` API read only, and instead sets the `issued_by` field to the current user when a build is created. This change was made to ensure that the `issued_by` field accurately reflects the user who created the build, and to prevent users from setting this field to an arbitrary value when creating or updating a build.
|
||||
|
||||
### Removed
|
||||
|
||||
- [#11962](https://github.com/inventree/InvenTree/pull/11962) removes the "remote_image" field from the Part API endpoint, which (previously) allowed the user to specify a remote URL for an image to be downloaded and associated with the part. This field was removed due to security concerns around downloading images from arbitrary URLs. If you were using this field in an external client application, you will need to update your application to use the new "download_image_from_url" API endpoint instead.
|
||||
|
||||
## 1.3.0 - 2026-04-11
|
||||
|
||||
### Breaking Changes
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
ignore:
|
||||
- "src/backend/InvenTree/**/test_migrations.py"
|
||||
|
||||
coverage:
|
||||
status:
|
||||
project:
|
||||
|
|
|
|||
|
|
@ -139,9 +139,9 @@ charset-normalizer==3.4.7 \
|
|||
# via
|
||||
# -c src/backend/requirements.txt
|
||||
# requests
|
||||
idna==3.13 \
|
||||
--hash=sha256:585ea8fe5d69b9181ec1afba340451fba6ba764af97026f92a91d4eef164a242 \
|
||||
--hash=sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3
|
||||
idna==3.15 \
|
||||
--hash=sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8 \
|
||||
--hash=sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc
|
||||
# via
|
||||
# -c src/backend/requirements.txt
|
||||
# requests
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ Each user is assigned an authentication token which can be used to access the AP
|
|||
|
||||
If a user does not know their access token, it can be requested via the API interface itself, using a basic authentication request.
|
||||
|
||||
To obtain a valid token, perform a GET request to `/api/user/token/`. No data are required, but a valid username / password combination must be supplied in the authentication headers.
|
||||
To obtain a valid token, perform a GET request to `/api/user/me/token/`. No data are required, but a valid username / password combination must be supplied in the authentication headers.
|
||||
|
||||
!!! info "Credentials"
|
||||
Ensure that a valid username:password combination are supplied as basic authorization headers.
|
||||
|
|
@ -146,7 +146,7 @@ r:delete:stock
|
|||
Users can only perform REST API actions which align with their assigned [role permissions](../settings/permissions.md#roles).
|
||||
Once a user has *authenticated* via the API, a list of the available roles can be retrieved from:
|
||||
|
||||
`/api/user/roles/`
|
||||
`/api/user/me/roles/`
|
||||
|
||||
For example, when accessing the API from a *superuser* account:
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ The API schema as documented below is generated using the [drf-spectactular](htt
|
|||
|
||||
## API Version
|
||||
|
||||
This documentation is for API version: `449`
|
||||
This documentation is for API version: `459`
|
||||
|
||||
!!! tip "API Schema History"
|
||||
We track API schema changes, and provide a snapshot of each API schema version in the [API schema repository](https://github.com/inventree/schema/).
|
||||
|
|
|
|||
Binary file not shown.
|
After Width: | Height: | Size: 43 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 87 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
|
|
@ -16,3 +16,36 @@ Parameters can be associated with various InvenTree models.
|
|||
Any model which supports attachments will have an "Attachments" tab on its detail page. This tab displays all attachments associated with that object:
|
||||
|
||||
{{ image("concepts/attachments-tab.png", "Order Attachments Example") }}
|
||||
|
||||
## Attachments Types
|
||||
|
||||
The following types of attachments are supported:
|
||||
|
||||
### File Attachments
|
||||
|
||||
File attachments allow users to upload files directly to InvenTree. These files are stored on the server and can be downloaded or viewed by users with appropriate permissions.
|
||||
|
||||
### Image Thumbnails
|
||||
|
||||
When a file attachment is uploaded, InvenTree automatically determines whether the file is a valid image. If it is, a thumbnail is generated and stored alongside the attachment.
|
||||
|
||||
- The thumbnail is created with a reduced image size, while preserving the original aspect ratio.
|
||||
- Thumbnail generation is performed in the background after upload.
|
||||
- The `is_image` flag on the attachment record is set to `True` for valid images, and `False` for all other file types.
|
||||
- If the uploaded file has an image extension but contains invalid or corrupt image data, no thumbnail is generated and `is_image` remains `False`.
|
||||
- Link attachments (external URLs) are never assigned a thumbnail.
|
||||
|
||||
!!! info "Supported Formats"
|
||||
Any image format recognised by the [Pillow](https://pillow.readthedocs.io/) library (e.g. PNG, JPEG, GIF, BMP, WEBP) will be treated as a valid image and have a thumbnail generated automatically.
|
||||
|
||||
### Link Attachments
|
||||
|
||||
Link attachments allow users to associate external URLs with an object. This can be useful for linking to external documentation, resources, or other relevant web content.
|
||||
|
||||
## Adding Attachments
|
||||
|
||||
To add an attachment to an object, navigate to the object's detail page and click on the "Attachments" tab. From there, you can click the "Add attachment" button to upload a file or the "Add external link" button to add a link.
|
||||
|
||||
### Renaming Attachments
|
||||
|
||||
Once a file attachment has been uploaded, it can be renamed by clicking the "Edit" action associated with the attachment. This allows you to change the filename without needing to re-upload the file. The system will handle renaming the file on the server and updating the database record accordingly.
|
||||
|
|
|
|||
|
|
@ -4,16 +4,70 @@ title: Custom States
|
|||
|
||||
## Custom States
|
||||
|
||||
Several models within InvenTree support the use of custom states. The custom states are display only - the business logic is not affected by the state.
|
||||
Several models within InvenTree support the use of *custom states*. Custom states extend the built-in status system by adding extra labels and colours that are displayed in the user interface.
|
||||
|
||||
States can be added in the [Admin Center](../settings/admin.md#admin-center) under the "Custom States" section. Each state has a name, label and a color that are used to display the state in the user interface. Changes to these settings will only be reflected in the user interface after a full reload of the interface.
|
||||
!!! info "Display Only"
|
||||
Custom states affect display only — they do not add new workflow steps or change business logic. Every custom state is mapped to an existing built-in state (its *logical key*), and the system uses that built-in state for all decisions such as availability counts, order transitions, and filtering.
|
||||
|
||||
States need to be assigned to a model, state (for example status on a StockItem) and a logical key - that will be used for business logic. These 3 values combined need to be unique throughout the system.
|
||||
### Example
|
||||
|
||||
Custom states can be defined for the following models:
|
||||
Suppose you want to track stock items that are physically present and available, but are waiting for a quality inspection before use. The built-in `OK` status is the closest match — the item is available — but you want it to appear distinctly in the interface.
|
||||
|
||||
- [Stock Item](../stock/index.md)
|
||||
- [Build Order](../manufacturing/build.md)
|
||||
- [Purchase Order](../purchasing/purchase_order.md)
|
||||
- [Sales Order](../sales/sales_order.md)
|
||||
- [Return Order](../sales/return_order.md)
|
||||
You would create a custom state:
|
||||
|
||||
- **Logical key**: `OK` — the system treats the item as available stock
|
||||
- **Label**: `Awaiting Inspection` — shown in the interface instead of "OK"
|
||||
- **Colour**: `warning` — displayed in amber to draw attention
|
||||
|
||||
The item is counted as available stock in all reports and filters, but is visually distinguished from items with a standard `OK` status.
|
||||
|
||||
## Managing Custom States
|
||||
|
||||
Custom states are managed in the [Admin Center](../settings/admin.md#admin-center) under the *Custom States* section.
|
||||
|
||||
!!! warning "Page Reload Required"
|
||||
Changes to custom states are only reflected in the user interface after a full page reload.
|
||||
|
||||
## State Fields
|
||||
|
||||
When creating a custom state, the following fields must be provided:
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| **Model** | The model type this state applies to (e.g. *Stock Item*, *Build Order*) |
|
||||
| **Reference Status** | The status class being extended (e.g. `StockStatus`, `BuildStatus`) |
|
||||
| **Logical Key** | The built-in status value this custom state maps to for business logic |
|
||||
| **Key** | A unique integer that identifies this custom state in the database |
|
||||
| **Name** | An uppercase Python identifier for this state (e.g. `AWAITING_INSPECTION`) |
|
||||
| **Label** | The human-readable text displayed in the interface |
|
||||
| **Colour** | The badge colour used to display the state |
|
||||
|
||||
### Key
|
||||
|
||||
The *Key* is the integer value stored in the database when this custom state is active. It must satisfy all of the following:
|
||||
|
||||
- Must be a positive integer
|
||||
- Must not be equal to the *Logical Key*
|
||||
- Must not conflict with any existing built-in status values for the selected model
|
||||
|
||||
### Name
|
||||
|
||||
The *Name* field is used internally to identify the state. It must:
|
||||
|
||||
- Be uppercase (e.g. `AWAITING_INSPECTION`, not `awaiting_inspection`)
|
||||
- Be a valid Python identifier (letters, digits, underscores; no spaces or hyphens)
|
||||
- Not conflict with any existing status names for the selected model
|
||||
|
||||
### Colours
|
||||
|
||||
The following colour values are available:
|
||||
|
||||
| Colour | Appearance |
|
||||
|--------|------------|
|
||||
| `primary` | Blue |
|
||||
| `secondary` | Grey |
|
||||
| `success` | Green |
|
||||
| `warning` | Amber |
|
||||
| `danger` | Red |
|
||||
| `info` | Cyan |
|
||||
| `dark` | Dark grey / black |
|
||||
|
|
|
|||
|
|
@ -0,0 +1,72 @@
|
|||
---
|
||||
title: Exporting Data
|
||||
---
|
||||
|
||||
## Exporting Data
|
||||
|
||||
InvenTree provides data export functionality for a variety of data types. Most data tables in the web interface include a *Download* button in the table toolbar, which allows the currently displayed data to be exported to a file.
|
||||
|
||||
!!! info "Filtered Data"
|
||||
The export reflects the data currently visible in the table — any active filters, search terms, or sort order are carried through to the exported file. To export the full dataset, clear all filters before exporting.
|
||||
|
||||
!!! info "Paginated Data"
|
||||
In the user interface, data tables are paginated to improve performance. When exporting data, the export will include **all** records that match the current filters and search terms, not just the records visible on the current page.
|
||||
|
||||
## How to Export
|
||||
|
||||
**Step 1** — In any table view, click the {{ icon("cloud-download") }} *Download* button in the table toolbar:
|
||||
|
||||
{{ image("admin/export.png", "Download button") }}
|
||||
|
||||
**Step 2** — An export dialog is displayed. Select the desired *Export Format* and *Export Plugin*, then click *Export*:
|
||||
|
||||
{{ image("admin/export_options.png", "Export dialog") }}
|
||||
|
||||
**Step 3** — The export runs in the background. A loading indicator is shown while the export is being processed. When the export is complete, the file is automatically downloaded to your browser.
|
||||
|
||||
## Supported File Formats
|
||||
|
||||
The following file formats are available for export:
|
||||
|
||||
| Format | Description |
|
||||
|--------|-------------|
|
||||
| CSV | Comma-separated values. Portable plain-text format, compatible with most tools. |
|
||||
| Excel | Microsoft Excel format (`.xlsx`). Suitable for direct use in spreadsheet applications. |
|
||||
| TSV | Tab-separated values. Similar to CSV but uses tab characters as delimiters. |
|
||||
|
||||
## Export Plugins
|
||||
|
||||
InvenTree uses a plugin-based export system. The export dialog lists all plugins that are available for the data type being exported. Selecting a different plugin may provide additional export options or a different output format.
|
||||
|
||||
### Built-in Exporters
|
||||
|
||||
InvenTree includes the following built-in export plugins:
|
||||
|
||||
| Plugin | Description |
|
||||
|--------|-------------|
|
||||
| [InvenTree Exporter](../plugins/builtin/inventree_exporter.md) | General-purpose exporter for any tabulated dataset. Always enabled. |
|
||||
| [BOM Exporter](../plugins/builtin/bom_exporter.md) | Custom exporter for Bill of Materials data, with additional BOM-specific options. |
|
||||
| [Parameter Exporter](../plugins/builtin/parameter_exporter.md) | Exports part data including all associated custom parameter values as additional columns. |
|
||||
| [Stocktake Exporter](../plugins/builtin/stocktake_exporter.md) | Exports a comprehensive stock-level summary for parts, with optional pricing and variant data. |
|
||||
|
||||
Custom export plugins can also be developed using the [DataExportMixin](../plugins/mixins/export.md).
|
||||
|
||||
## API Export
|
||||
|
||||
Data can also be exported programmatically via the InvenTree REST API. To trigger an export, perform a `GET` request against any list endpoint with the following query parameters:
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `export` | Set to `true` to trigger an export |
|
||||
| `export_format` | File format: `csv`, `xlsx`, or `tsv` (default: `csv`) |
|
||||
| `export_plugin` | Slug of the export plugin to use (default: `inventree-exporter`) |
|
||||
|
||||
Additional `export_*` parameters may be accepted depending on the plugin selected.
|
||||
|
||||
**Example:**
|
||||
|
||||
```
|
||||
GET /api/part/?export=true&export_format=xlsx&export_plugin=inventree-exporter
|
||||
```
|
||||
|
||||
Refer to the [API documentation](../api/index.md) for further details.
|
||||
|
|
@ -43,7 +43,7 @@ Importing data is a multi-step process, which is managed via an *import session*
|
|||
|
||||
The import session is managed by the InvenTree server, and all import session data is stored on the server. As the import process can be time-consuming, the user can navigate away from the import page and return later to check on the progress of the import.
|
||||
|
||||
Import sessions can be managed from the [Admin Center](./admin.md#admin-center) page, which lists all available import sessions
|
||||
Import sessions can be managed from the [Admin Center](../settings/admin.md#admin-center) page, which lists all available import sessions
|
||||
|
||||
### Context Sensitive Importing
|
||||
|
||||
|
|
@ -55,9 +55,9 @@ An import session can be initiated from a number of different contexts within th
|
|||
|
||||
### Admin Center
|
||||
|
||||
Staff users can create an import session from within the [Admin Center](./admin.md#admin-center). This is a general-purpose import session, and the user will be required to select the type of data to import.
|
||||
Staff users can create an import session from within the [Admin Center](../settings/admin.md#admin-center). This is a general-purpose import session, and the user will be required to select the type of data to import.
|
||||
|
||||
Users can quickly navigate to the data import managemement page from the [spotlight search](../concepts/user_interface.md#spotlight), by searching for "import" and selecting the "Import data" option.
|
||||
Users can quickly navigate to the data import management page from the [spotlight search](../concepts/user_interface.md#spotlight), by searching for "import" and selecting the "Import data" option.
|
||||
|
||||
### Data Tables
|
||||
|
||||
|
|
@ -123,7 +123,7 @@ The basic outline of this process is:
|
|||
### Create Import Session
|
||||
|
||||
!!! note "Admin Center"
|
||||
Updating existing records can only be performed when creating a new import session from the [Admin Center](./admin.md#admin-center).
|
||||
Updating existing records can only be performed when creating a new import session from the [Admin Center](../settings/admin.md#admin-center).
|
||||
|
||||
Create a new import session, and ensure that the *Update Existing Records* option is selected. This will allow the import session to update existing records in the database.
|
||||
|
||||
|
|
@ -118,7 +118,7 @@ By default, the BOM is displayed in "view" mode. To edit the BOM, click on the {
|
|||
|
||||
### Importing a BOM
|
||||
|
||||
BOM data can be imported from an existing file (such as CSV or Excel) from the *BOM* panel for a particular part/assembly. This process is a special case of the more general [data import process](../settings/import.md).
|
||||
BOM data can be imported from an existing file (such as CSV or Excel) from the *BOM* panel for a particular part/assembly. This process is a special case of the more general [data import process](../concepts/data_import.md).
|
||||
|
||||
At the top of the *BOM* panel, click on the {{ icon("file-arrow-left", color="green", title="Import BOM Data") }} icon to open the import dialog.
|
||||
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ If the *Add Supplier Data* option is checked, then supplier part and manufacture
|
|||
|
||||
Parts can be imported from an external file, by selecting the *Import from File* option.
|
||||
|
||||
This action opens the [data import wizard](../settings/import.md), which steps the user through the process of importing parts from the selected file.
|
||||
This action opens the [data import wizard](../concepts/data_import.md), which steps the user through the process of importing parts from the selected file.
|
||||
|
||||
## Import from Supplier
|
||||
|
||||
|
|
|
|||
|
|
@ -96,6 +96,8 @@ Parts can be locked to prevent them from being modified. This is useful for part
|
|||
- BOM items cannot be created, edited, or deleted when they are part of a locked assembly
|
||||
- Parameters linked to a locked part cannot be created, edited or deleted
|
||||
|
||||
The part locking functionality can be enabled or disabled globally via the [Part Locking](../settings/global.md#parts) system setting (`PART_ENABLE_LOCKING`). When disabled, the locked state of a part is ignored and all operations are permitted.
|
||||
|
||||
## Active Parts
|
||||
|
||||
By default, all parts are *Active*. Marking a part as inactive means it is not available for many actions, but the part remains in the database. If a part becomes obsolete, it is recommended that it is marked as inactive, rather than deleting it from the database.
|
||||
|
|
@ -158,4 +160,4 @@ The [InvenTree mobile app](../app/part.md#part-image-view) allows part images to
|
|||
|
||||
## Part Import
|
||||
|
||||
*Parts* can be imported by staff-members on the part-list-view (this feature must be enabled in the part-settings), in the part-settings or on the [admin-page for parts](../settings/import.md) (only accessible if you are also an admin). The first two options provide a multi-stage wizard that enables mapping fields from various spreadsheet or table-data formats while the latter requires a well-formatted file but is much more performant.
|
||||
*Part* data can be imported using the [data import wizard](../concepts/data_import.md). This allows part data to be imported from an external file, which can be useful for bulk importing of part data.
|
||||
|
|
|
|||
|
|
@ -183,6 +183,20 @@ The `get_ui_template_previews` feature type can be used to provide custom templa
|
|||
summary: False
|
||||
members: []
|
||||
|
||||
### Primary Actions
|
||||
|
||||
The `get_ui_primary_actions` method can be used to provide custom primary action, which are rendered in the header of the page, next to the title/name and any status indicators. These primary actions are typically used to provide quick access to common actions related to the current page.
|
||||
|
||||
::: plugin.base.ui.mixins.UserInterfaceMixin.get_ui_primary_actions
|
||||
options:
|
||||
show_bases: False
|
||||
show_root_heading: False
|
||||
show_root_toc_entry: False
|
||||
extra:
|
||||
show_source: True
|
||||
summary: False
|
||||
members: []
|
||||
|
||||
## Plugin Context
|
||||
|
||||
When rendering certain content in the user interface, the rendering functions are passed a `context` object which contains information about the current page being rendered. The type of the `context` object is defined in the `PluginContext` file:
|
||||
|
|
|
|||
|
|
@ -1,25 +0,0 @@
|
|||
---
|
||||
title: Exporting Data
|
||||
---
|
||||
|
||||
## Exporting Data
|
||||
|
||||
InvenTree provides data export functionality for a variety of data types. Most data tables provide an "Download" button, which allows the user to export the data in a variety of formats.
|
||||
|
||||
In the top right corner of the table, click the "Download" button to export the data in the table.
|
||||
|
||||
{{ image("admin/export.png", "Download") }}
|
||||
|
||||
This will present a dialog box with the available export options:
|
||||
|
||||
{{ image("admin/export_options.png", "Export Dialog") }}
|
||||
|
||||
## Plugin Support
|
||||
|
||||
InvenTree plugins can also provide custom export functionality for specific data types. If a plugin provides export functionality, it will be listed in the export options.
|
||||
|
||||
Refer to the [export plugin mixin documentation](../plugins/mixins/export.md) for more information on how to create export plugins.
|
||||
|
||||
## API Export
|
||||
|
||||
Data can also be exported via the InvenTree REST API, by appending the appropriate format suffix (and other export options) to the API endpoint URL.
|
||||
|
|
@ -33,14 +33,7 @@ Configuration of basic server settings:
|
|||
{{ globalsetting("DISPLAY_FULL_NAMES") }}
|
||||
{{ globalsetting("DISPLAY_PROFILE_INFO") }}
|
||||
{{ globalsetting("WEEK_STARTS_ON") }}
|
||||
|
||||
Configuration of image download settings:
|
||||
|
||||
| Name | Description | Default | Units |
|
||||
| ---- | ----------- | ------- | ----- |
|
||||
{{ globalsetting("INVENTREE_DOWNLOAD_FROM_URL") }}
|
||||
{{ globalsetting("INVENTREE_DOWNLOAD_IMAGE_MAX_SIZE") }}
|
||||
{{ globalsetting("INVENTREE_DOWNLOAD_FROM_URL_USER_AGENT") }}
|
||||
{{ globalsetting("INVENTREE_UPLOAD_MAX_SIZE") }}
|
||||
{{ globalsetting("INVENTREE_STRICT_URLS") }}
|
||||
|
||||
Configuration of various scheduled tasks:
|
||||
|
|
@ -169,6 +162,7 @@ Configuration of label printing:
|
|||
{{ globalsetting("PART_ALLOW_DUPLICATE_IPN") }}
|
||||
{{ globalsetting("PART_ALLOW_EDIT_IPN") }}
|
||||
{{ globalsetting("PART_ALLOW_DELETE_FROM_ASSEMBLY") }}
|
||||
{{ globalsetting("PART_ENABLE_LOCKING") }}
|
||||
{{ globalsetting("PART_ENABLE_REVISION") }}
|
||||
{{ globalsetting("PART_REVISION_ASSEMBLY_ONLY") }}
|
||||
{{ globalsetting("PART_NAME_FORMAT") }}
|
||||
|
|
@ -217,6 +211,7 @@ Configuration of stock item options
|
|||
| Name | Description | Default | Units |
|
||||
| ---- | ----------- | ------- | ----- |
|
||||
{{ globalsetting("SERIAL_NUMBER_GLOBALLY_UNIQUE") }}
|
||||
{{ globalsetting("STOCK_ALLOW_EDIT_SERIAL") }}
|
||||
{{ globalsetting("STOCK_ALLOW_DELETE_SERIALIZED") }}
|
||||
{{ globalsetting("STOCK_DELETE_DEPLETED_DEFAULT") }}
|
||||
{{ globalsetting("STOCK_BATCH_CODE_TEMPLATE") }}
|
||||
|
|
@ -247,6 +242,10 @@ Refer to the [sales order settings](../sales/sales_order.md#sales-order-settings
|
|||
|
||||
Refer to the [return order settings](../sales/return_order.md#return-order-settings).
|
||||
|
||||
### Transfer Orders
|
||||
|
||||
Refer to the [transfer order settings](../stock/transfer_order.md#transfer-order-settings).
|
||||
|
||||
### Plugin Settings
|
||||
|
||||
| Name | Description | Default | Units |
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ The *Display Settings* screen shows general display configuration options:
|
|||
{{ usersetting("SHOW_BOM_SUBASSEMBLY_LEVELS")}}
|
||||
{{ usersetting("ENABLE_LAST_BREADCRUMB") }}
|
||||
{{ usersetting("SHOW_FULL_LOCATION_IN_TABLES") }}
|
||||
{{ usersetting("DISPLAY_ITEMS_FINAL_LEVEL") }}
|
||||
|
||||
### Search Settings
|
||||
|
||||
|
|
|
|||
|
|
@ -142,6 +142,8 @@ Note that any serial number adjustments are subject to the same validation rules
|
|||
|
||||
{{ image("stock/serial_edit_error.png", title="Error while editing a serial number") }}
|
||||
|
||||
!!! info "Disable Serial Number Editing"
|
||||
If you wish to prevent users from editing serial numbers, this can be achieved by disabling the `Allow Edit Serial Number` setting in the system settings view.
|
||||
|
||||
#### Plugin Support
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,150 @@
|
|||
|
||||
---
|
||||
title: Transfer Orders
|
||||
---
|
||||
|
||||
## Transfer Orders
|
||||
|
||||
Transfer orders provide a method for requesting stock to be moved from one location to another. It does not replace the existing on-demand stock transaction options, but lets you "document" many transactions from a single view.
|
||||
|
||||
### View Transfer Orders
|
||||
|
||||
To navigate to the Transfer Order display, select *Stock* from the main navigation menu, and *Transfer Orders* from the sidebar:
|
||||
|
||||
{{ image("stock/transfer_order_display.png", "Transfer Order display") }}
|
||||
|
||||
The following view modes are available:
|
||||
|
||||
#### Table View
|
||||
|
||||
*Table View* provides a list of Transfer Orders, which can be filtered to display a subset of orders according to user supplied parameters.
|
||||
|
||||
{{ image("stock/transfer_order_list.png", "Transfer Order list") }}
|
||||
|
||||
#### Calendar View
|
||||
|
||||
*Calendar View* shows a calendar display with outstanding transfer orders.
|
||||
|
||||
{{ image("stock/transfer_order_calendar.png", "Transfer Order calendar") }}
|
||||
|
||||
### Transfer Order Status Codes
|
||||
|
||||
Each Transfer Order has a specific status code, which represents the state of the order:
|
||||
|
||||
| Status | Description |
|
||||
| --- | --- |
|
||||
| Pending | The transfer order has been created, but has not been finalized or submitted |
|
||||
| Issued | The transfer order has been issued, and is in progress |
|
||||
| On Hold | The transfer order has been placed on hold, but is still active |
|
||||
| Complete | The transfer order is fully completed, and is now closed |
|
||||
| Cancelled | The transfer order was cancelled, and is now closed |
|
||||
|
||||
**Source Code**
|
||||
|
||||
Refer to the source code for the Transfer Order status codes:
|
||||
|
||||
::: order.status_codes.TransferOrderStatus
|
||||
options:
|
||||
show_bases: False
|
||||
show_root_heading: False
|
||||
show_root_toc_entry: False
|
||||
show_source: True
|
||||
members: []
|
||||
|
||||
Transfer Order Status supports [custom states](../concepts/custom_states.md).
|
||||
|
||||
### Transfer Order Parameters
|
||||
|
||||
The following parameters are available for each Transfer Order, and can be edited by the user:
|
||||
|
||||
| Parameter | Description |
|
||||
| --- | --- |
|
||||
| Reference | Transfer Order reference e.g. '001' |
|
||||
| Description | Description of the Transfer Order |
|
||||
| Project Code | Project Code of the Transfer Order |
|
||||
| Source Location | Stock location to source stock items from (blank = all locations) |
|
||||
| Destination Location | Stock location where the stock will be transferred |
|
||||
| Consume Stock | Rather than transfer the stock to the destination, "consume" it by removing the specified quantity from the allocated stock item
|
||||
| Start Date | The scheduled start date for the transfer |
|
||||
| Target Date | Target date for transfer completion |
|
||||
| External Link | Link to external webpage |
|
||||
| Responsible | User (or group of users) who is responsible for the transfer |
|
||||
| Notes | Transfer notes, supports markdown |
|
||||
|
||||
## Create a Transfer Order
|
||||
|
||||
Once the transfer order page is loaded, click on <span class="badge inventree add">{{ icon("plus-circle") }} New Transfer Order</span> which opens the "Create Transfer Order" form.
|
||||
|
||||
Fill out the rest of the form with the transfer order information then click on <span class="badge inventree confirm">Submit</span> to create the order.
|
||||
|
||||
### Transfer Order Reference
|
||||
|
||||
Each Transfer Order is uniquely identified by its *Reference* field. Read more about [reference fields](../settings/reference.md).
|
||||
|
||||
### Add Line Items
|
||||
|
||||
On the transfer order detail page, user can link parts to the transfer order selecting the <span class="badge inventree nav side">{{ icon("list") }}</span> Line Items</span> tab then clicking on the <span class="badge inventree add">{{ icon("plus-circle") }} Add Line Item</span> button.
|
||||
|
||||
Once the "Add Line Item" form opens, select a part in the list.
|
||||
|
||||
!!! warning
|
||||
Only parts that have the "Virtual" attribute disabled will be shown and can be selected.
|
||||
|
||||
Fill out the rest of the form then click on <span class="badge inventree confirm">Submit</span>
|
||||
|
||||
### Allocate Stock Items
|
||||
|
||||
After line items were created, user can either:
|
||||
|
||||
* Allocate stock items for that part to the transfer order (click on {{ icon("arrow-right") }} button)
|
||||
* Create a build order for that part to cover the quantity of the transfer order (click on {{ icon("tools") }} button)
|
||||
|
||||
### Complete Order
|
||||
|
||||
Once all items in the transfer order have been allocated, click on <span class="badge inventree add">{{ icon("circle-check", color="green") }} Complete Order</span> to mark the transfer order as complete. Confirm then click on <span class="badge inventree confirm">Submit</span> to complete the order.
|
||||
|
||||
### Transferred Stock
|
||||
|
||||
After completing the transfer order, a <span class="badge inventree nav side">{{ icon("list") }}</span> Transferred Stock</span> tab will appear showing which stock was affected.
|
||||
|
||||
!!! warning
|
||||
Similar to received stock on purchase orders, this tab will only be accurate while the affected stock items still exist. Furthermore, if the stock item is depleted while using the "consume" parameter, it will not appear here unless "delete on deplete" is turned off for this stock item
|
||||
|
||||
### Cancel Order
|
||||
|
||||
To cancel the order, click on the {{ icon("tools") }} menu button next to the <span class="badge inventree add">{{ icon("circle-check", color="green") }} Complete Order</span> button, then click on the "{{ icon("tools") }} Cancel Order" menu option. Confirm then click on the <span class="badge inventree confirm">Submit</span> to cancel the order.
|
||||
|
||||
## Order Scheduling
|
||||
|
||||
Transfer orders can be scheduled for a future date, to allow for order scheduling.
|
||||
|
||||
### Start Date
|
||||
|
||||
The *Start Date* of the transfer order is the date on which the order is scheduled to be issued, allowing work to begin on the order.
|
||||
|
||||
### Target Date
|
||||
|
||||
The *Target Date* of the transfer order is the date on which the order is scheduled to be completed.
|
||||
|
||||
### Overdue Orders
|
||||
|
||||
If the *Target Date* of the transfer order has passed, the order will be marked as *overdue*.
|
||||
|
||||
## Calendar view
|
||||
|
||||
Using the button to the top right of the list of Transfer Orders, the view can be switched to a calendar view using the button {{ icon("calendar") }}. This view shows orders with a defined target date only.
|
||||
|
||||
This view can be accessed externally as an ICS calendar using a URL like the following:
|
||||
`http://inventree.example.org/api/order/calendar/transfer-order/calendar.ics`
|
||||
|
||||
By default, completed orders are not exported. These can be included by appending `?include_completed=True` to the URL.
|
||||
|
||||
## Transfer Order Settings
|
||||
|
||||
The following [global settings](../settings/global.md) are available for transfer orders:
|
||||
|
||||
| Name | Description | Default | Units |
|
||||
| ---- | ----------- | ------- | ----- |
|
||||
{{ globalsetting("TRANSFERORDER_ENABLED") }}
|
||||
{{ globalsetting("TRANSFERORDER_REFERENCE_PATTERN") }}
|
||||
{{ globalsetting("TRANSFERORDER_REQUIRE_RESPONSIBLE") }}
|
||||
|
|
@ -96,6 +96,8 @@ nav:
|
|||
- Physical Units: concepts/units.md
|
||||
- Companies: concepts/company.md
|
||||
- Custom States: concepts/custom_states.md
|
||||
- Data Export: concepts/data_export.md
|
||||
- Data Import: concepts/data_import.md
|
||||
- Pricing: concepts/pricing.md
|
||||
- Project Codes: concepts/project_codes.md
|
||||
- Attachments: concepts/attachments.md
|
||||
|
|
@ -145,6 +147,7 @@ nav:
|
|||
- Stock Expiry: stock/expiry.md
|
||||
- Stock Ownership: stock/owner.md
|
||||
- Test Results: stock/test.md
|
||||
- Transfer Orders: stock/transfer_order.md
|
||||
- Manufacturing:
|
||||
- Manufacturing: manufacturing/index.md
|
||||
- Bill of Materials: manufacturing/bom.md
|
||||
|
|
@ -185,8 +188,6 @@ nav:
|
|||
- Multi Factor Authentication: settings/MFA.md
|
||||
- Email Settings: settings/email.md
|
||||
- Experimental Features: settings/experimental.md
|
||||
- Export Data: settings/export.md
|
||||
- Import Data: settings/import.md
|
||||
- Operations:
|
||||
- Background Tasks: settings/tasks.md
|
||||
- Error Logs: settings/logs.md
|
||||
|
|
|
|||
|
|
@ -227,9 +227,9 @@ httpx==0.28.1 \
|
|||
--hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \
|
||||
--hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad
|
||||
# via neoteroi-mkdocs
|
||||
idna==3.13 \
|
||||
--hash=sha256:585ea8fe5d69b9181ec1afba340451fba6ba764af97026f92a91d4eef164a242 \
|
||||
--hash=sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3
|
||||
idna==3.15 \
|
||||
--hash=sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8 \
|
||||
--hash=sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc
|
||||
# via
|
||||
# -c src/backend/requirements.txt
|
||||
# anyio
|
||||
|
|
@ -480,9 +480,9 @@ pygments==2.20.0 \
|
|||
# via
|
||||
# mkdocs-material
|
||||
# rich
|
||||
pymdown-extensions==10.21.2 \
|
||||
--hash=sha256:5c0fd2a2bea14eb39af8ff284f1066d898ab2187d81b889b75d46d4348c01638 \
|
||||
--hash=sha256:c3f55a5b8a1d0edf6699e35dcbea71d978d34ff3fa79f3d807b8a5b3fa90fbdc
|
||||
pymdown-extensions==10.21.3 \
|
||||
--hash=sha256:72cfcf55f07aea0d4af2c4f11dd4e52466ddfb1bb819673146398e0bd3a77354 \
|
||||
--hash=sha256:d7a5d08014fc571e80ca21dd6f854e31f94c489800350564d55d15b3c41e76b6
|
||||
# via
|
||||
# mkdocs-material
|
||||
# mkdocs-mermaid2-plugin
|
||||
|
|
|
|||
|
|
@ -120,6 +120,7 @@ possibly-unbound-attribute="ignore" # 21
|
|||
[tool.coverage.run]
|
||||
source = ["src/backend/InvenTree", "InvenTree"]
|
||||
dynamic_context = "test_function"
|
||||
omit = ["*/test_migrations.py"]
|
||||
|
||||
[tool.coverage.html]
|
||||
show_contexts = true
|
||||
|
|
|
|||
|
|
@ -1,11 +1,34 @@
|
|||
"""InvenTree API version information."""
|
||||
|
||||
# InvenTree API version
|
||||
INVENTREE_API_VERSION = 487
|
||||
INVENTREE_API_VERSION = 494
|
||||
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
|
||||
|
||||
INVENTREE_API_TEXT = """
|
||||
|
||||
v494 -> 2026-05-23 : https://github.com/inventree/InvenTree/pull/11990
|
||||
- Offload build output operations to a background task, and return a task ID which can be used to monitor the progress of the task
|
||||
|
||||
v493 -> 2026-05-22 : https://github.com/inventree/InvenTree/pull/11961
|
||||
- Adds "thumbnail" field to the Attachment API endpoint, which provides a URL to a thumbnail image for image attachments (if available)
|
||||
|
||||
v492 -> 2026-05-22 : https://github.com/inventree/InvenTree/pull/11281
|
||||
- Add Transfer Order model and associated API endpoint
|
||||
|
||||
v491 -> 2026-05-21 : https://github.com/inventree/InvenTree/pull/11979
|
||||
- Add API serializer for deleting a part category
|
||||
- Add API serializer for deleting a stock location
|
||||
|
||||
v490 -> 2026-05-19 : https://github.com/inventree/InvenTree/pull/11963
|
||||
- Moves user-self-filtered endpoints to /user/me/ to make their security boundaries clearer
|
||||
|
||||
v489 -> 2026-05-18 : https://github.com/inventree/InvenTree/pull/11962
|
||||
- Removes the "remote_image" field from the Part API endpoint
|
||||
- Removes the "remote_image" field from the Company API endpoint
|
||||
|
||||
v488 -> 2026-05-17 : https://github.com/inventree/InvenTree/pull/11920
|
||||
- Allow renaming of attachments after upload via the API
|
||||
|
||||
v487 -> 2026-05-15 : https://github.com/inventree/InvenTree/pull/11948
|
||||
- Make SelectionList default nullable
|
||||
- Add icon to TreePath schema
|
||||
|
|
|
|||
|
|
@ -120,7 +120,12 @@ def validate_url_no_ssrf(url):
|
|||
raise ValueError(_('URL points to a private or reserved IP address'))
|
||||
|
||||
|
||||
def download_image_from_url(remote_url, timeout=2.5):
|
||||
def download_image_from_url(
|
||||
remote_url: str,
|
||||
timeout: float = 2.5,
|
||||
user_agent: str = '',
|
||||
max_size: Optional[int] = None,
|
||||
):
|
||||
"""Download an image file from a remote URL.
|
||||
|
||||
This is a potentially dangerous operation, so we must perform some checks:
|
||||
|
|
@ -130,8 +135,9 @@ def download_image_from_url(remote_url, timeout=2.5):
|
|||
|
||||
Arguments:
|
||||
remote_url: The remote URL to retrieve image
|
||||
max_size: Maximum allowed image size (default = 1MB)
|
||||
timeout: Connection timeout in seconds (default = 5)
|
||||
user_agent: User-Agent string to use for the request (optional)
|
||||
max_size: Maximum allowed image size (in bytes) (default = 1MB)
|
||||
|
||||
Returns:
|
||||
An in-memory PIL image file, if the download was successful
|
||||
|
|
@ -151,13 +157,9 @@ def download_image_from_url(remote_url, timeout=2.5):
|
|||
validate_url_no_ssrf(remote_url)
|
||||
|
||||
# Calculate maximum allowable image size (in bytes)
|
||||
max_size = (
|
||||
int(get_global_setting('INVENTREE_DOWNLOAD_IMAGE_MAX_SIZE')) * 1024 * 1024
|
||||
)
|
||||
max_size = max_size or 1 * 1024 * 1024 # Default to 1MB if not provided
|
||||
|
||||
# Add user specified user-agent to request (if specified)
|
||||
user_agent = get_global_setting('INVENTREE_DOWNLOAD_FROM_URL_USER_AGENT')
|
||||
|
||||
headers = {'User-Agent': user_agent} if user_agent else None
|
||||
|
||||
try:
|
||||
|
|
|
|||
|
|
@ -661,7 +661,9 @@ class InvenTreeAttachmentMixin(InvenTreePermissionCheckMixin):
|
|||
|
||||
Before deleting the model instance, delete any associated attachments.
|
||||
"""
|
||||
self.attachments.all().delete()
|
||||
for attachment in list(self.attachments.all()):
|
||||
attachment.delete()
|
||||
|
||||
super().delete(*args, **kwargs)
|
||||
|
||||
@property
|
||||
|
|
|
|||
|
|
@ -37,7 +37,9 @@ def isAppLoaded(app_name: str) -> bool:
|
|||
|
||||
def isInTestMode():
|
||||
"""Returns True if the database is in testing mode."""
|
||||
return 'test' in sys.argv or sys.argv[0].endswith('pytest')
|
||||
return any(x in sys.argv for x in ['test', 'pytest']) or sys.argv[0].endswith(
|
||||
'pytest'
|
||||
)
|
||||
|
||||
|
||||
def isWaitingForDatabase():
|
||||
|
|
|
|||
|
|
@ -341,3 +341,24 @@ def schema_for_view_output_options(view_class):
|
|||
view_class
|
||||
)
|
||||
return extended_view
|
||||
|
||||
|
||||
def exclude_from_schema(klass: type, alternative_path: str) -> type:
|
||||
"""Decorator to exclude a view from the OpenAPI schema.
|
||||
|
||||
This is used to hide legacy endpoints from the schema, while still retaining them for backwards compatibility.
|
||||
"""
|
||||
|
||||
class LegacyView(klass):
|
||||
"""Dummy doc."""
|
||||
|
||||
LegacyView.__name__ = klass.__name__ + ' - Legacy'
|
||||
LegacyView.__doc__ = f'This is a legacy endpoint, retained for backwards compatibility. Consider migrating to the new endpoint under {alternative_path}.'
|
||||
|
||||
# Exclude all default operations from the schema
|
||||
for operation in ['get', 'post', 'put', 'patch', 'delete']:
|
||||
if hasattr(klass, operation):
|
||||
LegacyView = extend_schema_view(**{operation: extend_schema(exclude=True)})(
|
||||
LegacyView
|
||||
)
|
||||
return LegacyView
|
||||
|
|
|
|||
|
|
@ -26,7 +26,6 @@ from rest_framework.serializers import DecimalField, Serializer
|
|||
from rest_framework.utils import model_meta
|
||||
from taggit.serializers import TaggitSerializer
|
||||
|
||||
import common.models as common_models
|
||||
import InvenTree.ready
|
||||
from common.currency import currency_code_default, currency_code_mappings
|
||||
from InvenTree.fields import InvenTreeRestURLField, InvenTreeURLField
|
||||
|
|
@ -785,51 +784,6 @@ class NotesFieldMixin:
|
|||
self.fields.pop('notes', None)
|
||||
|
||||
|
||||
class RemoteImageMixin(metaclass=serializers.SerializerMetaclass):
|
||||
"""Mixin class which allows downloading an 'image' from a remote URL.
|
||||
|
||||
Adds the optional, write-only `remote_image` field to the serializer
|
||||
"""
|
||||
|
||||
def skip_create_fields(self):
|
||||
"""Ensure the 'remote_image' field is skipped when creating a new instance."""
|
||||
return ['remote_image']
|
||||
|
||||
remote_image = serializers.URLField(
|
||||
required=False,
|
||||
allow_blank=True,
|
||||
write_only=True,
|
||||
label=_('Remote Image'),
|
||||
help_text=_('URL of remote image file'),
|
||||
)
|
||||
|
||||
def validate_remote_image(self, url):
|
||||
"""Perform custom validation for the remote image URL.
|
||||
|
||||
- Attempt to download the image and store it against this object instance
|
||||
- Catches and re-throws any errors
|
||||
"""
|
||||
from InvenTree.helpers_model import download_image_from_url
|
||||
|
||||
if not url:
|
||||
return
|
||||
|
||||
if not common_models.InvenTreeSetting.get_setting(
|
||||
'INVENTREE_DOWNLOAD_FROM_URL'
|
||||
):
|
||||
raise ValidationError(
|
||||
_('Downloading images from remote URL is not enabled')
|
||||
)
|
||||
|
||||
try:
|
||||
self.remote_image_file = download_image_from_url(url)
|
||||
except Exception:
|
||||
self.remote_image_file = None
|
||||
raise ValidationError(_('Failed to download image from remote URL'))
|
||||
|
||||
return url
|
||||
|
||||
|
||||
class ContentTypeField(serializers.ChoiceField):
|
||||
"""Serializer field which represents a ContentType as 'app_label.model_name'.
|
||||
|
||||
|
|
|
|||
|
|
@ -178,7 +178,7 @@ def check_existing_task(taskname, group: str, *args, **kwargs) -> Optional[str]:
|
|||
|
||||
# Iterate through all available tasks, with the most recent first
|
||||
for task in OrmQ.objects.all().order_by('-id'):
|
||||
if task.func() != taskname and task.task['func'] != taskname:
|
||||
if task.func() != taskname and task.task.get('func') != taskname:
|
||||
# Task does not match
|
||||
continue
|
||||
|
||||
|
|
|
|||
|
|
@ -738,21 +738,10 @@ class TestHelpers(TestCase):
|
|||
|
||||
large_img = 'https://github.com/inventree/InvenTree/raw/master/src/backend/InvenTree/InvenTree/static/img/paper_splash_large.jpg'
|
||||
|
||||
InvenTreeSetting.set_setting(
|
||||
'INVENTREE_DOWNLOAD_IMAGE_MAX_SIZE', 1, change_user=None
|
||||
)
|
||||
|
||||
# Attempt to download an image which is too large
|
||||
with self.assertRaises(ValueError):
|
||||
InvenTree.helpers_model.download_image_from_url(large_img, timeout=10)
|
||||
|
||||
# Increase allowable download size
|
||||
InvenTreeSetting.set_setting(
|
||||
'INVENTREE_DOWNLOAD_IMAGE_MAX_SIZE', 5, change_user=None
|
||||
)
|
||||
|
||||
# Download a valid image (should not throw an error)
|
||||
InvenTree.helpers_model.download_image_from_url(large_img, timeout=10)
|
||||
InvenTree.helpers_model.download_image_from_url(
|
||||
large_img, timeout=10, max_size=10 * 1024 * 1024
|
||||
)
|
||||
|
||||
def test_model_mixin(self):
|
||||
"""Test the getModelsWithMixin function."""
|
||||
|
|
|
|||
|
|
@ -735,14 +735,81 @@ class BuildOutputScrap(BuildOrderContextMixin, CreateAPI):
|
|||
ctx['to_complete'] = False
|
||||
return ctx
|
||||
|
||||
@extend_schema(responses={200: common.serializers.TaskDetailSerializer})
|
||||
def post(self, *args, **kwargs):
|
||||
"""Override POST to offload scrapping to the background worker."""
|
||||
from build.tasks import scrap_build_outputs
|
||||
from InvenTree.tasks import offload_task
|
||||
|
||||
build = self.get_build()
|
||||
serializer = self.get_serializer(data=self.request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
data = serializer.validated_data
|
||||
|
||||
task_id = offload_task(
|
||||
scrap_build_outputs,
|
||||
build.pk,
|
||||
outputs=[
|
||||
{
|
||||
'output_id': item['output'].pk,
|
||||
'quantity': float(item['quantity'])
|
||||
if item.get('quantity') is not None
|
||||
else None,
|
||||
}
|
||||
for item in data['outputs']
|
||||
],
|
||||
location_id=data['location'].pk,
|
||||
notes=data.get('notes', ''),
|
||||
discard_allocations=data.get('discard_allocations', False),
|
||||
user_id=self.request.user.pk,
|
||||
group='build',
|
||||
)
|
||||
|
||||
response = common.serializers.TaskDetailSerializer.from_task(task_id).data
|
||||
return Response(response, status=response['http_status'])
|
||||
|
||||
|
||||
class BuildOutputComplete(BuildOrderContextMixin, CreateAPI):
|
||||
"""API endpoint for completing build outputs."""
|
||||
|
||||
queryset = Build.objects.none()
|
||||
|
||||
serializer_class = build.serializers.BuildOutputCompleteSerializer
|
||||
|
||||
@extend_schema(responses={200: common.serializers.TaskDetailSerializer})
|
||||
def post(self, *args, **kwargs):
|
||||
"""Override POST to offload build output completion to the background worker."""
|
||||
from build.tasks import complete_build_outputs
|
||||
from InvenTree.tasks import offload_task
|
||||
|
||||
build = self.get_build()
|
||||
serializer = self.get_serializer(data=self.request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
data = serializer.validated_data
|
||||
|
||||
location = data.get('location')
|
||||
|
||||
task_id = offload_task(
|
||||
complete_build_outputs,
|
||||
build.pk,
|
||||
outputs=[
|
||||
{
|
||||
'output_id': item['output'].pk,
|
||||
'quantity': float(item['quantity'])
|
||||
if item.get('quantity') is not None
|
||||
else None,
|
||||
}
|
||||
for item in data['outputs']
|
||||
],
|
||||
location_id=location.pk if location else None,
|
||||
status=data.get('status_custom_key'),
|
||||
notes=data.get('notes', ''),
|
||||
user_id=self.request.user.pk,
|
||||
group='build',
|
||||
)
|
||||
|
||||
response = common.serializers.TaskDetailSerializer.from_task(task_id).data
|
||||
return Response(response, status=response['http_status'])
|
||||
|
||||
|
||||
class BuildOutputDelete(BuildOrderContextMixin, CreateAPI):
|
||||
"""API endpoint for deleting multiple build outputs."""
|
||||
|
|
@ -750,15 +817,33 @@ class BuildOutputDelete(BuildOrderContextMixin, CreateAPI):
|
|||
def get_serializer_context(self):
|
||||
"""Add extra context information to the endpoint serializer."""
|
||||
ctx = super().get_serializer_context()
|
||||
|
||||
ctx['to_complete'] = False
|
||||
|
||||
return ctx
|
||||
|
||||
queryset = Build.objects.none()
|
||||
|
||||
serializer_class = build.serializers.BuildOutputDeleteSerializer
|
||||
|
||||
@extend_schema(responses={200: common.serializers.TaskDetailSerializer})
|
||||
def post(self, *args, **kwargs):
|
||||
"""Override POST to offload build output deletion to the background worker."""
|
||||
from build.tasks import delete_build_outputs
|
||||
from InvenTree.tasks import offload_task
|
||||
|
||||
build = self.get_build()
|
||||
serializer = self.get_serializer(data=self.request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
data = serializer.validated_data
|
||||
|
||||
task_id = offload_task(
|
||||
delete_build_outputs,
|
||||
build.pk,
|
||||
output_ids=[item['output'].pk for item in data['outputs']],
|
||||
group='build',
|
||||
)
|
||||
|
||||
response = common.serializers.TaskDetailSerializer.from_task(task_id).data
|
||||
return Response(response, status=response['http_status'])
|
||||
|
||||
|
||||
class BuildFinish(BuildOrderContextMixin, CreateAPI):
|
||||
"""API endpoint for marking a build as finished (completed)."""
|
||||
|
|
|
|||
|
|
@ -37,7 +37,6 @@ from build.validators import (
|
|||
validate_build_order_reference,
|
||||
)
|
||||
from common.models import ProjectCode
|
||||
from common.notifications import InvenTreeNotificationBodies, trigger_notification
|
||||
from common.settings import (
|
||||
get_global_setting,
|
||||
prevent_build_output_complete_on_incompleted_tests,
|
||||
|
|
@ -651,7 +650,6 @@ class Build(
|
|||
|
||||
return self.is_fully_allocated(tracked=False)
|
||||
|
||||
@transaction.atomic
|
||||
def complete_allocations(self, user) -> None:
|
||||
"""Complete all stock allocations for this build order.
|
||||
|
||||
|
|
@ -662,7 +660,7 @@ class Build(
|
|||
|
||||
# Ensure that there are no longer any BuildItem objects
|
||||
# which point to this Build Order
|
||||
self.allocated_stock.delete()
|
||||
self.allocated_stock.all().delete()
|
||||
|
||||
@transaction.atomic
|
||||
def complete_build(self, user: User, trim_allocated_stock: bool = False):
|
||||
|
|
@ -702,66 +700,20 @@ class Build(
|
|||
_('Cannot complete build order with incomplete outputs')
|
||||
)
|
||||
|
||||
if trim_allocated_stock:
|
||||
self.trim_allocated_stock()
|
||||
# Offload background task to complete build allocations
|
||||
InvenTree.tasks.offload_task(
|
||||
build.tasks.complete_build,
|
||||
self.pk,
|
||||
user.pk if user else None,
|
||||
trim_allocated_stock=trim_allocated_stock,
|
||||
group='build',
|
||||
)
|
||||
|
||||
self.completion_date = InvenTree.helpers.current_date()
|
||||
self.completed_by = user
|
||||
self.status = BuildStatus.COMPLETE.value
|
||||
self.save()
|
||||
|
||||
# Offload task to complete build allocations
|
||||
if not InvenTree.tasks.offload_task(
|
||||
build.tasks.complete_build_allocations,
|
||||
self.pk,
|
||||
user.pk if user else None,
|
||||
group='build',
|
||||
):
|
||||
raise ValidationError(
|
||||
_('Failed to offload task to complete build allocations')
|
||||
)
|
||||
|
||||
# Register an event
|
||||
trigger_event(BuildEvents.COMPLETED, id=self.pk)
|
||||
|
||||
# Notify users that this build has been completed
|
||||
targets = [self.issued_by, self.responsible]
|
||||
|
||||
# Also inform anyone subscribed to the assembly part
|
||||
targets.extend(self.part.get_subscribers())
|
||||
|
||||
# Notify those users interested in the parent build
|
||||
if self.parent:
|
||||
targets.append(self.parent.issued_by)
|
||||
targets.append(self.parent.responsible)
|
||||
|
||||
# Notify users if this build points to a sales order
|
||||
if self.sales_order:
|
||||
targets.append(self.sales_order.created_by)
|
||||
targets.append(self.sales_order.responsible)
|
||||
|
||||
build = self
|
||||
name = _(f'Build order {build} has been completed')
|
||||
|
||||
context = {
|
||||
'build': build,
|
||||
'name': name,
|
||||
'slug': 'build.completed',
|
||||
'message': _('A build order has been completed'),
|
||||
'link': InvenTree.helpers_model.construct_absolute_url(
|
||||
self.get_absolute_url()
|
||||
),
|
||||
'template': {'html': 'email/build_order_completed.html', 'subject': name},
|
||||
}
|
||||
|
||||
trigger_notification(
|
||||
build,
|
||||
'build.completed',
|
||||
targets=targets,
|
||||
context=context,
|
||||
target_exclude=[user],
|
||||
)
|
||||
|
||||
@transaction.atomic
|
||||
def issue_build(self):
|
||||
"""Mark the Build as IN PRODUCTION.
|
||||
|
|
@ -839,26 +791,15 @@ class Build(
|
|||
remove_allocated_stock = kwargs.get('remove_allocated_stock', False)
|
||||
remove_incomplete_outputs = kwargs.get('remove_incomplete_outputs', False)
|
||||
|
||||
if remove_allocated_stock:
|
||||
# Offload task to remove allocated stock
|
||||
if not InvenTree.tasks.offload_task(
|
||||
build.tasks.complete_build_allocations,
|
||||
self.pk,
|
||||
user.pk if user else None,
|
||||
group='build',
|
||||
):
|
||||
raise ValidationError(
|
||||
_('Failed to offload task to complete build allocations')
|
||||
)
|
||||
|
||||
else:
|
||||
self.allocated_stock.all().delete()
|
||||
|
||||
# Remove incomplete outputs (if required)
|
||||
if remove_incomplete_outputs:
|
||||
outputs = self.build_outputs.filter(is_building=True)
|
||||
|
||||
outputs.delete()
|
||||
# Offload background task to take care of the expensive operations
|
||||
InvenTree.tasks.offload_task(
|
||||
build.tasks.cancel_build,
|
||||
self.pk,
|
||||
user.pk if user else None,
|
||||
remove_allocated_stock=remove_allocated_stock,
|
||||
remove_incomplete_outputs=remove_incomplete_outputs,
|
||||
group='build',
|
||||
)
|
||||
|
||||
# Date of 'completion' is the date the build was cancelled
|
||||
self.completion_date = InvenTree.helpers.current_date()
|
||||
|
|
@ -867,17 +808,6 @@ class Build(
|
|||
self.status = BuildStatus.CANCELLED.value
|
||||
self.save()
|
||||
|
||||
# Notify users that the order has been canceled
|
||||
InvenTree.helpers_model.notify_responsible(
|
||||
self,
|
||||
Build,
|
||||
exclude=self.issued_by,
|
||||
content=InvenTreeNotificationBodies.OrderCanceled,
|
||||
extra_users=self.part.get_subscribers(),
|
||||
)
|
||||
|
||||
trigger_event(BuildEvents.CANCELLED, id=self.pk)
|
||||
|
||||
@transaction.atomic
|
||||
def deallocate_stock(self, build_line=None, output=None):
|
||||
"""Deallocate stock from this Build.
|
||||
|
|
@ -1083,7 +1013,6 @@ class Build(
|
|||
"""Returns a QuerySet object of all BuildItem objects which point back to this Build."""
|
||||
return BuildItem.objects.filter(build_line__build=self)
|
||||
|
||||
@transaction.atomic
|
||||
def subtract_allocated_stock(self, user) -> None:
|
||||
"""Removes the allocated untracked items from stock."""
|
||||
# Find all BuildItem objects which point to this build
|
||||
|
|
|
|||
|
|
@ -462,18 +462,6 @@ class BuildOutputDeleteSerializer(serializers.Serializer):
|
|||
|
||||
return data
|
||||
|
||||
def save(self):
|
||||
"""'save' the serializer to delete the build outputs."""
|
||||
data = self.validated_data
|
||||
outputs = data.get('outputs', [])
|
||||
|
||||
build = self.context['build']
|
||||
|
||||
with transaction.atomic():
|
||||
for item in outputs:
|
||||
output = item['output']
|
||||
build.delete_output(output)
|
||||
|
||||
|
||||
class BuildOutputScrapSerializer(serializers.Serializer):
|
||||
"""Scrapping one or more build outputs."""
|
||||
|
|
@ -518,27 +506,6 @@ class BuildOutputScrapSerializer(serializers.Serializer):
|
|||
|
||||
return data
|
||||
|
||||
def save(self):
|
||||
"""Save the serializer to scrap the build outputs."""
|
||||
build = self.context['build']
|
||||
request = self.context.get('request')
|
||||
data = self.validated_data
|
||||
outputs = data.get('outputs', [])
|
||||
|
||||
# Scrap the build outputs
|
||||
with transaction.atomic():
|
||||
for item in outputs:
|
||||
output = item['output']
|
||||
quantity = item.get('quantity', None)
|
||||
build.scrap_build_output(
|
||||
output,
|
||||
quantity,
|
||||
data.get('location', None),
|
||||
user=request.user if request else None,
|
||||
notes=data.get('notes', ''),
|
||||
discard_allocations=data.get('discard_allocations', False),
|
||||
)
|
||||
|
||||
|
||||
class BuildOutputCompleteSerializer(serializers.Serializer):
|
||||
"""DRF serializer for completing one or more build outputs."""
|
||||
|
|
@ -610,42 +577,6 @@ class BuildOutputCompleteSerializer(serializers.Serializer):
|
|||
|
||||
return data
|
||||
|
||||
def save(self):
|
||||
"""Save the serializer to complete the build outputs."""
|
||||
build = self.context['build']
|
||||
request = self.context.get('request')
|
||||
|
||||
data = self.validated_data
|
||||
|
||||
location = data.get('location', None)
|
||||
status = data.get('status_custom_key', StockStatus.OK.value)
|
||||
notes = data.get('notes', '')
|
||||
|
||||
outputs = data.get('outputs', [])
|
||||
|
||||
# Cache some calculated values which can be passed to each output
|
||||
required_tests = outputs[0]['output'].part.getRequiredTests()
|
||||
prevent_on_incomplete = (
|
||||
common.settings.prevent_build_output_complete_on_incompleted_tests()
|
||||
)
|
||||
|
||||
# Mark the specified build outputs as "complete"
|
||||
with transaction.atomic():
|
||||
for item in outputs:
|
||||
output = item['output']
|
||||
quantity = item.get('quantity', None)
|
||||
|
||||
build.complete_build_output(
|
||||
output,
|
||||
request.user if request else None,
|
||||
quantity=quantity,
|
||||
location=location,
|
||||
status=status,
|
||||
notes=notes,
|
||||
required_tests=required_tests,
|
||||
prevent_on_incomplete=prevent_on_incomplete,
|
||||
)
|
||||
|
||||
|
||||
class BuildIssueSerializer(serializers.Serializer):
|
||||
"""DRF serializer for issuing a build order."""
|
||||
|
|
|
|||
|
|
@ -100,6 +100,214 @@ def complete_build_allocations(build_id: int, user_id: int):
|
|||
build_order.complete_allocations(user)
|
||||
|
||||
|
||||
@tracer.start_as_current_span('delete_build_outputs')
|
||||
def delete_build_outputs(build_id: int, output_ids: list, **kwargs):
|
||||
"""Delete (cancel) specified build outputs for a BuildOrder.
|
||||
|
||||
Arguments:
|
||||
build_id: The ID of the BuildOrder
|
||||
output_ids: List of StockItem PKs to delete
|
||||
"""
|
||||
from build.models import Build
|
||||
from stock.models import StockItem
|
||||
|
||||
build = Build.objects.get(pk=build_id)
|
||||
|
||||
with transaction.atomic():
|
||||
for output_id in output_ids:
|
||||
output = StockItem.objects.filter(pk=output_id).first()
|
||||
if output:
|
||||
build.delete_output(output)
|
||||
|
||||
|
||||
@tracer.start_as_current_span('scrap_build_outputs')
|
||||
def scrap_build_outputs(
|
||||
build_id: int,
|
||||
outputs: list,
|
||||
location_id: int,
|
||||
notes: str = '',
|
||||
discard_allocations: bool = False,
|
||||
user_id: int | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
"""Scrap specified build outputs for a BuildOrder.
|
||||
|
||||
Arguments:
|
||||
build_id: The ID of the BuildOrder
|
||||
outputs: List of dicts with 'output_id' and 'quantity'
|
||||
location_id: PK of the destination StockLocation
|
||||
notes: Reason for scrapping
|
||||
discard_allocations: If True, discard (not consume) allocations
|
||||
user_id: PK of the user initiating the action
|
||||
"""
|
||||
from build.models import Build
|
||||
from stock.models import StockItem, StockLocation
|
||||
|
||||
build = Build.objects.get(pk=build_id)
|
||||
location = StockLocation.objects.get(pk=location_id)
|
||||
user = User.objects.filter(pk=user_id).first() if user_id else None
|
||||
|
||||
with transaction.atomic():
|
||||
for item in outputs:
|
||||
output = StockItem.objects.filter(pk=item['output_id']).first()
|
||||
if output:
|
||||
build.scrap_build_output(
|
||||
output,
|
||||
item.get('quantity'),
|
||||
location,
|
||||
user=user,
|
||||
notes=notes,
|
||||
discard_allocations=discard_allocations,
|
||||
)
|
||||
|
||||
|
||||
@tracer.start_as_current_span('complete_build_outputs')
|
||||
def complete_build_outputs(
|
||||
build_id: int,
|
||||
outputs: list,
|
||||
location_id: int | None,
|
||||
status: int,
|
||||
notes: str = '',
|
||||
user_id: int | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
"""Complete specified build outputs for a BuildOrder.
|
||||
|
||||
Arguments:
|
||||
build_id: The ID of the BuildOrder
|
||||
outputs: List of dicts with 'output_id' and optional 'quantity'
|
||||
location_id: PK of the destination StockLocation (or None)
|
||||
status: Stock status code to assign to completed outputs
|
||||
notes: Completion notes
|
||||
user_id: PK of the user initiating the action
|
||||
"""
|
||||
from build.models import Build
|
||||
from stock.models import StockItem, StockLocation
|
||||
|
||||
build = Build.objects.get(pk=build_id)
|
||||
location = (
|
||||
StockLocation.objects.filter(pk=location_id).first() if location_id else None
|
||||
)
|
||||
user = User.objects.filter(pk=user_id).first() if user_id else None
|
||||
|
||||
required_tests = build.part.getRequiredTests()
|
||||
|
||||
with transaction.atomic():
|
||||
for item in outputs:
|
||||
output = StockItem.objects.filter(pk=item['output_id']).first()
|
||||
if output:
|
||||
build.complete_build_output(
|
||||
output,
|
||||
user,
|
||||
quantity=item.get('quantity'),
|
||||
location=location,
|
||||
status=status,
|
||||
notes=notes,
|
||||
required_tests=required_tests,
|
||||
)
|
||||
|
||||
|
||||
@tracer.start_as_current_span('cancel_build')
|
||||
def cancel_build(
|
||||
build_id: int,
|
||||
user_id: int,
|
||||
remove_allocated_stock: bool = False,
|
||||
remove_incomplete_outputs: bool = False,
|
||||
):
|
||||
"""Tasks to run after a BuildOrder is cancelled.
|
||||
|
||||
Arguments:
|
||||
build_id: The ID of the BuildOrder which has been cancelled
|
||||
user_id: The ID of the user who cancelled the BuildOrder
|
||||
remove_allocated_stock: If True, consume any allocated stock
|
||||
remove_incomplete_outputs: If True, delete any incomplete build outputs
|
||||
|
||||
"""
|
||||
from build.models import Build
|
||||
|
||||
build = Build.objects.get(pk=build_id)
|
||||
|
||||
if remove_allocated_stock:
|
||||
complete_build_allocations(build_id, user_id)
|
||||
else:
|
||||
build.allocated_stock.all().delete()
|
||||
|
||||
if remove_incomplete_outputs:
|
||||
build.build_outputs.filter(is_building=True).delete()
|
||||
|
||||
# Notify users that the order has been canceled
|
||||
InvenTree.helpers_model.notify_responsible(
|
||||
build,
|
||||
Build,
|
||||
exclude=build.issued_by,
|
||||
content=common.notifications.InvenTreeNotificationBodies.OrderCanceled,
|
||||
extra_users=build.part.get_subscribers(),
|
||||
)
|
||||
|
||||
trigger_event(BuildEvents.CANCELLED, id=build.pk)
|
||||
|
||||
|
||||
@tracer.start_as_current_span('complete_build')
|
||||
def complete_build(build_id: int, user_id: int, trim_allocated_stock: bool = False):
|
||||
"""Tasks to run after a BuildOrder is completed.
|
||||
|
||||
Arguments:
|
||||
build_id: The ID of the BuildOrder which has been completed
|
||||
user_id: The ID of the user who completed the BuildOrder
|
||||
trim_allocated_stock: If True, trim any allocated stock which was not consumed
|
||||
"""
|
||||
from build.models import Build
|
||||
|
||||
build = Build.objects.get(pk=build_id)
|
||||
user = User.objects.filter(pk=user_id).first() if user_id else None
|
||||
|
||||
if trim_allocated_stock:
|
||||
build.trim_allocated_stock()
|
||||
|
||||
# Complete any remaining allocations for this build order
|
||||
complete_build_allocations(build_id, user_id)
|
||||
|
||||
# Register an event
|
||||
trigger_event(BuildEvents.COMPLETED, id=build.pk)
|
||||
|
||||
# Notify users that this build has been completed
|
||||
targets = [build.issued_by, build.responsible]
|
||||
|
||||
# Also inform anyone subscribed to the assembly part
|
||||
targets.extend(build.part.get_subscribers())
|
||||
|
||||
# Notify those users interested in the parent build
|
||||
if build.parent:
|
||||
targets.append(build.parent.issued_by)
|
||||
targets.append(build.parent.responsible)
|
||||
|
||||
# Notify users if this build points to a sales order
|
||||
if build.sales_order:
|
||||
targets.append(build.sales_order.created_by)
|
||||
targets.append(build.sales_order.responsible)
|
||||
|
||||
name = _(f'Build order {build} has been completed')
|
||||
|
||||
context = {
|
||||
'build': build,
|
||||
'name': name,
|
||||
'slug': 'build.completed',
|
||||
'message': _('A build order has been completed'),
|
||||
'link': InvenTree.helpers_model.construct_absolute_url(
|
||||
build.get_absolute_url()
|
||||
),
|
||||
'template': {'html': 'email/build_order_completed.html', 'subject': name},
|
||||
}
|
||||
|
||||
common.notifications.trigger_notification(
|
||||
build,
|
||||
'build.completed',
|
||||
targets=targets,
|
||||
context=context,
|
||||
target_exclude=[user],
|
||||
)
|
||||
|
||||
|
||||
@tracer.start_as_current_span('update_build_order_lines')
|
||||
def update_build_order_lines(bom_item_pk: int):
|
||||
"""Update all BuildOrderLineItem objects which reference a particular BomItem.
|
||||
|
|
|
|||
|
|
@ -155,7 +155,7 @@ class BuildTest(BuildAPITest):
|
|||
self.post(
|
||||
reverse('api-build-output-complete', kwargs={'pk': 99999}),
|
||||
{},
|
||||
expected_code=400,
|
||||
expected_code=404,
|
||||
)
|
||||
|
||||
data = self.post(self.url, {}, expected_code=400).data
|
||||
|
|
@ -226,8 +226,8 @@ class BuildTest(BuildAPITest):
|
|||
'location': 1,
|
||||
'status': StockStatus.ATTENTION.value,
|
||||
},
|
||||
expected_code=201,
|
||||
max_query_count=400,
|
||||
expected_code=200,
|
||||
max_query_count=450,
|
||||
)
|
||||
|
||||
self.assertEqual(self.build.incomplete_outputs.count(), 0)
|
||||
|
|
@ -446,7 +446,7 @@ class BuildTest(BuildAPITest):
|
|||
self.post(
|
||||
delete_url,
|
||||
{'outputs': [{'output': output.pk} for output in outputs[1:3]]},
|
||||
expected_code=201,
|
||||
expected_code=200,
|
||||
)
|
||||
|
||||
# Two build outputs have been removed
|
||||
|
|
@ -473,7 +473,7 @@ class BuildTest(BuildAPITest):
|
|||
'outputs': [{'output': output.pk} for output in outputs[3:]],
|
||||
'location': 4,
|
||||
},
|
||||
expected_code=201,
|
||||
expected_code=200,
|
||||
)
|
||||
|
||||
# Check that the outputs have been completed
|
||||
|
|
@ -1353,7 +1353,7 @@ class BuildOutputCreateTest(BuildAPITest):
|
|||
url, data={'quantity': 5, 'serial_numbers': '1,2,3-5'}, expected_code=201
|
||||
)
|
||||
|
||||
# Build outputs have incdeased
|
||||
# Build outputs have increased
|
||||
self.assertEqual(n_outputs + 5, build.output_count)
|
||||
|
||||
# Stock items have increased
|
||||
|
|
@ -1466,7 +1466,7 @@ class BuildOutputScrapTest(BuildAPITest):
|
|||
'location': 1,
|
||||
'notes': 'Should succeed',
|
||||
},
|
||||
expected_code=201,
|
||||
expected_code=200,
|
||||
)
|
||||
|
||||
# There should still be three outputs associated with this build
|
||||
|
|
@ -1534,7 +1534,7 @@ class BuildOutputScrapTest(BuildAPITest):
|
|||
|
||||
# Partially complete the output (with a valid quantity)
|
||||
data['outputs'][0]['quantity'] = 4
|
||||
self.post(url, data, expected_code=201)
|
||||
self.post(url, data, expected_code=200)
|
||||
|
||||
build.refresh_from_db()
|
||||
output.refresh_from_db()
|
||||
|
|
@ -1571,13 +1571,22 @@ class BuildOutputCancelTest(BuildAPITest):
|
|||
set_global_setting('STOCK_ALLOW_DELETE_SERIALIZED', True)
|
||||
url = reverse('api-build-output-delete', kwargs={'pk': build.pk})
|
||||
|
||||
self.post(url, data={'outputs': [{'output': output_ids[0]}]}, expected_code=201)
|
||||
self.post(url, data={'outputs': [{'output': output_ids[0]}]}, expected_code=200)
|
||||
|
||||
# Prevent deletion of serialized stock items, and try again
|
||||
# Note that this should still succeed, independent of the global setting
|
||||
set_global_setting('STOCK_ALLOW_DELETE_SERIALIZED', False)
|
||||
|
||||
self.post(url, data={'outputs': [{'output': output_ids[1]}]}, expected_code=201)
|
||||
response = self.post(
|
||||
url, data={'outputs': [{'output': output_ids[1]}]}, expected_code=200
|
||||
)
|
||||
|
||||
# Response should be the task info - the cancellation is performed asynchronously
|
||||
self.assertIn('task_id', response.data)
|
||||
self.assertFalse(response.data['exists'])
|
||||
self.assertFalse(response.data['pending'])
|
||||
self.assertTrue(response.data['complete'])
|
||||
self.assertTrue(response.data['success'])
|
||||
|
||||
# The outputs should have been scrapped
|
||||
self.assertEqual(build.build_outputs.count(), N)
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ from InvenTree.unit_test import (
|
|||
from order.models import PurchaseOrder, PurchaseOrderLineItem
|
||||
from part.models import BomItem, BomItemSubstitute, Part, PartTestTemplate
|
||||
from stock.models import StockItem, StockItemTestResult, StockLocation
|
||||
from stock.status_codes import StockStatus
|
||||
from users.models import Owner
|
||||
|
||||
logger = structlog.get_logger('inventree')
|
||||
|
|
@ -557,14 +558,29 @@ class BuildTest(BuildTestBase):
|
|||
bo.clean()
|
||||
|
||||
def test_cancel(self):
|
||||
"""Test cancellation of the build."""
|
||||
# TODO
|
||||
"""
|
||||
self.allocate_stock(50, 50, 200, self.output_1)
|
||||
self.build.cancel_build(None)
|
||||
"""Test build cancellation: status is updated and allocations are removed by default."""
|
||||
self.build.issue_build()
|
||||
|
||||
self.assertEqual(BuildItem.objects.count(), 0)
|
||||
"""
|
||||
self.allocate_stock(None, {self.stock_1_2: 50})
|
||||
self.assertGreater(self.build.allocated_stock.count(), 0)
|
||||
|
||||
initial_output_count = self.build.build_outputs.filter(is_building=True).count()
|
||||
self.assertGreater(initial_output_count, 0)
|
||||
|
||||
self.build.cancel_build(None)
|
||||
self.build.refresh_from_db()
|
||||
|
||||
self.assertEqual(self.build.status, BuildStatus.CANCELLED)
|
||||
|
||||
# Allocations removed (but stock not consumed) by default
|
||||
self.assertEqual(self.build.allocated_stock.count(), 0)
|
||||
self.assertIsNone(StockItem.objects.get(pk=self.stock_1_2.pk).consumed_by)
|
||||
|
||||
# Incomplete outputs preserved by default (remove_incomplete_outputs=False)
|
||||
self.assertEqual(
|
||||
self.build.build_outputs.filter(is_building=True).count(),
|
||||
initial_output_count,
|
||||
)
|
||||
|
||||
def test_complete(self):
|
||||
"""Test completion of a build output."""
|
||||
|
|
@ -1107,3 +1123,276 @@ class ExternalBuildTest(InvenTreeAPITestCase):
|
|||
# Filter by 'not external'
|
||||
response = self.get(url, {'external': 'false'})
|
||||
self.assertEqual(len(response.data), 2)
|
||||
|
||||
|
||||
class BuildTaskTests(BuildTestBase):
|
||||
"""Direct unit tests for the background task functions in build/tasks.py.
|
||||
|
||||
These tests call task functions directly (synchronously) to verify the
|
||||
business logic they encapsulate, independently of the API and offload mechanism.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
"""Create a stock location available to all task tests."""
|
||||
super().setUp()
|
||||
self.location = StockLocation.objects.create(name='Task Test Location')
|
||||
|
||||
def allocate_stock(self, output, allocations):
|
||||
"""Create BuildItem allocations against self.build for the given output."""
|
||||
items_to_create = []
|
||||
for item, quantity in allocations.items():
|
||||
line = BuildLine.objects.filter(
|
||||
build=self.build, bom_item__sub_part=item.part
|
||||
).first()
|
||||
items_to_create.append(
|
||||
BuildItem(
|
||||
build_line=line,
|
||||
stock_item=item,
|
||||
quantity=quantity,
|
||||
install_into=output,
|
||||
)
|
||||
)
|
||||
BuildItem.objects.bulk_create(items_to_create)
|
||||
|
||||
def _setup_complete_build(self):
|
||||
"""Helper: allocate stock fully and complete all outputs so the build is ready to complete."""
|
||||
self.stock_1_1.quantity = 1000
|
||||
self.stock_1_1.save()
|
||||
self.stock_2_1.quantity = 30
|
||||
self.stock_2_1.save()
|
||||
|
||||
self.build.issue_build()
|
||||
|
||||
# Allocate untracked parts
|
||||
self.allocate_stock(
|
||||
None, {self.stock_1_1: 50, self.stock_1_2: 10, self.stock_2_1: 30}
|
||||
)
|
||||
# Allocate tracked parts to each output
|
||||
self.allocate_stock(self.output_1, {self.stock_3_1: 6})
|
||||
self.allocate_stock(self.output_2, {self.stock_3_1: 14})
|
||||
|
||||
self.build.complete_build_output(self.output_1, None)
|
||||
self.build.complete_build_output(self.output_2, None)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# cancel_build task
|
||||
# -----------------------------------------------------------------------
|
||||
|
||||
def test_cancel_task_discards_allocations(self):
|
||||
"""cancel_build with remove_allocated_stock=False: allocations deleted, stock not consumed."""
|
||||
self.build.issue_build()
|
||||
self.allocate_stock(None, {self.stock_1_2: 50})
|
||||
self.assertGreater(self.build.allocated_stock.count(), 0)
|
||||
|
||||
build.tasks.cancel_build(
|
||||
self.build.pk, self.user.pk, remove_allocated_stock=False
|
||||
)
|
||||
|
||||
# BuildItem rows gone
|
||||
self.assertEqual(self.build.allocated_stock.count(), 0)
|
||||
# Stock item was NOT consumed
|
||||
self.assertIsNone(StockItem.objects.get(pk=self.stock_1_2.pk).consumed_by)
|
||||
|
||||
def test_cancel_task_consumes_allocations(self):
|
||||
"""cancel_build with remove_allocated_stock=True: stock items are marked consumed."""
|
||||
self.build.issue_build()
|
||||
self.allocate_stock(None, {self.stock_1_2: 50})
|
||||
|
||||
build.tasks.cancel_build(
|
||||
self.build.pk, self.user.pk, remove_allocated_stock=True
|
||||
)
|
||||
|
||||
# All BuildItem rows gone
|
||||
self.assertEqual(self.build.allocated_stock.count(), 0)
|
||||
# The allocated (non-trackable) stock was consumed
|
||||
self.assertGreater(self.build.consumed_stock.count(), 0)
|
||||
|
||||
def test_cancel_task_removes_incomplete_outputs(self):
|
||||
"""cancel_build with remove_incomplete_outputs=True: in-progress outputs are deleted."""
|
||||
self.build.issue_build()
|
||||
initial_count = self.build.build_outputs.filter(is_building=True).count()
|
||||
self.assertGreater(initial_count, 0)
|
||||
|
||||
build.tasks.cancel_build(
|
||||
self.build.pk, self.user.pk, remove_incomplete_outputs=True
|
||||
)
|
||||
|
||||
self.assertEqual(self.build.build_outputs.filter(is_building=True).count(), 0)
|
||||
|
||||
def test_cancel_task_preserves_incomplete_outputs(self):
|
||||
"""cancel_build with remove_incomplete_outputs=False: in-progress outputs are kept."""
|
||||
self.build.issue_build()
|
||||
initial_count = self.build.build_outputs.filter(is_building=True).count()
|
||||
self.assertGreater(initial_count, 0)
|
||||
|
||||
build.tasks.cancel_build(
|
||||
self.build.pk, self.user.pk, remove_incomplete_outputs=False
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
self.build.build_outputs.filter(is_building=True).count(), initial_count
|
||||
)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# complete_build task
|
||||
# -----------------------------------------------------------------------
|
||||
|
||||
@override_settings(
|
||||
TESTING_TABLE_EVENTS=True,
|
||||
PLUGIN_TESTING_EVENTS=True,
|
||||
PLUGIN_TESTING_EVENTS_ASYNC=True,
|
||||
)
|
||||
def test_complete_build_task_triggers_event(self):
|
||||
"""complete_build task fires the BuildEvents.COMPLETED event."""
|
||||
from django_q.models import OrmQ
|
||||
|
||||
from build.events import BuildEvents
|
||||
|
||||
set_global_setting('ENABLE_PLUGINS_EVENTS', True)
|
||||
OrmQ.objects.all().delete()
|
||||
|
||||
self._setup_complete_build()
|
||||
self.build.complete_build(self.user)
|
||||
|
||||
task = findOffloadedEvent(BuildEvents.COMPLETED, matching_kwargs=['id'])
|
||||
self.assertIsNotNone(task)
|
||||
self.assertEqual(task.kwargs()['id'], self.build.pk)
|
||||
|
||||
set_global_setting('ENABLE_PLUGINS_EVENTS', False)
|
||||
|
||||
def test_complete_build_task_trim_stock(self):
|
||||
"""complete_build with trim_allocated_stock=True removes over-allocations before consuming."""
|
||||
self.stock_1_2.quantity = 100
|
||||
self.stock_1_2.save()
|
||||
self.stock_2_1.quantity = 30
|
||||
self.stock_2_1.save()
|
||||
|
||||
self.build.issue_build()
|
||||
|
||||
# Over-allocate sub_part_1: need 50, allocate 100
|
||||
self.allocate_stock(None, {self.stock_1_2: 100, self.stock_2_1: 30})
|
||||
self.allocate_stock(self.output_1, {self.stock_3_1: 6})
|
||||
self.allocate_stock(self.output_2, {self.stock_3_1: 14})
|
||||
|
||||
self.assertTrue(self.build.is_overallocated())
|
||||
|
||||
self.build.complete_build_output(self.output_1, None)
|
||||
self.build.complete_build_output(self.output_2, None)
|
||||
self.assertTrue(self.build.can_complete)
|
||||
|
||||
self.build.complete_build(self.user, trim_allocated_stock=True)
|
||||
self.build.refresh_from_db()
|
||||
self.assertEqual(self.build.status, BuildStatus.COMPLETE)
|
||||
|
||||
# Only 50 units of sub_part_1 should have been consumed (not 100)
|
||||
consumed_qty = StockItem.objects.filter(
|
||||
consumed_by=self.build, part=self.sub_part_1
|
||||
).aggregate(total=Sum('quantity'))['total']
|
||||
self.assertEqual(consumed_qty, 50)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# delete_build_outputs task
|
||||
# -----------------------------------------------------------------------
|
||||
|
||||
def test_delete_build_outputs_skips_missing_id(self):
|
||||
"""delete_build_outputs silently skips nonexistent output IDs and deletes valid ones."""
|
||||
from build.tasks import delete_build_outputs
|
||||
|
||||
# Create an output directly to avoid serial-number requirements on the trackable assembly
|
||||
output = StockItem.objects.create(
|
||||
part=self.assembly, quantity=3, is_building=True, build=self.build
|
||||
)
|
||||
real_id = output.pk
|
||||
|
||||
# Mix a valid ID with a nonexistent one — must not raise
|
||||
delete_build_outputs(self.build.pk, [real_id, 99999])
|
||||
|
||||
self.assertFalse(StockItem.objects.filter(pk=real_id).exists())
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# scrap_build_outputs task
|
||||
# -----------------------------------------------------------------------
|
||||
|
||||
def test_scrap_build_outputs_discard_allocations(self):
|
||||
"""scrap_build_outputs with discard_allocations=True removes allocations without consuming stock."""
|
||||
from build.tasks import scrap_build_outputs
|
||||
|
||||
self.build.issue_build()
|
||||
# Allocate tracked stock to output_1
|
||||
self.allocate_stock(self.output_1, {self.stock_3_1: 6})
|
||||
self.assertGreater(self.output_1.items_to_install.count(), 0)
|
||||
|
||||
scrap_build_outputs(
|
||||
self.build.pk,
|
||||
[{'output_id': self.output_1.pk, 'quantity': self.output_1.quantity}],
|
||||
location_id=self.location.pk,
|
||||
notes='discard test',
|
||||
discard_allocations=True,
|
||||
user_id=None,
|
||||
)
|
||||
|
||||
self.output_1.refresh_from_db()
|
||||
self.assertEqual(self.output_1.status, StockStatus.REJECTED.value)
|
||||
self.assertFalse(self.output_1.is_building)
|
||||
|
||||
# Allocation rows should be gone
|
||||
self.assertEqual(self.output_1.items_to_install.count(), 0)
|
||||
# Stock was discarded (not consumed or installed)
|
||||
self.stock_3_1.refresh_from_db()
|
||||
self.assertIsNone(self.stock_3_1.consumed_by)
|
||||
self.assertIsNone(self.stock_3_1.belongs_to)
|
||||
|
||||
def test_scrap_build_outputs_consume_allocations(self):
|
||||
"""scrap_build_outputs with discard_allocations=False (default) consumes/installs stock."""
|
||||
from build.tasks import scrap_build_outputs
|
||||
|
||||
self.build.issue_build()
|
||||
self.allocate_stock(self.output_1, {self.stock_3_1: 6})
|
||||
|
||||
scrap_build_outputs(
|
||||
self.build.pk,
|
||||
[{'output_id': self.output_1.pk, 'quantity': self.output_1.quantity}],
|
||||
location_id=self.location.pk,
|
||||
notes='consume test',
|
||||
discard_allocations=False,
|
||||
user_id=None,
|
||||
)
|
||||
|
||||
self.output_1.refresh_from_db()
|
||||
self.assertEqual(self.output_1.status, StockStatus.REJECTED.value)
|
||||
self.assertFalse(self.output_1.is_building)
|
||||
|
||||
# complete_allocation splits stock_3_1 and installs the split piece into output_1
|
||||
# (stock_3_1 quantity=1000, only 6 allocated, so a child item is created)
|
||||
self.assertTrue(
|
||||
StockItem.objects.filter(belongs_to=self.output_1).exists(),
|
||||
'Expected a tracked stock item to be installed into the output',
|
||||
)
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
# complete_build_outputs task
|
||||
# -----------------------------------------------------------------------
|
||||
|
||||
def test_complete_build_outputs_with_status_none(self):
|
||||
"""complete_build_outputs with status=None falls back to StockStatus.OK in the model."""
|
||||
from build.tasks import complete_build_outputs
|
||||
|
||||
self.build.issue_build()
|
||||
# Create output directly to avoid serial-number requirements on the trackable assembly
|
||||
output = StockItem.objects.create(
|
||||
part=self.assembly, quantity=5, is_building=True, build=self.build
|
||||
)
|
||||
|
||||
complete_build_outputs(
|
||||
self.build.pk,
|
||||
[{'output_id': output.pk}],
|
||||
location_id=self.location.pk,
|
||||
status=None,
|
||||
notes='status none test',
|
||||
user_id=None,
|
||||
)
|
||||
|
||||
output.refresh_from_db()
|
||||
self.assertFalse(output.is_building)
|
||||
# status=None should resolve to StockStatus.OK (the model default)
|
||||
self.assertEqual(output.status, StockStatus.OK.value)
|
||||
|
|
|
|||
|
|
@ -717,7 +717,17 @@ class AttachmentFilter(FilterSet):
|
|||
"""Metaclass options."""
|
||||
|
||||
model = common.models.Attachment
|
||||
fields = ['model_type', 'model_id', 'upload_user']
|
||||
fields = ['model_type', 'model_id', 'upload_user', 'is_image']
|
||||
|
||||
has_thumbnail = rest_filters.BooleanFilter(
|
||||
label=_('Has Thumbnail'), method='filter_has_thumbnail'
|
||||
)
|
||||
|
||||
def filter_has_thumbnail(self, queryset, name, value):
|
||||
"""Filter attachments based on whether they have a thumbnail or not."""
|
||||
if value:
|
||||
return queryset.exclude(thumbnail=None).exclude(thumbnail='')
|
||||
return queryset.filter(Q(thumbnail=None) | Q(thumbnail='')).distinct()
|
||||
|
||||
is_link = rest_filters.BooleanFilter(label=_('Is Link'), method='filter_is_link')
|
||||
|
||||
|
|
@ -781,8 +791,34 @@ class AttachmentList(AttachmentMixin, BulkDeleteMixin, ListCreateAPI):
|
|||
class AttachmentDetail(AttachmentMixin, RetrieveUpdateDestroyAPI):
|
||||
"""Detail API endpoint for Attachment objects."""
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
"""Update an existing attachment object."""
|
||||
attachment = self.get_object()
|
||||
|
||||
if not attachment.check_permission('change', request.user):
|
||||
raise PermissionDenied(
|
||||
_('User does not have permission to edit this attachment')
|
||||
)
|
||||
|
||||
partial = kwargs.pop('partial', False)
|
||||
data = self.clean_data(request.data)
|
||||
|
||||
# Extract filename first
|
||||
filename = data.pop('filename', None)
|
||||
|
||||
# Run other validation / updates first, before attempting to rename the file
|
||||
serializer = self.get_serializer(attachment, data=data, partial=partial)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
self.perform_update(serializer)
|
||||
|
||||
# User is attempting to rename the file
|
||||
if filename and attachment.basename and filename != attachment.basename:
|
||||
attachment.rename(filename)
|
||||
|
||||
return Response(serializer.data)
|
||||
|
||||
def destroy(self, request, *args, **kwargs):
|
||||
"""Check user permissions before deleting an attachment."""
|
||||
"""Delete an existing attachment object."""
|
||||
attachment = self.get_object()
|
||||
|
||||
if not attachment.check_permission('delete', request.user):
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
# Generated by Django 5.2.14 on 2026-05-18 11:34
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
import common.models
|
||||
import common.validators
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("common", "0041_auto_20251203_1244"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="attachment",
|
||||
name="thumbnail",
|
||||
field=models.ImageField(
|
||||
blank=True,
|
||||
help_text="Thumbnail image for this attachment",
|
||||
null=True,
|
||||
upload_to="",
|
||||
verbose_name="Thumbnail",
|
||||
),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="attachment",
|
||||
name="is_image",
|
||||
field=models.BooleanField(
|
||||
default=False,
|
||||
help_text="True if this attachment is a valid image file",
|
||||
verbose_name="Is image",
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="attachment",
|
||||
name="attachment",
|
||||
field=models.FileField(
|
||||
blank=True,
|
||||
help_text="Select file to attach",
|
||||
null=True,
|
||||
upload_to=common.models.rename_attachment,
|
||||
validators=[common.validators.validate_attachment_file],
|
||||
verbose_name="Attachment",
|
||||
),
|
||||
),
|
||||
]
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
# Generated by Django 5.2.14 on 2026-05-18 12:06
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
from PIL import Image
|
||||
from tqdm import tqdm
|
||||
|
||||
from time import sleep
|
||||
|
||||
from django.db import migrations
|
||||
from django.core.files.base import ContentFile
|
||||
from django.core.files.storage import default_storage
|
||||
|
||||
|
||||
def update_image_attachments(apps, schema_editor):
|
||||
"""Update existing attachments to ensure that image attachments have thumbnails.
|
||||
|
||||
For each existing attachment, check if it is an image.
|
||||
If it is, generate a thumbnail for it.
|
||||
|
||||
Note: This function mirrors the logic used in the Attachment model's
|
||||
check_is_image method, at the time of writing this migration (2026-05-18).
|
||||
"""
|
||||
|
||||
import common.tasks
|
||||
|
||||
Attachment = apps.get_model('common', 'Attachment')
|
||||
|
||||
# Find all Attachment instances which (potentially) have a file attached
|
||||
attachments = Attachment.objects.exclude(attachment__isnull=True).exclude(attachment='')
|
||||
|
||||
if attachments.count() == 0:
|
||||
return
|
||||
|
||||
progress = tqdm(total=attachments.count(), desc='Migration common.0043: Updating attachments')
|
||||
|
||||
for attachment in attachments:
|
||||
progress.update(1)
|
||||
|
||||
if not attachment.attachment:
|
||||
continue
|
||||
|
||||
if not attachment.attachment.name or not default_storage.exists(attachment.attachment.name):
|
||||
continue
|
||||
|
||||
common.tasks.rebuild_attachment(attachment.pk)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("common", "0042_attachment_is_image_attachment_thumbnail"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(update_image_attachments, reverse_code=migrations.RunPython.noop),
|
||||
]
|
||||
|
|
@ -15,6 +15,7 @@ from datetime import timedelta, timezone
|
|||
from email.utils import make_msgid
|
||||
from enum import Enum
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from secrets import compare_digest
|
||||
from typing import Any, Optional
|
||||
|
||||
|
|
@ -25,9 +26,10 @@ from django.contrib.contenttypes.fields import GenericForeignKey
|
|||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.contrib.humanize.templatetags.humanize import naturaltime
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.exceptions import SuspiciousFileOperation, ValidationError
|
||||
from django.core.files.base import ContentFile
|
||||
from django.core.files.storage import default_storage
|
||||
from django.core.files.utils import validate_file_name
|
||||
from django.core.mail import EmailMultiAlternatives, get_connection
|
||||
from django.core.mail.utils import DNS_NAME
|
||||
from django.core.validators import MinLengthValidator, MinValueValidator
|
||||
|
|
@ -46,6 +48,7 @@ from django_q.signals import post_spawn
|
|||
from djmoney.contrib.exchange.exceptions import MissingRate
|
||||
from djmoney.contrib.exchange.models import convert_money
|
||||
from opentelemetry import trace
|
||||
from PIL import Image
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
from taggit.managers import TaggableManager
|
||||
|
||||
|
|
@ -1930,6 +1933,8 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
model_id: The ID of the model to which this attachment is linked
|
||||
attachment: The uploaded file
|
||||
url: An external URL
|
||||
thumbnail: A generated thumbnail for the uploaded file (if applicable)
|
||||
is_image: True if this attachment is a valid image file
|
||||
comment: A comment or description for the attachment
|
||||
user: The user who uploaded the attachment
|
||||
upload_date: The date the attachment was uploaded
|
||||
|
|
@ -1938,6 +1943,8 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
tags: Tags for the attachment
|
||||
"""
|
||||
|
||||
THUMBNAIL_SIZE = 256
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
|
|
@ -1948,6 +1955,31 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
|
||||
choice_fnc = common.validators.attachment_model_options
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
"""Custom delete method for the Attachment model.
|
||||
|
||||
- Ensure that the attached file is deleted from storage when the database entry is removed
|
||||
"""
|
||||
attachment = self.attachment
|
||||
thumbnail = self.thumbnail
|
||||
|
||||
super().delete(*args, **kwargs)
|
||||
|
||||
# Delete the associated files from storage (if they exist)W
|
||||
if attachment and default_storage.exists(attachment.name):
|
||||
try:
|
||||
# Remove the attached file from storage
|
||||
default_storage.delete(attachment.name)
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
|
||||
if thumbnail and default_storage.exists(thumbnail.name):
|
||||
try:
|
||||
# Remove the thumbnail file from storage
|
||||
default_storage.delete(thumbnail.name)
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
"""Custom 'save' method for the Attachment model.
|
||||
|
||||
|
|
@ -1955,6 +1987,10 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
- Ensure that the 'content_type' and 'object_id' fields are set
|
||||
- Run extra validations
|
||||
"""
|
||||
import common.tasks
|
||||
|
||||
rebuild = kwargs.pop('rebuild', True)
|
||||
|
||||
# Either 'attachment' or 'link' must be specified!
|
||||
if not self.attachment and not self.link:
|
||||
raise ValidationError({
|
||||
|
|
@ -1982,6 +2018,12 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
if self.file_size != 0:
|
||||
super().save()
|
||||
|
||||
# Offload a background task to update the thumbnail for this attachment
|
||||
if rebuild:
|
||||
InvenTree.tasks.offload_task(
|
||||
common.tasks.rebuild_attachment, self.pk, group='attachments'
|
||||
)
|
||||
|
||||
def clean_svg(self, field):
|
||||
"""Sanitize SVG file before saving."""
|
||||
cleaned = sanitize_svg(field.file.read())
|
||||
|
|
@ -1993,6 +2035,60 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
return os.path.basename(self.attachment.name)
|
||||
return str(self.link)
|
||||
|
||||
def validate_rename(self, filename: str):
|
||||
"""Validate that the provided filename is valid, for renaming an attachment."""
|
||||
filename = filename.strip()
|
||||
|
||||
if not self.attachment:
|
||||
raise ValidationError(_('No file attached to rename'))
|
||||
|
||||
if not filename:
|
||||
raise ValidationError(_('Filename cannot be empty'))
|
||||
|
||||
try:
|
||||
validate_file_name(filename, allow_relative_path=False)
|
||||
except SuspiciousFileOperation:
|
||||
raise ValidationError(_('Invalid filename'))
|
||||
|
||||
current_ext = os.path.splitext(self.attachment.name)[1]
|
||||
new_ext = os.path.splitext(filename)[1]
|
||||
|
||||
if current_ext.lower() != new_ext.lower():
|
||||
raise ValidationError(_('Cannot change file extension'))
|
||||
|
||||
def rename(self, filename: str):
|
||||
"""Rename the attached file."""
|
||||
self.validate_rename(filename)
|
||||
|
||||
old_path = Path(self.attachment.name)
|
||||
new_path = old_path.parent / filename
|
||||
|
||||
if old_path == new_path: # pragma: no cover
|
||||
# No change in filename
|
||||
return
|
||||
|
||||
if not new_path.is_relative_to(old_path.parent): # pragma: no cover
|
||||
raise ValidationError(_('Invalid filename'))
|
||||
|
||||
new_path = new_path.as_posix()
|
||||
|
||||
if default_storage.exists(new_path):
|
||||
raise ValidationError(_('A file with this name already exists'))
|
||||
|
||||
# Create a new file with the new name, and delete the old file
|
||||
new_path = default_storage.save(new_path, self.attachment.file)
|
||||
|
||||
# Ensure that the new file exists
|
||||
if not default_storage.exists(new_path): # pragma: no cover
|
||||
raise ValidationError(_('Failed to save renamed file'))
|
||||
|
||||
# Update the database file path
|
||||
self.attachment.name = new_path
|
||||
self.save()
|
||||
|
||||
# Remove the old path
|
||||
default_storage.delete(old_path)
|
||||
|
||||
model_type = models.CharField(
|
||||
max_length=100,
|
||||
validators=[common.validators.validate_attachment_model_type],
|
||||
|
|
@ -2005,11 +2101,19 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
attachment = models.FileField(
|
||||
upload_to=rename_attachment,
|
||||
verbose_name=_('Attachment'),
|
||||
validators=[common.validators.validate_attachment_file],
|
||||
help_text=_('Select file to attach'),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
|
||||
thumbnail = models.ImageField(
|
||||
verbose_name=_('Thumbnail'),
|
||||
help_text=_('Thumbnail image for this attachment'),
|
||||
blank=True,
|
||||
null=True,
|
||||
)
|
||||
|
||||
link = InvenTree.fields.InvenTreeURLField(
|
||||
blank=True,
|
||||
null=True,
|
||||
|
|
@ -2042,6 +2146,12 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
help_text=_('Date the file was uploaded'),
|
||||
)
|
||||
|
||||
is_image = models.BooleanField(
|
||||
default=False,
|
||||
verbose_name=_('Is image'),
|
||||
help_text=_('True if this attachment is a valid image file'),
|
||||
)
|
||||
|
||||
file_size = models.PositiveIntegerField(
|
||||
default=0, verbose_name=_('File size'), help_text=_('File size in bytes')
|
||||
)
|
||||
|
|
@ -2085,6 +2195,69 @@ class Attachment(InvenTree.models.MetadataMixin, InvenTree.models.InvenTreeModel
|
|||
|
||||
return model_class.check_related_permission(permission, user)
|
||||
|
||||
def check_is_image(self) -> bool:
|
||||
"""Check if the attached file is an image.
|
||||
|
||||
We consider it a valid image if:
|
||||
|
||||
- The file exists in storage
|
||||
- The file can be opened and verified by the PIL library
|
||||
|
||||
"""
|
||||
if not self.attachment:
|
||||
return False
|
||||
|
||||
if not self.attachment.name:
|
||||
return False
|
||||
|
||||
try:
|
||||
if not default_storage.exists(self.attachment.name):
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
img_data = default_storage.open(self.attachment.name).read()
|
||||
|
||||
try:
|
||||
Image.open(BytesIO(img_data)).verify()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def generate_thumbnail(self):
|
||||
"""Generate a thumbnail for the attached image."""
|
||||
# Remove any existing thumbnail
|
||||
if self.thumbnail:
|
||||
self.thumbnail.delete(save=False)
|
||||
|
||||
if not self.attachment:
|
||||
return
|
||||
|
||||
if not self.attachment.name or not default_storage.exists(self.attachment.name):
|
||||
return
|
||||
|
||||
# TODO: Offload to plugins, for creating custom thumbnails for different file types
|
||||
# TODO: If a plugin provides a thumbnail, return early
|
||||
|
||||
# Default action is to generate a thumbnail for image files
|
||||
try:
|
||||
img_data = default_storage.open(self.attachment.name).read()
|
||||
except Exception:
|
||||
# No file found, or file cannot be read - cannot generate thumbnail
|
||||
return
|
||||
|
||||
try:
|
||||
img = Image.open(BytesIO(img_data))
|
||||
img.thumbnail((self.THUMBNAIL_SIZE, self.THUMBNAIL_SIZE))
|
||||
thumb_io = BytesIO()
|
||||
img.save(thumb_io, format='PNG')
|
||||
thumb_io.seek(0)
|
||||
|
||||
thumb_name = f'thumb_{os.path.basename(self.attachment.name)}'
|
||||
self.thumbnail.save(thumb_name, ContentFile(thumb_io.read()), save=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class InvenTreeCustomUserStateModel(models.Model):
|
||||
"""Custom model to extends any registered state with extra custom, user defined states.
|
||||
|
|
@ -2612,7 +2785,7 @@ def post_save_parameter_template(sender, instance, created, **kwargs):
|
|||
common.tasks.rebuild_parameters,
|
||||
instance.pk,
|
||||
force_async=True,
|
||||
group='part',
|
||||
group='parameters',
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
"""JSON serializers for common components."""
|
||||
"""API serializers for common components."""
|
||||
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.db.models import Count, OuterRef, Subquery
|
||||
|
|
@ -730,9 +730,11 @@ class AttachmentSerializer(FilterableSerializerMixin, InvenTreeModelSerializer):
|
|||
fields = [
|
||||
'pk',
|
||||
'attachment',
|
||||
'thumbnail',
|
||||
'filename',
|
||||
'link',
|
||||
'comment',
|
||||
'is_image',
|
||||
'upload_date',
|
||||
'upload_user',
|
||||
'user_detail',
|
||||
|
|
@ -742,7 +744,14 @@ class AttachmentSerializer(FilterableSerializerMixin, InvenTreeModelSerializer):
|
|||
'tags',
|
||||
]
|
||||
|
||||
read_only_fields = ['pk', 'file_size', 'upload_date', 'upload_user', 'filename']
|
||||
read_only_fields = [
|
||||
'pk',
|
||||
'file_size',
|
||||
'upload_date',
|
||||
'upload_user',
|
||||
'filename',
|
||||
'is_image',
|
||||
]
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Override the model_type field to provide dynamic choices."""
|
||||
|
|
@ -759,6 +768,8 @@ class AttachmentSerializer(FilterableSerializerMixin, InvenTreeModelSerializer):
|
|||
|
||||
attachment = InvenTreeAttachmentSerializerField(required=False, allow_null=True)
|
||||
|
||||
thumbnail = InvenTreeImageSerializerField(read_only=True, allow_null=True)
|
||||
|
||||
# The 'filename' field must be present in the serializer
|
||||
filename = serializers.CharField(
|
||||
label=_('Filename'), required=False, source='basename', allow_blank=False
|
||||
|
|
|
|||
|
|
@ -286,25 +286,12 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
|||
'choices': common.currency.currency_exchange_plugins,
|
||||
'default': 'inventreecurrencyexchange',
|
||||
},
|
||||
'INVENTREE_DOWNLOAD_FROM_URL': {
|
||||
'name': _('Download from URL'),
|
||||
'description': _('Allow download of remote images and files from external URL'),
|
||||
'validator': bool,
|
||||
'default': False,
|
||||
},
|
||||
'INVENTREE_DOWNLOAD_IMAGE_MAX_SIZE': {
|
||||
'name': _('Download Size Limit'),
|
||||
'description': _('Maximum allowable download size for remote image'),
|
||||
'INVENTREE_UPLOAD_MAX_SIZE': {
|
||||
'name': _('Upload Size Limit'),
|
||||
'description': _('Maximum allowable upload size for images and files'),
|
||||
'units': 'MB',
|
||||
'default': 1,
|
||||
'validator': [int, MinValueValidator(1), MaxValueValidator(25)],
|
||||
},
|
||||
'INVENTREE_DOWNLOAD_FROM_URL_USER_AGENT': {
|
||||
'name': _('User-agent used to download from URL'),
|
||||
'description': _(
|
||||
'Allow to override the user-agent used to download images and files from external URL (leave blank for the default)'
|
||||
),
|
||||
'default': '',
|
||||
'default': 10,
|
||||
'validator': [int, MinValueValidator(1)],
|
||||
},
|
||||
'INVENTREE_STRICT_URLS': {
|
||||
'name': _('Strict URL Validation'),
|
||||
|
|
@ -415,6 +402,12 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
|||
'choices': barcode_plugins,
|
||||
'default': 'inventreebarcode',
|
||||
},
|
||||
'PART_ENABLE_LOCKING': {
|
||||
'name': _('Part Locking'),
|
||||
'description': _('Enable locking of parts to prevent modification'),
|
||||
'validator': bool,
|
||||
'default': True,
|
||||
},
|
||||
'PART_ENABLE_REVISION': {
|
||||
'name': _('Part Revisions'),
|
||||
'description': _('Enable revision field for Part'),
|
||||
|
|
@ -716,6 +709,12 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
|||
'default': True,
|
||||
'validator': bool,
|
||||
},
|
||||
'STOCK_ALLOW_EDIT_SERIAL': {
|
||||
'name': _('Allow Edit Serial Number'),
|
||||
'description': _('Allow editing of serial number for stock items'),
|
||||
'default': True,
|
||||
'validator': bool,
|
||||
},
|
||||
'STOCK_ALLOW_DELETE_SERIALIZED': {
|
||||
'name': _('Delete Serialized Stock'),
|
||||
'description': _('Allow deletion of stock items which have a serial number'),
|
||||
|
|
@ -918,6 +917,26 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
|||
'default': False,
|
||||
'validator': bool,
|
||||
},
|
||||
'TRANSFERORDER_ENABLED': {
|
||||
'name': _('Enable Transfer Orders'),
|
||||
'description': _('Enable transfer order functionality in the user interface'),
|
||||
'validator': bool,
|
||||
'default': False,
|
||||
},
|
||||
'TRANSFERORDER_REFERENCE_PATTERN': {
|
||||
'name': _('Transfer Order Reference Pattern'),
|
||||
'description': _(
|
||||
'Required pattern for generating Transfer Order reference field'
|
||||
),
|
||||
'default': 'TO-{ref:04d}',
|
||||
'validator': order.validators.validate_transfer_order_reference_pattern,
|
||||
},
|
||||
'TRANSFERORDER_REQUIRE_RESPONSIBLE': {
|
||||
'name': _('Require Responsible Owner'),
|
||||
'description': _('A responsible owner must be assigned to each order'),
|
||||
'default': False,
|
||||
'validator': bool,
|
||||
},
|
||||
'SALESORDER_BLOCK_INCOMPLETE_ITEM_TESTS': {
|
||||
'name': _('Block Incomplete Item Tests'),
|
||||
'description': _(
|
||||
|
|
|
|||
|
|
@ -268,4 +268,12 @@ USER_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
|||
'description': _('Save the last used printing machines for a user'),
|
||||
'default': '',
|
||||
},
|
||||
'DISPLAY_ITEMS_FINAL_LEVEL': {
|
||||
'name': _('Display Items at Final Level'),
|
||||
'description': _(
|
||||
'Automatically default to showing items/parts instead of sub-levels for locations or categories with no children'
|
||||
),
|
||||
'default': False,
|
||||
'validator': bool,
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -204,3 +204,21 @@ def rebuild_parameters(template_id):
|
|||
|
||||
if n > 0:
|
||||
logger.info("Rebuilt %s parameters for template '%s'", n, template.name)
|
||||
|
||||
|
||||
@tracer.start_as_current_span('rebuild_attachment')
|
||||
def rebuild_attachment(attachment_id: int):
|
||||
"""Rebuild the given attachment, if possible.
|
||||
|
||||
This task is called whenever an attachment is saved, and perform the following tasks:
|
||||
|
||||
- Check if the attachment is an image file, and update the "is_image" field accordingly
|
||||
- Attempt to generate a thumbnail for the attachment
|
||||
"""
|
||||
from common.models import Attachment
|
||||
|
||||
attachment = Attachment.objects.get(pk=attachment_id)
|
||||
|
||||
attachment.is_image = attachment.check_is_image()
|
||||
attachment.generate_thumbnail()
|
||||
attachment.save(rebuild=False)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,14 @@
|
|||
"""API unit tests for InvenTree common functionality."""
|
||||
|
||||
import io
|
||||
|
||||
from django.core.files.base import ContentFile
|
||||
from django.core.files.storage import default_storage
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.urls import reverse
|
||||
|
||||
from PIL import Image
|
||||
|
||||
import common.models
|
||||
from InvenTree.unit_test import InvenTreeAPITestCase
|
||||
|
||||
|
|
@ -675,3 +682,320 @@ class ParameterAPITests(InvenTreeAPITestCase):
|
|||
self.assertFalse(
|
||||
common.models.Parameter.objects.filter(template=template.pk).exists()
|
||||
)
|
||||
|
||||
|
||||
class AttachmentAPITests(InvenTreeAPITestCase):
|
||||
"""Tests for the Attachment API."""
|
||||
|
||||
def test_attachments(self):
|
||||
"""Test API functionality for attachments."""
|
||||
from common.models import Attachment
|
||||
from part.models import Part
|
||||
|
||||
self.assignRole('part.add')
|
||||
|
||||
part = Part.objects.create(name='Test Part', description='A part for testing')
|
||||
|
||||
N = Attachment.objects.count()
|
||||
|
||||
# Upload multiple attachments against the part instance
|
||||
for ii in range(5):
|
||||
file_object = io.StringIO('Hello world')
|
||||
file_object.seek(0)
|
||||
|
||||
fn = f'test_file_{ii}.txt'
|
||||
|
||||
content_file = ContentFile(file_object.read(), name=fn)
|
||||
|
||||
url = reverse('api-attachment-list')
|
||||
|
||||
response = self.post(
|
||||
url,
|
||||
data={
|
||||
'model_type': 'part',
|
||||
'model_id': part.pk,
|
||||
'attachment': content_file,
|
||||
'comment': f'This is test file {ii}',
|
||||
},
|
||||
format='multipart',
|
||||
expected_code=201,
|
||||
)
|
||||
|
||||
data = response.data
|
||||
|
||||
# Check that the file has actually been created
|
||||
self.assertEqual(data['filename'], fn)
|
||||
self.assertTrue(
|
||||
default_storage.exists(data['attachment'].replace('/media/', ''))
|
||||
)
|
||||
|
||||
# Check that we have the expected number of attachments
|
||||
self.assertEqual(Attachment.objects.count(), N + 5)
|
||||
self.assertEqual(part.attachments.count(), 5)
|
||||
|
||||
# Let's rename one of the attachments
|
||||
att = part.attachments.first()
|
||||
self.assertEqual(att.basename, 'test_file_0.txt')
|
||||
|
||||
url = reverse('api-attachment-detail', kwargs={'pk': att.pk})
|
||||
|
||||
# A few failed attempts
|
||||
for new_name in [
|
||||
'different_ext.docx',
|
||||
'test_file_1.txt',
|
||||
'../../test_file.txt',
|
||||
]:
|
||||
print('- ATTEMPTING:', new_name)
|
||||
response = self.patch(url, data={'filename': new_name}, expected_code=400)
|
||||
|
||||
att.refresh_from_db()
|
||||
self.assertEqual(att.basename, 'test_file_0.txt')
|
||||
|
||||
# Let's try seriously this time
|
||||
new_name = 'a_new_file.txt'
|
||||
response = self.patch(url, data={'filename': new_name}, expected_code=200)
|
||||
|
||||
att.refresh_from_db()
|
||||
self.assertEqual(att.basename, new_name)
|
||||
|
||||
# Check that the file has been renamed on disk
|
||||
self.assertTrue(
|
||||
default_storage.exists(f'attachments/part/{part.pk}/{new_name}')
|
||||
)
|
||||
self.assertFalse(
|
||||
default_storage.exists(f'attachments/part/{part.pk}/test_file_0.txt')
|
||||
)
|
||||
|
||||
# Next, let's delete the attachment manually - via the API
|
||||
response = self.delete(url, expected_code=403)
|
||||
self.assignRole('part.delete')
|
||||
response = self.delete(url, expected_code=204)
|
||||
|
||||
# Check that the file has been deleted from disk
|
||||
self.assertFalse(
|
||||
default_storage.exists(f'attachments/part/{part.pk}/{new_name}')
|
||||
)
|
||||
|
||||
self.assertEqual(Attachment.objects.count(), N + 4)
|
||||
self.assertEqual(part.attachments.count(), 4)
|
||||
|
||||
# Fetch the remaining attachments
|
||||
attachments = list(part.attachments.all())
|
||||
|
||||
# Now, delete the part instance
|
||||
part.active = False
|
||||
part.save()
|
||||
part.delete()
|
||||
|
||||
self.assertEqual(Attachment.objects.count(), N)
|
||||
|
||||
for att in attachments:
|
||||
# Ensure that the file associated with each attachment has been removed
|
||||
self.assertFalse(default_storage.exists(att.attachment.path))
|
||||
|
||||
|
||||
class AttachmentThumbnailAPITests(InvenTreeAPITestCase):
|
||||
"""Tests for thumbnail generation when uploading attachments via the API."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up a Part instance and required roles."""
|
||||
from part.models import Part
|
||||
|
||||
super().setUp()
|
||||
self.assignRole('part.add')
|
||||
self.assignRole('part.delete')
|
||||
self.part = Part.objects.create(
|
||||
name='Thumbnail Test Part', description='Part for thumbnail testing'
|
||||
)
|
||||
|
||||
def _make_image_file(self, name='test.png', size=(100, 100), color='red'):
|
||||
"""Return a SimpleUploadedFile containing a valid PNG image."""
|
||||
buf = io.BytesIO()
|
||||
Image.new('RGB', size, color=color).save(buf, format='PNG')
|
||||
return SimpleUploadedFile(name, buf.getvalue(), content_type='image/png')
|
||||
|
||||
def _upload_attachment(self, file_obj, expected_code=201):
|
||||
"""Upload a file attachment against the test part and return the response."""
|
||||
return self.post(
|
||||
reverse('api-attachment-list'),
|
||||
data={
|
||||
'model_type': 'part',
|
||||
'model_id': self.part.pk,
|
||||
'attachment': file_obj,
|
||||
},
|
||||
format='multipart',
|
||||
expected_code=expected_code,
|
||||
)
|
||||
|
||||
def test_thumbnail_valid_image(self):
|
||||
"""Uploading a valid image file should set is_image=True and generate a thumbnail."""
|
||||
from common.models import Attachment
|
||||
|
||||
response = self._upload_attachment(self._make_image_file())
|
||||
att = Attachment.objects.get(pk=response.data['pk'])
|
||||
|
||||
self.assertTrue(att.is_image)
|
||||
self.assertTrue(att.thumbnail)
|
||||
self.assertTrue(default_storage.exists(att.thumbnail.name))
|
||||
|
||||
def test_thumbnail_invalid_image(self):
|
||||
"""Uploading a file with an image extension but invalid image data should not create a thumbnail."""
|
||||
from common.models import Attachment
|
||||
|
||||
bad_file = SimpleUploadedFile(
|
||||
'corrupt.png', b'this is not image data', content_type='image/png'
|
||||
)
|
||||
response = self._upload_attachment(bad_file)
|
||||
att = Attachment.objects.get(pk=response.data['pk'])
|
||||
|
||||
self.assertFalse(att.is_image)
|
||||
self.assertFalse(att.thumbnail)
|
||||
|
||||
def test_thumbnail_non_image_file(self):
|
||||
"""Uploading a non-image file should leave is_image=False with no thumbnail."""
|
||||
from common.models import Attachment
|
||||
|
||||
txt_file = SimpleUploadedFile(
|
||||
'document.txt', b'Hello, InvenTree!', content_type='text/plain'
|
||||
)
|
||||
response = self._upload_attachment(txt_file)
|
||||
att = Attachment.objects.get(pk=response.data['pk'])
|
||||
|
||||
self.assertFalse(att.is_image)
|
||||
self.assertFalse(att.thumbnail)
|
||||
|
||||
def test_thumbnail_large_image(self):
|
||||
"""A large image attachment should produce a thumbnail no larger than THUMBNAIL_SIZE on each side."""
|
||||
from common.models import Attachment
|
||||
|
||||
response = self._upload_attachment(self._make_image_file(size=(1000, 1000)))
|
||||
att = Attachment.objects.get(pk=response.data['pk'])
|
||||
|
||||
self.assertTrue(att.is_image)
|
||||
self.assertTrue(att.thumbnail)
|
||||
|
||||
thumb_data = default_storage.open(att.thumbnail.name).read()
|
||||
thumb_img = Image.open(io.BytesIO(thumb_data))
|
||||
self.assertLessEqual(thumb_img.width, Attachment.THUMBNAIL_SIZE)
|
||||
self.assertLessEqual(thumb_img.height, Attachment.THUMBNAIL_SIZE)
|
||||
|
||||
def test_thumbnail_deleted_with_attachment(self):
|
||||
"""Deleting an attachment via the API should also remove its thumbnail from storage."""
|
||||
from common.models import Attachment
|
||||
|
||||
response = self._upload_attachment(self._make_image_file())
|
||||
att = Attachment.objects.get(pk=response.data['pk'])
|
||||
|
||||
self.assertTrue(att.thumbnail)
|
||||
thumb_name = att.thumbnail.name
|
||||
att_name = att.attachment.name
|
||||
|
||||
self.assertTrue(default_storage.exists(att_name))
|
||||
self.assertTrue(default_storage.exists(thumb_name))
|
||||
|
||||
self.delete(
|
||||
reverse('api-attachment-detail', kwargs={'pk': att.pk}), expected_code=204
|
||||
)
|
||||
|
||||
self.assertFalse(default_storage.exists(att_name))
|
||||
self.assertFalse(default_storage.exists(thumb_name))
|
||||
|
||||
def test_thumbnail_zero_byte_file(self):
|
||||
"""Uploading a zero-byte file should be rejected by Django's file validation before reaching thumbnail logic."""
|
||||
empty_file = SimpleUploadedFile('empty.png', b'', content_type='image/png')
|
||||
# Django's FileField rejects empty uploads at the serializer/validation layer
|
||||
response = self._upload_attachment(empty_file, expected_code=400)
|
||||
self.assertIn('attachment', response.data)
|
||||
|
||||
def test_thumbnail_link_attachment(self):
|
||||
"""An attachment created with an external link (no file) should not generate a thumbnail."""
|
||||
from common.models import Attachment
|
||||
|
||||
response = self.post(
|
||||
reverse('api-attachment-list'),
|
||||
data={
|
||||
'model_type': 'part',
|
||||
'model_id': self.part.pk,
|
||||
'link': 'https://example.com/some/resource',
|
||||
},
|
||||
format='multipart',
|
||||
expected_code=201,
|
||||
)
|
||||
|
||||
att = Attachment.objects.get(pk=response.data['pk'])
|
||||
|
||||
self.assertFalse(att.is_image)
|
||||
self.assertFalse(att.thumbnail)
|
||||
|
||||
def test_is_image_filter(self):
|
||||
"""The is_image filter on the attachment list endpoint should return only matching attachments."""
|
||||
url = reverse('api-attachment-list')
|
||||
base_filters = {'model_type': 'part', 'model_id': self.part.pk}
|
||||
|
||||
# Upload one valid image and three non-image attachments
|
||||
self._upload_attachment(self._make_image_file('img1.png'))
|
||||
self._upload_attachment(
|
||||
SimpleUploadedFile(
|
||||
'corrupt.png', b'not image data', content_type='image/png'
|
||||
)
|
||||
)
|
||||
self._upload_attachment(
|
||||
SimpleUploadedFile('doc.txt', b'hello', content_type='text/plain')
|
||||
)
|
||||
self.post(
|
||||
url,
|
||||
data={**base_filters, 'link': 'https://example.com/resource'},
|
||||
format='multipart',
|
||||
expected_code=201,
|
||||
)
|
||||
|
||||
all_attachments = self.get(url, base_filters, expected_code=200).data
|
||||
self.assertEqual(len(all_attachments), 4)
|
||||
|
||||
# is_image=true → only the valid image
|
||||
images = self.get(
|
||||
url, {**base_filters, 'is_image': 'true'}, expected_code=200
|
||||
).data
|
||||
self.assertEqual(len(images), 1)
|
||||
self.assertTrue(images[0]['is_image'])
|
||||
|
||||
# is_image=false → the three non-image attachments
|
||||
non_images = self.get(
|
||||
url, {**base_filters, 'is_image': 'false'}, expected_code=200
|
||||
).data
|
||||
self.assertEqual(len(non_images), 3)
|
||||
self.assertTrue(all(not a['is_image'] for a in non_images))
|
||||
|
||||
def test_upload_exceeds_size_limit(self):
|
||||
"""Uploading a file that exceeds INVENTREE_UPLOAD_MAX_SIZE should be rejected with a 400 error."""
|
||||
from common.settings import get_global_setting, set_global_setting
|
||||
|
||||
original_limit = get_global_setting('INVENTREE_UPLOAD_MAX_SIZE')
|
||||
# Use a 1 MB ceiling so the test file stays small and fast
|
||||
set_global_setting('INVENTREE_UPLOAD_MAX_SIZE', 1, change_user=None)
|
||||
|
||||
limit_bytes = 1 * 1024 * 1024
|
||||
|
||||
try:
|
||||
# File exactly at the limit — validator uses >, so this must be accepted
|
||||
self._upload_attachment(
|
||||
SimpleUploadedFile(
|
||||
'at_limit.txt', b'\x00' * limit_bytes, content_type='text/plain'
|
||||
),
|
||||
expected_code=201,
|
||||
)
|
||||
|
||||
# File one byte over the limit — must be rejected
|
||||
response = self._upload_attachment(
|
||||
SimpleUploadedFile(
|
||||
'over_limit.txt',
|
||||
b'\x00' * (limit_bytes + 1),
|
||||
content_type='text/plain',
|
||||
),
|
||||
expected_code=400,
|
||||
)
|
||||
self.assertIn('attachment', response.data)
|
||||
finally:
|
||||
set_global_setting(
|
||||
'INVENTREE_UPLOAD_MAX_SIZE', original_limit, change_user=None
|
||||
)
|
||||
|
|
|
|||
|
|
@ -4,8 +4,10 @@ import io
|
|||
import os
|
||||
|
||||
from django.core.files.base import ContentFile
|
||||
from django.core.files.storage import default_storage
|
||||
|
||||
from django_test_migrations.contrib.unittest_case import MigratorTestCase
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def get_legacy_models():
|
||||
|
|
@ -209,6 +211,85 @@ class TestForwardMigrations(MigratorTestCase):
|
|||
self.assertEqual(Attachment.objects.filter(model_type=model).count(), 2)
|
||||
|
||||
|
||||
class TestAttachmentThumbnailMigration(MigratorTestCase):
|
||||
"""Test that migration 0043 correctly populates is_image and generates thumbnails for existing attachments."""
|
||||
|
||||
migrate_from = ('common', '0041_auto_20251203_1244')
|
||||
migrate_to = ('common', '0043_auto_20260518_1206')
|
||||
|
||||
def prepare(self):
|
||||
"""Create a set of attachments with different file types in the pre-migration state.
|
||||
|
||||
At this point the Attachment model has no is_image or thumbnail fields yet.
|
||||
Files are written to storage directly through the FileField so that the
|
||||
data migration can find them at their stored paths.
|
||||
"""
|
||||
Attachment = self.old_state.apps.get_model('common', 'Attachment')
|
||||
|
||||
# 1. Valid PNG image — migration should set is_image=True and create a thumbnail
|
||||
buf = io.BytesIO()
|
||||
Image.new('RGB', (100, 100), color='blue').save(buf, format='PNG')
|
||||
Attachment.objects.create(
|
||||
model_type='part',
|
||||
model_id=1,
|
||||
attachment=ContentFile(buf.getvalue(), name='valid_image.png'),
|
||||
comment='valid_image',
|
||||
)
|
||||
|
||||
# 2. File with a .png extension but non-image content — migration should leave is_image=False
|
||||
Attachment.objects.create(
|
||||
model_type='part',
|
||||
model_id=1,
|
||||
attachment=ContentFile(b'this is not image data', name='corrupt.png'),
|
||||
comment='corrupt_image',
|
||||
)
|
||||
|
||||
# 3. Plain text file — migration should leave is_image=False with no thumbnail
|
||||
Attachment.objects.create(
|
||||
model_type='part',
|
||||
model_id=1,
|
||||
attachment=ContentFile(b'Hello, InvenTree!', name='document.txt'),
|
||||
comment='text_file',
|
||||
)
|
||||
|
||||
# 4. Link attachment (no file at all) — migration should skip it entirely
|
||||
Attachment.objects.create(
|
||||
model_type='part',
|
||||
model_id=1,
|
||||
link='https://example.com/resource',
|
||||
comment='link_attachment',
|
||||
)
|
||||
|
||||
self.assertEqual(Attachment.objects.count(), 4)
|
||||
|
||||
def test_attachment_thumbnails_after_migration(self):
|
||||
"""After applying migrations 0042 and 0043, verify is_image and thumbnail are correct."""
|
||||
Attachment = self.new_state.apps.get_model('common', 'Attachment')
|
||||
|
||||
self.assertEqual(Attachment.objects.count(), 4)
|
||||
|
||||
# Valid image → is_image set, thumbnail file created in storage
|
||||
att = Attachment.objects.get(comment='valid_image')
|
||||
self.assertTrue(att.is_image)
|
||||
self.assertTrue(att.thumbnail)
|
||||
self.assertTrue(default_storage.exists(att.thumbnail.name))
|
||||
|
||||
# Corrupt image → is_image not set, no thumbnail
|
||||
att = Attachment.objects.get(comment='corrupt_image')
|
||||
self.assertFalse(att.is_image)
|
||||
self.assertFalse(att.thumbnail)
|
||||
|
||||
# Text file → is_image not set, no thumbnail
|
||||
att = Attachment.objects.get(comment='text_file')
|
||||
self.assertFalse(att.is_image)
|
||||
self.assertFalse(att.thumbnail)
|
||||
|
||||
# Link attachment → is_image not set, no thumbnail
|
||||
att = Attachment.objects.get(comment='link_attachment')
|
||||
self.assertFalse(att.is_image)
|
||||
self.assertFalse(att.thumbnail)
|
||||
|
||||
|
||||
def prep_currency_migration(self, vals: str):
|
||||
"""Prepare the environment for the currency migration tests."""
|
||||
# Set keys
|
||||
|
|
|
|||
|
|
@ -86,6 +86,11 @@ class AttachmentTest(InvenTreeAPITestCase):
|
|||
}
|
||||
|
||||
for fn, expected in filenames.items():
|
||||
expected_path = f'attachments/part/{part.pk}/{expected}'
|
||||
# Remove the file if it already exists (i.e. from a previous test run)
|
||||
if default_storage.exists(expected_path):
|
||||
default_storage.delete(expected_path)
|
||||
|
||||
attachment = Attachment.objects.create(
|
||||
attachment=self.generate_file(fn),
|
||||
comment=f'Testing filename: {fn}',
|
||||
|
|
@ -93,7 +98,6 @@ class AttachmentTest(InvenTreeAPITestCase):
|
|||
model_id=part.pk,
|
||||
)
|
||||
|
||||
expected_path = f'attachments/part/{part.pk}/{expected}'
|
||||
self.assertEqual(attachment.attachment.name, expected_path)
|
||||
self.assertEqual(attachment.file_size, 15)
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,8 @@
|
|||
|
||||
import re
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.exceptions import SuspiciousFileOperation, ValidationError
|
||||
from django.core.files.storage import default_storage
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
import common.icons
|
||||
|
|
@ -76,6 +77,21 @@ def validate_attachment_model_type(value):
|
|||
raise ValidationError('Model type does not support attachments')
|
||||
|
||||
|
||||
def validate_attachment_file(attachment):
|
||||
"""Ensure that the provided attachment file is valid."""
|
||||
max_size = get_global_setting('INVENTREE_UPLOAD_MAX_SIZE', create=False)
|
||||
|
||||
if attachment.size > (max_size * 1024 * 1024):
|
||||
raise ValidationError(
|
||||
_(f'File size exceeds maximum upload limit of {max_size} MB')
|
||||
)
|
||||
|
||||
try:
|
||||
default_storage.generate_filename(attachment.name)
|
||||
except SuspiciousFileOperation: # pragma: no cover
|
||||
raise ValidationError(_('Invalid file name'))
|
||||
|
||||
|
||||
def validate_notes_model_type(value):
|
||||
"""Ensure that the provided model type is valid.
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
"""JSON serializers for Company app."""
|
||||
|
||||
import io
|
||||
|
||||
from django.core.files.base import ContentFile
|
||||
from django.db.models import Prefetch
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
|
@ -26,7 +23,6 @@ from InvenTree.serializers import (
|
|||
InvenTreeTagModelSerializer,
|
||||
NotesFieldMixin,
|
||||
OptionalField,
|
||||
RemoteImageMixin,
|
||||
)
|
||||
|
||||
from .models import (
|
||||
|
|
@ -113,7 +109,6 @@ class CompanySerializer(
|
|||
FilterableSerializerMixin,
|
||||
DataImportExportSerializerMixin,
|
||||
NotesFieldMixin,
|
||||
RemoteImageMixin,
|
||||
InvenTreeModelSerializer,
|
||||
):
|
||||
"""Serializer for Company object (full detail)."""
|
||||
|
|
@ -145,7 +140,6 @@ class CompanySerializer(
|
|||
'notes',
|
||||
'parts_supplied',
|
||||
'parts_manufactured',
|
||||
'remote_image',
|
||||
'primary_address',
|
||||
'tax_id',
|
||||
'parameters',
|
||||
|
|
@ -193,27 +187,6 @@ class CompanySerializer(
|
|||
|
||||
parameters = common.filters.enable_parameters_filter()
|
||||
|
||||
def save(self):
|
||||
"""Save the Company instance."""
|
||||
super().save()
|
||||
|
||||
company = self.instance
|
||||
|
||||
# Check if an image was downloaded from a remote URL
|
||||
remote_img = getattr(self, 'remote_image_file', None)
|
||||
|
||||
if remote_img and company:
|
||||
fmt = remote_img.format or 'PNG'
|
||||
buffer = io.BytesIO()
|
||||
remote_img.save(buffer, format=fmt)
|
||||
|
||||
# Construct a simplified name for the image
|
||||
filename = f'company_{company.pk}_image.{fmt.lower()}'
|
||||
|
||||
company.image.save(filename, ContentFile(buffer.getvalue()))
|
||||
|
||||
return self.instance
|
||||
|
||||
|
||||
@register_importer()
|
||||
class ContactSerializer(DataImportExportSerializerMixin, InvenTreeModelSerializer):
|
||||
|
|
|
|||
|
|
@ -232,8 +232,8 @@ class ApiTests(InvenTreeAPITestCase):
|
|||
"""Test the API endpoint for listing all status models."""
|
||||
response = self.get(reverse('api-status-all'))
|
||||
|
||||
# 10 built-in state classes, plus the added GeneralState class
|
||||
self.assertEqual(len(response.data), 11)
|
||||
# 11 built-in state classes, plus the added GeneralState class
|
||||
self.assertEqual(len(response.data), 12)
|
||||
|
||||
# Test the BuildStatus model
|
||||
build_status = response.data['BuildStatus']
|
||||
|
|
@ -273,7 +273,7 @@ class ApiTests(InvenTreeAPITestCase):
|
|||
)
|
||||
response = self.get(reverse('api-status-all'))
|
||||
|
||||
self.assertEqual(len(response.data), 11)
|
||||
self.assertEqual(len(response.data), 12)
|
||||
|
||||
stock_status_cstm = response.data['StockStatus']
|
||||
self.assertEqual(stock_status_cstm['status_class'], 'StockStatus')
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ class ImporterTest(ImporterMixin, InvenTreeTestCase):
|
|||
|
||||
session.extract_columns()
|
||||
|
||||
self.assertEqual(session.column_mappings.count(), 15)
|
||||
self.assertEqual(session.column_mappings.count(), 14)
|
||||
|
||||
# Check some of the field mappings
|
||||
for field, col in [
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -170,3 +170,41 @@ class ReturnOrderLineItemAdmin(admin.ModelAdmin):
|
|||
@admin.register(models.ReturnOrderExtraLine)
|
||||
class ReturnOrdeerExtraLineAdmin(GeneralExtraLineAdmin, admin.ModelAdmin):
|
||||
"""Admin class for the ReturnOrderExtraLine model."""
|
||||
|
||||
|
||||
class TransferOrderLineItemInlineAdmin(admin.StackedInline):
|
||||
"""Inline admin class for the TransferOrderLineItem model."""
|
||||
|
||||
autocomplete_fields = ['part']
|
||||
|
||||
model = models.TransferOrderLineItem
|
||||
extra = 0
|
||||
|
||||
|
||||
@admin.register(models.TransferOrder)
|
||||
class TransferOrderAdmin(admin.ModelAdmin):
|
||||
"""Admin class for the TransferOrder model."""
|
||||
|
||||
exclude = ['reference_int', 'address', 'contact']
|
||||
|
||||
list_display = (
|
||||
'reference',
|
||||
'status',
|
||||
'description',
|
||||
'take_from',
|
||||
'destination',
|
||||
'consume',
|
||||
'creation_date',
|
||||
)
|
||||
|
||||
search_fields = ['reference', 'description']
|
||||
|
||||
inlines = [TransferOrderLineItemInlineAdmin]
|
||||
|
||||
autocomplete_fields = [
|
||||
'created_by',
|
||||
'take_from',
|
||||
'destination',
|
||||
'project_code',
|
||||
'responsible',
|
||||
]
|
||||
|
|
|
|||
|
|
@ -56,6 +56,8 @@ from order.status_codes import (
|
|||
ReturnOrderStatus,
|
||||
SalesOrderStatus,
|
||||
SalesOrderStatusGroups,
|
||||
TransferOrderStatus,
|
||||
TransferOrderStatusGroups,
|
||||
)
|
||||
from part.models import Part
|
||||
from users.models import Owner
|
||||
|
|
@ -1766,6 +1768,521 @@ class ReturnOrderExtraLineDetail(RetrieveUpdateDestroyAPI):
|
|||
serializer_class = serializers.ReturnOrderExtraLineSerializer
|
||||
|
||||
|
||||
class TransferOrderFilter(OrderFilter):
|
||||
"""Custom API filters for the TransferOrderList endpoint."""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
model = models.TransferOrder
|
||||
fields = []
|
||||
|
||||
include_variants = rest_filters.BooleanFilter(
|
||||
label=_('Include Variants'), method='filter_include_variants'
|
||||
)
|
||||
|
||||
def filter_include_variants(self, queryset, name, value):
|
||||
"""Filter by whether or not to include variants of the selected part.
|
||||
|
||||
Note:
|
||||
- This filter does nothing by itself, and requires the 'part' filter to be set.
|
||||
- Refer to the 'filter_part' method for more information.
|
||||
"""
|
||||
return queryset
|
||||
|
||||
part = rest_filters.ModelChoiceFilter(
|
||||
queryset=Part.objects.all(), field_name='part', method='filter_part'
|
||||
)
|
||||
|
||||
@extend_schema_field(OpenApiTypes.INT)
|
||||
def filter_part(self, queryset, name, part):
|
||||
"""Filter by selected 'part'.
|
||||
|
||||
Note:
|
||||
- If 'include_variants' is set to True, then all variants of the selected part will be included.
|
||||
- Otherwise, just filter by the selected part.
|
||||
"""
|
||||
include_variants = str2bool(self.data.get('include_variants', False))
|
||||
|
||||
if include_variants:
|
||||
parts = part.get_descendants(include_self=True)
|
||||
else:
|
||||
parts = Part.objects.filter(pk=part.pk)
|
||||
|
||||
# Now that we have a queryset of parts, find all the matching return orders
|
||||
line_items = models.TransferOrderLineItem.objects.filter(part__in=parts)
|
||||
|
||||
# Generate a list of ID values for the matching transfer orders
|
||||
transfer_orders = line_items.values_list('order', flat=True).distinct()
|
||||
|
||||
# Now we have a list of matching IDs, filter the queryset
|
||||
return queryset.filter(pk__in=transfer_orders)
|
||||
|
||||
completed_before = InvenTreeDateFilter(
|
||||
label=_('Completed Before'), field_name='complete_date', lookup_expr='lt'
|
||||
)
|
||||
|
||||
completed_after = InvenTreeDateFilter(
|
||||
label=_('Completed After'), field_name='complete_date', lookup_expr='gt'
|
||||
)
|
||||
|
||||
|
||||
class TransferOrderMixin(SerializerContextMixin):
|
||||
"""Mixin class for TransferOrder endpoints."""
|
||||
|
||||
queryset = models.TransferOrder.objects.all()
|
||||
serializer_class = serializers.TransferOrderSerializer
|
||||
|
||||
def get_queryset(self, *args, **kwargs):
|
||||
"""Return annotated queryset for this endpoint."""
|
||||
queryset = super().get_queryset(*args, **kwargs)
|
||||
queryset = serializers.TransferOrderSerializer.annotate_queryset(queryset)
|
||||
queryset = queryset.prefetch_related('created_by', 'responsible')
|
||||
|
||||
return queryset
|
||||
|
||||
|
||||
class TransferOrderList(
|
||||
TransferOrderMixin,
|
||||
OrderCreateMixin,
|
||||
DataExportViewMixin,
|
||||
OutputOptionsMixin,
|
||||
ParameterListMixin,
|
||||
ListCreateAPI,
|
||||
):
|
||||
"""API endpoint for accessing a list of TransferOrder objects."""
|
||||
|
||||
filterset_class = TransferOrderFilter
|
||||
filter_backends = SEARCH_ORDER_FILTER
|
||||
|
||||
# TODO:
|
||||
# output_options = TransferOrderOutputOptions
|
||||
|
||||
ordering_field_aliases = {
|
||||
'reference': ['reference_int', 'reference'],
|
||||
'project_code': ['project_code__code'],
|
||||
}
|
||||
|
||||
ordering_fields = [
|
||||
'creation_date',
|
||||
'created_by',
|
||||
'reference',
|
||||
'line_items',
|
||||
'status',
|
||||
'start_date',
|
||||
'target_date',
|
||||
'complete_date',
|
||||
'project_code',
|
||||
]
|
||||
|
||||
search_fields = ['reference', 'description', 'project_code__code']
|
||||
|
||||
ordering = '-reference'
|
||||
|
||||
|
||||
class TransferOrderDetail(
|
||||
TransferOrderMixin, OutputOptionsMixin, RetrieveUpdateDestroyAPI
|
||||
):
|
||||
"""API endpoint for detail view of a single TransferOrder object."""
|
||||
|
||||
# output_options = TransferOrderOutputOptions
|
||||
|
||||
|
||||
class TransferOrderContextMixin:
|
||||
"""Simple mixin class to add a TransferOrder to the serializer context."""
|
||||
|
||||
queryset = models.TransferOrder.objects.all()
|
||||
|
||||
def get_serializer_context(self):
|
||||
"""Add the TransferOrder object to the serializer context."""
|
||||
context = super().get_serializer_context()
|
||||
|
||||
# Pass the Transfer instance through to the serializer for validation
|
||||
try:
|
||||
context['order'] = models.TransferOrder.objects.get(
|
||||
pk=self.kwargs.get('pk', None)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
context['request'] = self.request
|
||||
|
||||
return context
|
||||
|
||||
|
||||
class TransferOrderCancel(TransferOrderContextMixin, CreateAPI):
|
||||
"""API endpoint to cancel a TransferOrder."""
|
||||
|
||||
serializer_class = serializers.TransferOrderCancelSerializer
|
||||
|
||||
|
||||
class TransferOrderHold(TransferOrderContextMixin, CreateAPI):
|
||||
"""API endpoint to hold a TransferOrder."""
|
||||
|
||||
serializer_class = serializers.TransferOrderHoldSerializer
|
||||
|
||||
|
||||
class TransferOrderComplete(TransferOrderContextMixin, CreateAPI):
|
||||
"""API endpoint to complete a TransferOrder."""
|
||||
|
||||
serializer_class = serializers.TransferOrderCompleteSerializer
|
||||
|
||||
|
||||
class TransferOrderIssue(TransferOrderContextMixin, CreateAPI):
|
||||
"""API endpoint to issue a Transfer Order."""
|
||||
|
||||
serializer_class = serializers.TransferOrderIssueSerializer
|
||||
|
||||
|
||||
class TransferOrderAllocateSerials(TransferOrderContextMixin, CreateAPI):
|
||||
"""API endpoint to allocation stock items against a TransferOrder, by specifying serial numbers."""
|
||||
|
||||
queryset = models.TransferOrder.objects.none()
|
||||
serializer_class = serializers.TransferOrderSerialAllocationSerializer
|
||||
|
||||
|
||||
class TransferOrderAllocate(TransferOrderContextMixin, CreateAPI):
|
||||
"""API endpoint to allocate stock items against a TransferOrder.
|
||||
|
||||
- The TransferOrder is specified in the URL
|
||||
- See the TransferOrderAllocationSerializer class
|
||||
"""
|
||||
|
||||
queryset = models.TransferOrder.objects.none()
|
||||
serializer_class = serializers.TransferOrderLineItemAllocationSerializer
|
||||
|
||||
|
||||
class TransferOrderAllocationFilter(FilterSet):
|
||||
"""Custom filterset for the TransferOrderAllocationList endpoint."""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
model = models.TransferOrderAllocation
|
||||
fields = ['line', 'item']
|
||||
|
||||
order = rest_filters.ModelChoiceFilter(
|
||||
queryset=models.TransferOrder.objects.all(),
|
||||
field_name='line__order',
|
||||
label=_('Order'),
|
||||
)
|
||||
|
||||
include_variants = rest_filters.BooleanFilter(
|
||||
label=_('Include Variants'), method='filter_include_variants'
|
||||
)
|
||||
|
||||
def filter_include_variants(self, queryset, name, value):
|
||||
"""Filter by whether or not to include variants of the selected part.
|
||||
|
||||
Note:
|
||||
- This filter does nothing by itself, and requires the 'part' filter to be set.
|
||||
- Refer to the 'filter_part' method for more information.
|
||||
"""
|
||||
return queryset
|
||||
|
||||
part = rest_filters.ModelChoiceFilter(
|
||||
queryset=Part.objects.all(), method='filter_part', label=_('Part')
|
||||
)
|
||||
|
||||
@extend_schema_field(rest_framework.serializers.IntegerField(help_text=_('Part')))
|
||||
def filter_part(self, queryset, name, part):
|
||||
"""Filter by the 'part' attribute.
|
||||
|
||||
Note:
|
||||
- If "include_variants" is True, include all variants of the selected part
|
||||
- Otherwise, just filter by the selected part
|
||||
"""
|
||||
include_variants = str2bool(self.data.get('include_variants', False))
|
||||
|
||||
if include_variants:
|
||||
parts = part.get_descendants(include_self=True)
|
||||
return queryset.filter(item__part__in=parts)
|
||||
else:
|
||||
return queryset.filter(item__part=part)
|
||||
|
||||
outstanding = rest_filters.BooleanFilter(
|
||||
label=_('Outstanding'), method='filter_outstanding'
|
||||
)
|
||||
|
||||
def filter_outstanding(self, queryset, name, value):
|
||||
"""Filter by "outstanding" status (boolean)."""
|
||||
if str2bool(value):
|
||||
return queryset.filter(
|
||||
line__order__status__in=TransferOrderStatusGroups.OPEN
|
||||
# TODO: is there an additional filter here if we aren't using a "shipment"
|
||||
# shipment__shipment_date=None,
|
||||
)
|
||||
return queryset.exclude(
|
||||
# TODO: is there an additional filter here if we aren't using a "shipment"
|
||||
# shipment__shipment_date=None,
|
||||
line__order__status__in=TransferOrderStatusGroups.OPEN
|
||||
)
|
||||
|
||||
location = rest_filters.ModelChoiceFilter(
|
||||
queryset=stock_models.StockLocation.objects.all(),
|
||||
label=_('Location'),
|
||||
method='filter_location',
|
||||
)
|
||||
|
||||
@extend_schema_field(
|
||||
rest_framework.serializers.IntegerField(help_text=_('Location'))
|
||||
)
|
||||
def filter_location(self, queryset, name, location):
|
||||
"""Filter by the location of the allocated StockItem."""
|
||||
locations = location.get_descendants(include_self=True)
|
||||
return queryset.filter(item__location__in=locations)
|
||||
|
||||
|
||||
class TransferOrderAllocationMixin:
|
||||
"""Mixin class for TransferOrderAllocation endpoints."""
|
||||
|
||||
queryset = models.TransferOrderAllocation.objects.all()
|
||||
serializer_class = serializers.TransferOrderAllocationSerializer
|
||||
|
||||
def get_queryset(self, *args, **kwargs):
|
||||
"""Annotate the queryset for this endpoint."""
|
||||
queryset = super().get_queryset(*args, **kwargs)
|
||||
|
||||
queryset = queryset.prefetch_related(
|
||||
'item',
|
||||
'item__sales_order',
|
||||
'item__part',
|
||||
'line__part',
|
||||
'item__location',
|
||||
'line__order',
|
||||
'line__order__responsible',
|
||||
'line__order__project_code',
|
||||
'line__order__project_code__responsible',
|
||||
).select_related('line__part__pricing_data', 'item__part__pricing_data')
|
||||
|
||||
return queryset
|
||||
|
||||
|
||||
class TransferOrderAllocationOutputOptions(OutputConfiguration):
|
||||
"""Output options for the TransferOrderAllocation endpoint."""
|
||||
|
||||
OPTIONS = [
|
||||
InvenTreeOutputOption('part_detail'),
|
||||
InvenTreeOutputOption('item_detail'),
|
||||
InvenTreeOutputOption('order_detail'),
|
||||
InvenTreeOutputOption('location_detail'),
|
||||
]
|
||||
|
||||
|
||||
class TransferOrderAllocationList(
|
||||
TransferOrderAllocationMixin, BulkUpdateMixin, OutputOptionsMixin, ListAPI
|
||||
):
|
||||
"""API endpoint for listing TransferOrderAllocation objects."""
|
||||
|
||||
filterset_class = TransferOrderAllocationFilter
|
||||
filter_backends = SEARCH_ORDER_FILTER
|
||||
output_options = TransferOrderAllocationOutputOptions
|
||||
|
||||
ordering_fields = [
|
||||
'quantity',
|
||||
'part',
|
||||
'serial',
|
||||
'IPN',
|
||||
'batch',
|
||||
'location',
|
||||
'order',
|
||||
]
|
||||
|
||||
ordering_field_aliases = {
|
||||
'IPN': 'item__part__IPN',
|
||||
'part': 'item__part__name',
|
||||
'serial': ['item__serial_int', 'item__serial'],
|
||||
'batch': 'item__batch',
|
||||
'location': 'item__location__name',
|
||||
'order': 'line__order__reference',
|
||||
}
|
||||
|
||||
search_fields = {
|
||||
'item__part__name',
|
||||
'item__part__IPN',
|
||||
'item__serial',
|
||||
'item__batch',
|
||||
}
|
||||
|
||||
|
||||
class TransferOrderAllocationDetail(
|
||||
TransferOrderAllocationMixin, RetrieveUpdateDestroyAPI
|
||||
):
|
||||
"""API endpoint for detail view of a TransferOrderAllocation object."""
|
||||
|
||||
|
||||
class TransferOrderLineItemFilter(LineItemFilter):
|
||||
"""Custom filters for TransferOrderLineItemList endpoint."""
|
||||
|
||||
class Meta:
|
||||
"""Metaclass options."""
|
||||
|
||||
model = models.TransferOrderLineItem
|
||||
fields = []
|
||||
|
||||
order = rest_filters.ModelChoiceFilter(
|
||||
queryset=models.TransferOrder.objects.all(),
|
||||
field_name='order',
|
||||
label=_('Order'),
|
||||
)
|
||||
|
||||
def filter_include_variants(self, queryset, name, value):
|
||||
"""Filter by whether or not to include variants of the selected part.
|
||||
|
||||
Note:
|
||||
- This filter does nothing by itself, and requires the 'part' filter to be set.
|
||||
- Refer to the 'filter_part' method for more information.
|
||||
"""
|
||||
return queryset
|
||||
|
||||
part = rest_filters.ModelChoiceFilter(
|
||||
queryset=Part.objects.all(),
|
||||
field_name='part',
|
||||
label=_('Part'),
|
||||
method='filter_part',
|
||||
)
|
||||
|
||||
@extend_schema_field(OpenApiTypes.INT)
|
||||
def filter_part(self, queryset, name, part):
|
||||
"""Filter TransferOrderLineItem by selected 'part'.
|
||||
|
||||
Note:
|
||||
- If 'include_variants' is set to True, then all variants of the selected part will be included.
|
||||
- Otherwise, just filter by the selected part.
|
||||
"""
|
||||
include_variants = str2bool(self.data.get('include_variants', False))
|
||||
|
||||
# Construct a queryset of parts to filter by
|
||||
if include_variants:
|
||||
parts = part.get_descendants(include_self=True)
|
||||
else:
|
||||
parts = Part.objects.filter(pk=part.pk)
|
||||
|
||||
return queryset.filter(part__in=parts)
|
||||
|
||||
allocated = rest_filters.BooleanFilter(
|
||||
label=_('Allocated'), method='filter_allocated'
|
||||
)
|
||||
|
||||
def filter_allocated(self, queryset, name, value):
|
||||
"""Filter by lines which are 'allocated'.
|
||||
|
||||
A line is 'allocated' when allocated >= quantity
|
||||
"""
|
||||
q = Q(allocated__gte=F('quantity'))
|
||||
|
||||
if str2bool(value):
|
||||
return queryset.filter(q)
|
||||
return queryset.exclude(q)
|
||||
|
||||
completed = rest_filters.BooleanFilter(
|
||||
label=_('Completed'), method='filter_completed'
|
||||
)
|
||||
|
||||
def filter_completed(self, queryset, name, value):
|
||||
"""Filter by lines which are "completed".
|
||||
|
||||
A line is 'completed' when transferred >= quantity
|
||||
"""
|
||||
q = Q(transferred__gte=F('quantity'))
|
||||
|
||||
if str2bool(value):
|
||||
return queryset.filter(q)
|
||||
return queryset.exclude(q)
|
||||
|
||||
order_complete = rest_filters.BooleanFilter(
|
||||
label=_('Order Complete'), method='filter_order_complete'
|
||||
)
|
||||
|
||||
def filter_order_complete(self, queryset, name, value):
|
||||
"""Filter by whether the order is 'complete' or not."""
|
||||
if str2bool(value):
|
||||
return queryset.filter(order__status__in=TransferOrderStatusGroups.COMPLETE)
|
||||
|
||||
return queryset.exclude(order__status__in=TransferOrderStatusGroups.COMPLETE)
|
||||
|
||||
order_outstanding = rest_filters.BooleanFilter(
|
||||
label=_('Order Outstanding'), method='filter_order_outstanding'
|
||||
)
|
||||
|
||||
def filter_order_outstanding(self, queryset, name, value):
|
||||
"""Filter by whether the order is 'outstanding' or not."""
|
||||
if str2bool(value):
|
||||
return queryset.filter(order__status__in=TransferOrderStatusGroups.OPEN)
|
||||
|
||||
return queryset.exclude(order__status__in=TransferOrderStatusGroups.OPEN)
|
||||
|
||||
|
||||
class TransferOrderLineItemMixin(SerializerContextMixin):
|
||||
"""Mixin class for TransferOrderLineItem endpoints."""
|
||||
|
||||
queryset = models.TransferOrderLineItem.objects.all()
|
||||
serializer_class = serializers.TransferOrderLineItemSerializer
|
||||
|
||||
def get_queryset(self, *args, **kwargs):
|
||||
"""Return annotated queryset for this endpoint."""
|
||||
queryset = super().get_queryset(*args, **kwargs)
|
||||
|
||||
queryset = queryset.prefetch_related(
|
||||
'part',
|
||||
'allocations',
|
||||
# 'allocations__transfer',
|
||||
'allocations__item__part',
|
||||
'allocations__item__location',
|
||||
'order',
|
||||
)
|
||||
|
||||
queryset = serializers.TransferOrderLineItemSerializer.annotate_queryset(
|
||||
queryset
|
||||
)
|
||||
|
||||
return queryset
|
||||
|
||||
|
||||
class TransferOrderLineItemOutputOptions(OutputConfiguration):
|
||||
"""Output options for the TransferOrderAllocation endpoint."""
|
||||
|
||||
OPTIONS = [
|
||||
InvenTreeOutputOption('part_detail'),
|
||||
InvenTreeOutputOption('order_detail'),
|
||||
]
|
||||
|
||||
|
||||
class TransferOrderLineItemList(
|
||||
TransferOrderLineItemMixin, DataExportViewMixin, OutputOptionsMixin, ListCreateAPI
|
||||
):
|
||||
"""API endpoint for accessing a list of TransferOrderLineItem objects."""
|
||||
|
||||
filterset_class = TransferOrderLineItemFilter
|
||||
|
||||
filter_backends = SEARCH_ORDER_FILTER
|
||||
|
||||
output_options = TransferOrderLineItemOutputOptions
|
||||
|
||||
ordering_fields = [
|
||||
'order',
|
||||
'part',
|
||||
'part__name',
|
||||
'quantity',
|
||||
'allocated',
|
||||
'transferred',
|
||||
'reference',
|
||||
'target_date',
|
||||
]
|
||||
|
||||
ordering_field_aliases = {'part': 'part__name', 'order': 'order__reference'}
|
||||
|
||||
search_fields = ['part__name', 'quantity', 'reference']
|
||||
|
||||
|
||||
class TransferOrderLineItemDetail(
|
||||
TransferOrderLineItemMixin, OutputOptionsMixin, RetrieveUpdateDestroyAPI
|
||||
):
|
||||
"""API endpoint for detail view of a TransferOrderLineItem object."""
|
||||
|
||||
output_options = TransferOrderLineItemOutputOptions
|
||||
|
||||
|
||||
class OrderCalendarExport(ICalFeed):
|
||||
"""Calendar export for Purchase/Sales Orders.
|
||||
|
||||
|
|
@ -1844,6 +2361,8 @@ class OrderCalendarExport(ICalFeed):
|
|||
ordertype_title = _('Sales Order')
|
||||
elif obj['ordertype'] == 'return-order':
|
||||
ordertype_title = _('Return Order')
|
||||
elif obj['ordertype'] == 'transfer-order':
|
||||
ordertype_title = _('Transfer Order')
|
||||
else:
|
||||
ordertype_title = _('Unknown')
|
||||
|
||||
|
|
@ -1889,6 +2408,15 @@ class OrderCalendarExport(ICalFeed):
|
|||
).filter(status__lt=ReturnOrderStatus.COMPLETE.value)
|
||||
else:
|
||||
outlist = models.ReturnOrder.objects.filter(target_date__isnull=False)
|
||||
elif obj['ordertype'] == 'transfer-order':
|
||||
if obj['include_completed'] is False:
|
||||
# Do not include completed orders from list in this case
|
||||
# Complete status = 30
|
||||
outlist = models.TransferOrder.objects.filter(
|
||||
target_date__isnull=False
|
||||
).filter(status__lt=TransferOrderStatus.COMPLETE.value)
|
||||
else:
|
||||
outlist = models.TransferOrder.objects.filter(target_date__isnull=False)
|
||||
else:
|
||||
outlist = []
|
||||
|
||||
|
|
@ -1900,7 +2428,12 @@ class OrderCalendarExport(ICalFeed):
|
|||
|
||||
def item_description(self, item):
|
||||
"""Set the event description."""
|
||||
return f'Company: {item.company.name}\nStatus: {item.get_status_display()}\nDescription: {item.description}'
|
||||
if hasattr(item, 'company') and item.company:
|
||||
return f'Company: {item.company.name}\nStatus: {item.get_status_display()}\nDescription: {item.description}'
|
||||
else:
|
||||
return (
|
||||
f'Status: {item.get_status_display()}\nDescription: {item.description}'
|
||||
)
|
||||
|
||||
def item_start_datetime(self, item):
|
||||
"""Set event start to target date. Goal is all-day event."""
|
||||
|
|
@ -2216,9 +2749,97 @@ order_api_urls = [
|
|||
),
|
||||
]),
|
||||
),
|
||||
# API endpoints for transfer orders
|
||||
path(
|
||||
'transfer-order/',
|
||||
include([
|
||||
# Transfer Order detail endpoints
|
||||
path(
|
||||
'<int:pk>/',
|
||||
include([
|
||||
path(
|
||||
'allocate/',
|
||||
TransferOrderAllocate.as_view(),
|
||||
name='api-transfer-order-allocate',
|
||||
),
|
||||
path(
|
||||
'allocate-serials/',
|
||||
TransferOrderAllocateSerials.as_view(),
|
||||
name='api-transfer-order-allocate-serials',
|
||||
),
|
||||
path(
|
||||
'cancel/',
|
||||
TransferOrderCancel.as_view(),
|
||||
name='api-transfer-order-cancel',
|
||||
),
|
||||
path(
|
||||
'hold/',
|
||||
TransferOrderHold.as_view(),
|
||||
name='api-transfer-order-hold',
|
||||
),
|
||||
path(
|
||||
'complete/',
|
||||
TransferOrderComplete.as_view(),
|
||||
name='api-transfer-order-complete',
|
||||
),
|
||||
path(
|
||||
'issue/',
|
||||
TransferOrderIssue.as_view(),
|
||||
name='api-transfer-order-issue',
|
||||
),
|
||||
meta_path(models.TransferOrder),
|
||||
path(
|
||||
'',
|
||||
TransferOrderDetail.as_view(),
|
||||
name='api-transfer-order-detail',
|
||||
),
|
||||
]),
|
||||
),
|
||||
# Transfer Order list
|
||||
path('', TransferOrderList.as_view(), name='api-transfer-order-list'),
|
||||
]),
|
||||
),
|
||||
# API endpoints for transfer order line items
|
||||
path(
|
||||
'transfer-order-line/',
|
||||
include([
|
||||
path(
|
||||
'<int:pk>/',
|
||||
include([
|
||||
meta_path(models.TransferOrderLineItem),
|
||||
path(
|
||||
'',
|
||||
TransferOrderLineItemDetail.as_view(),
|
||||
name='api-transfer-order-line-detail',
|
||||
),
|
||||
]),
|
||||
),
|
||||
path(
|
||||
'',
|
||||
TransferOrderLineItemList.as_view(),
|
||||
name='api-transfer-order-line-list',
|
||||
),
|
||||
]),
|
||||
),
|
||||
# API endpoints for sales order allocations
|
||||
path(
|
||||
'transfer-order-allocation/',
|
||||
include([
|
||||
path(
|
||||
'<int:pk>/',
|
||||
TransferOrderAllocationDetail.as_view(),
|
||||
name='api-transfer-order-allocation-detail',
|
||||
),
|
||||
path(
|
||||
'',
|
||||
TransferOrderAllocationList.as_view(),
|
||||
name='api-transfer-order-allocation-list',
|
||||
),
|
||||
]),
|
||||
),
|
||||
# API endpoint for subscribing to ICS calendar of purchase/sales/return orders
|
||||
re_path(
|
||||
r'^calendar/(?P<ordertype>purchase-order|sales-order|return-order)/calendar.ics',
|
||||
r'^calendar/(?P<ordertype>purchase-order|sales-order|return-order|transfer-order)/calendar.ics',
|
||||
OrderCalendarExport(),
|
||||
name='api-po-so-calendar',
|
||||
),
|
||||
|
|
|
|||
|
|
@ -37,3 +37,12 @@ class ReturnOrderEvents(BaseEventEnum):
|
|||
COMPLETED = 'returnorder.completed'
|
||||
CANCELLED = 'returnorder.cancelled'
|
||||
HOLD = 'returnorder.hold'
|
||||
|
||||
|
||||
class TransferOrderEvents(BaseEventEnum):
|
||||
"""Event enumeration for the PurchaseOrder models."""
|
||||
|
||||
ISSUED = 'transferorder.placed'
|
||||
COMPLETED = 'transferorder.completed'
|
||||
CANCELLED = 'transferorder.cancelled'
|
||||
HOLD = 'transferorder.hold'
|
||||
|
|
|
|||
|
|
@ -0,0 +1,68 @@
|
|||
- model: order.transferorder
|
||||
pk: 1
|
||||
fields:
|
||||
reference: 'TO-123'
|
||||
description: "One transfer order, please"
|
||||
status: 10 # Pending
|
||||
|
||||
- model: order.transferorder
|
||||
pk: 2
|
||||
fields:
|
||||
reference: 'TO-124'
|
||||
description: "One transfer order, please"
|
||||
status: 40 # Cancelled
|
||||
|
||||
- model: order.transferorder
|
||||
pk: 3
|
||||
fields:
|
||||
reference: 'TO-125'
|
||||
description: "One transfer order, please"
|
||||
status: 25 # On Hold
|
||||
|
||||
- model: order.transferorder
|
||||
pk: 4
|
||||
fields:
|
||||
reference: 'TO-126'
|
||||
description: "One transfer order, please"
|
||||
status: 20 # Issued
|
||||
|
||||
- model: order.transferorder
|
||||
pk: 5
|
||||
fields:
|
||||
reference: 'TO-127'
|
||||
description: "One transfer order, please"
|
||||
status: 30 # Complete
|
||||
|
||||
|
||||
# Line items for transfer orders
|
||||
- model: order.transferorderlineitem
|
||||
pk: 1
|
||||
fields:
|
||||
order: 5 # the completed order
|
||||
part: 10001 # blue chair
|
||||
quantity: 1
|
||||
|
||||
- model: order.transferorderlineitem
|
||||
pk: 2
|
||||
fields:
|
||||
order: 4 # the issued order
|
||||
part: 10001 # blue chair
|
||||
quantity: 1
|
||||
transferred: 1
|
||||
|
||||
# Allocations for transfer orders
|
||||
# an 'allocated' allocation
|
||||
- model: order.transferorderallocation
|
||||
pk: 1
|
||||
fields:
|
||||
line: 1 # the line item on the completed order
|
||||
item: 1 # stock item
|
||||
quantity: 1
|
||||
|
||||
# a 'complete' allocation
|
||||
- model: order.transferorderallocation
|
||||
pk: 2
|
||||
fields:
|
||||
line: 2 # the line item on the issued order
|
||||
item: 500 # stock item for the blue chair
|
||||
quantity: 1
|
||||
|
|
@ -0,0 +1,482 @@
|
|||
# Generated by Django 5.2.11 on 2026-02-27 22:00
|
||||
|
||||
import InvenTree.fields
|
||||
import InvenTree.models
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
import generic.states.fields
|
||||
import generic.states.states
|
||||
import generic.states.transition
|
||||
import generic.states.validators
|
||||
import order.status_codes
|
||||
import order.validators
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("common", "0041_auto_20251203_1244"),
|
||||
("company", "0077_delete_manufacturerpartparameter"),
|
||||
("order", "0117_purchaseorderextraline_line_int_and_more"),
|
||||
("part", "0146_auto_20251203_1241"),
|
||||
("stock", "0116_alter_stockitem_link"),
|
||||
("users", "0005_owner_model"),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="TransferOrder",
|
||||
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",
|
||||
),
|
||||
),
|
||||
("reference_int", models.BigIntegerField(default=0)),
|
||||
(
|
||||
"notes",
|
||||
InvenTree.fields.InvenTreeNotesField(
|
||||
blank=True,
|
||||
help_text="Markdown notes (optional)",
|
||||
max_length=50000,
|
||||
null=True,
|
||||
verbose_name="Notes",
|
||||
),
|
||||
),
|
||||
(
|
||||
"barcode_data",
|
||||
models.CharField(
|
||||
blank=True,
|
||||
help_text="Third party barcode data",
|
||||
max_length=500,
|
||||
verbose_name="Barcode Data",
|
||||
),
|
||||
),
|
||||
(
|
||||
"barcode_hash",
|
||||
models.CharField(
|
||||
blank=True,
|
||||
help_text="Unique hash of barcode data",
|
||||
max_length=128,
|
||||
verbose_name="Barcode Hash",
|
||||
),
|
||||
),
|
||||
(
|
||||
"description",
|
||||
models.CharField(
|
||||
blank=True,
|
||||
help_text="Order description (optional)",
|
||||
max_length=250,
|
||||
verbose_name="Description",
|
||||
),
|
||||
),
|
||||
(
|
||||
"link",
|
||||
InvenTree.fields.InvenTreeURLField(
|
||||
blank=True,
|
||||
help_text="Link to external page",
|
||||
max_length=2000,
|
||||
verbose_name="Link",
|
||||
),
|
||||
),
|
||||
(
|
||||
"start_date",
|
||||
models.DateField(
|
||||
blank=True,
|
||||
help_text="Scheduled start date for this order",
|
||||
null=True,
|
||||
verbose_name="Start date",
|
||||
),
|
||||
),
|
||||
(
|
||||
"target_date",
|
||||
models.DateField(
|
||||
blank=True,
|
||||
help_text="Expected date for order delivery. Order will be overdue after this date.",
|
||||
null=True,
|
||||
verbose_name="Target Date",
|
||||
),
|
||||
),
|
||||
(
|
||||
"creation_date",
|
||||
models.DateField(
|
||||
blank=True, null=True, verbose_name="Creation Date"
|
||||
),
|
||||
),
|
||||
(
|
||||
"issue_date",
|
||||
models.DateField(
|
||||
blank=True,
|
||||
help_text="Date order was issued",
|
||||
null=True,
|
||||
verbose_name="Issue Date",
|
||||
),
|
||||
),
|
||||
(
|
||||
"reference",
|
||||
models.CharField(
|
||||
default=order.validators.generate_next_transfer_order_reference,
|
||||
help_text="Transfer Order Reference",
|
||||
max_length=64,
|
||||
unique=True,
|
||||
validators=[order.validators.validate_transfer_order_reference],
|
||||
verbose_name="Reference",
|
||||
),
|
||||
),
|
||||
(
|
||||
"consume",
|
||||
models.BooleanField(
|
||||
default=False,
|
||||
help_text='Rather than transfer the stock to the destination, "consume" it, by removing transferred quantity from the allocated stock item',
|
||||
verbose_name="Consume Stock",
|
||||
),
|
||||
),
|
||||
(
|
||||
"complete_date",
|
||||
models.DateField(
|
||||
blank=True,
|
||||
help_text="Date order was completed",
|
||||
null=True,
|
||||
verbose_name="Completion Date",
|
||||
),
|
||||
),
|
||||
(
|
||||
"status_custom_key",
|
||||
generic.states.fields.ExtraInvenTreeCustomStatusModelField(
|
||||
blank=True,
|
||||
default=None,
|
||||
help_text="Additional status information for this item",
|
||||
null=True,
|
||||
validators=[
|
||||
generic.states.validators.CustomStatusCodeValidator(
|
||||
status_class=order.status_codes.TransferOrderStatus
|
||||
)
|
||||
],
|
||||
verbose_name="Custom status key",
|
||||
),
|
||||
),
|
||||
(
|
||||
"status",
|
||||
generic.states.fields.InvenTreeCustomStatusModelField(
|
||||
choices=[
|
||||
(10, "Pending"),
|
||||
(20, "Issued"),
|
||||
(25, "On Hold"),
|
||||
(30, "Complete"),
|
||||
(40, "Cancelled"),
|
||||
],
|
||||
default=10,
|
||||
help_text="Transfer order status",
|
||||
validators=[
|
||||
generic.states.validators.CustomStatusCodeValidator(
|
||||
status_class=order.status_codes.TransferOrderStatus
|
||||
)
|
||||
],
|
||||
verbose_name="Status",
|
||||
),
|
||||
),
|
||||
(
|
||||
"address",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
help_text="Company address for this order",
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="+",
|
||||
to="company.address",
|
||||
verbose_name="Address",
|
||||
),
|
||||
),
|
||||
(
|
||||
"contact",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
help_text="Point of contact for this order",
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="+",
|
||||
to="company.contact",
|
||||
verbose_name="Contact",
|
||||
),
|
||||
),
|
||||
(
|
||||
"created_by",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="+",
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
verbose_name="Created By",
|
||||
),
|
||||
),
|
||||
(
|
||||
"destination",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
help_text="Destination for transferred items",
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="incoming_transfers",
|
||||
to="stock.stocklocation",
|
||||
verbose_name="Destination Location",
|
||||
),
|
||||
),
|
||||
(
|
||||
"project_code",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
help_text="Select project code for this order",
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
to="common.projectcode",
|
||||
verbose_name="Project Code",
|
||||
),
|
||||
),
|
||||
(
|
||||
"responsible",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
help_text="User or group responsible for this order",
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="+",
|
||||
to="users.owner",
|
||||
verbose_name="Responsible",
|
||||
),
|
||||
),
|
||||
(
|
||||
"take_from",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
help_text="Source for transferred items",
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="sourcing_transfers",
|
||||
to="stock.stocklocation",
|
||||
verbose_name="Source Location",
|
||||
),
|
||||
),
|
||||
(
|
||||
"updated_at",
|
||||
models.DateTimeField(
|
||||
blank=True,
|
||||
help_text="Timestamp of last update",
|
||||
null=True,
|
||||
verbose_name="Updated At",
|
||||
),
|
||||
)
|
||||
],
|
||||
options={
|
||||
"verbose_name": "Transfer Order",
|
||||
},
|
||||
bases=(
|
||||
generic.states.states.StatusCodeMixin,
|
||||
generic.states.transition.StateTransitionMixin,
|
||||
InvenTree.models.InvenTreeAttachmentMixin,
|
||||
InvenTree.models.InvenTreePermissionCheckMixin,
|
||||
InvenTree.models.ContentTypeMixin,
|
||||
InvenTree.models.PluginValidationMixin,
|
||||
models.Model,
|
||||
),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="TransferOrderLineItem",
|
||||
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",
|
||||
),
|
||||
),
|
||||
(
|
||||
"quantity",
|
||||
InvenTree.fields.RoundingDecimalField(
|
||||
decimal_places=5,
|
||||
default=1,
|
||||
help_text="Item quantity",
|
||||
max_digits=15,
|
||||
validators=[django.core.validators.MinValueValidator(0)],
|
||||
verbose_name="Quantity",
|
||||
),
|
||||
),
|
||||
(
|
||||
"reference",
|
||||
models.CharField(
|
||||
blank=True,
|
||||
help_text="Line item reference",
|
||||
max_length=100,
|
||||
verbose_name="Reference",
|
||||
),
|
||||
),
|
||||
(
|
||||
"notes",
|
||||
models.CharField(
|
||||
blank=True,
|
||||
help_text="Line item notes",
|
||||
max_length=500,
|
||||
verbose_name="Notes",
|
||||
),
|
||||
),
|
||||
(
|
||||
"link",
|
||||
InvenTree.fields.InvenTreeURLField(
|
||||
blank=True,
|
||||
help_text="Link to external page",
|
||||
max_length=2000,
|
||||
verbose_name="Link",
|
||||
),
|
||||
),
|
||||
(
|
||||
"target_date",
|
||||
models.DateField(
|
||||
blank=True,
|
||||
help_text="Target date for this line item (leave blank to use the target date from the order)",
|
||||
null=True,
|
||||
verbose_name="Target Date",
|
||||
),
|
||||
),
|
||||
(
|
||||
"order",
|
||||
models.ForeignKey(
|
||||
help_text="Transfer Order",
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="lines",
|
||||
to="order.transferorder",
|
||||
verbose_name="Order",
|
||||
),
|
||||
),
|
||||
(
|
||||
"part",
|
||||
models.ForeignKey(
|
||||
help_text="Part",
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="transfer_order_line_items",
|
||||
to="part.part",
|
||||
verbose_name="Part",
|
||||
),
|
||||
),
|
||||
(
|
||||
"project_code",
|
||||
models.ForeignKey(
|
||||
blank=True,
|
||||
help_text="Select project code for this order",
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
to="common.projectcode",
|
||||
verbose_name="Project Code",
|
||||
),
|
||||
),
|
||||
(
|
||||
"transferred",
|
||||
InvenTree.fields.RoundingDecimalField(
|
||||
decimal_places=5,
|
||||
default=0,
|
||||
help_text="transferred quantity",
|
||||
max_digits=15,
|
||||
validators=[django.core.validators.MinValueValidator(0)],
|
||||
verbose_name="transferred",
|
||||
),
|
||||
),
|
||||
(
|
||||
"line",
|
||||
models.CharField(
|
||||
blank=True,
|
||||
default="",
|
||||
help_text="Line number for this item (optional)",
|
||||
max_length=20,
|
||||
verbose_name="Line Number",
|
||||
),
|
||||
)
|
||||
],
|
||||
options={
|
||||
"verbose_name": "Transfer Order Line Item",
|
||||
},
|
||||
bases=(
|
||||
InvenTree.models.ContentTypeMixin,
|
||||
InvenTree.models.PluginValidationMixin,
|
||||
models.Model,
|
||||
),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="TransferOrderAllocation",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.AutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
(
|
||||
"quantity",
|
||||
InvenTree.fields.RoundingDecimalField(
|
||||
decimal_places=5,
|
||||
default=1,
|
||||
help_text="Enter stock allocation quantity",
|
||||
max_digits=15,
|
||||
validators=[django.core.validators.MinValueValidator(0)],
|
||||
verbose_name="Quantity",
|
||||
),
|
||||
),
|
||||
(
|
||||
"item",
|
||||
models.ForeignKey(
|
||||
help_text="Select stock item to allocate",
|
||||
limit_choices_to={
|
||||
"belongs_to": None,
|
||||
"part__virtual": False,
|
||||
"sales_order": None,
|
||||
},
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="transfer_order_allocations",
|
||||
to="stock.stockitem",
|
||||
verbose_name="Item",
|
||||
),
|
||||
),
|
||||
(
|
||||
"line",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="allocations",
|
||||
to="order.transferorderlineitem",
|
||||
verbose_name="Line",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"verbose_name": "Transfer Order Allocation",
|
||||
},
|
||||
),
|
||||
]
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue