2
0
mirror of https://github.com/inventree/InvenTree.git synced 2026-07-06 07:00:39 +00:00

Merge branch 'master' into app-stock-coverage

This commit is contained in:
Matthias Mair
2024-09-23 22:55:40 +02:00
committed by GitHub
317 changed files with 96692 additions and 63439 deletions
+1 -1
View File
@@ -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@4dd16135b69a43b6c8efb853346f8437d92d3c93 # v3.26.6
uses: github/codeql-action/upload-sarif@8214744c546c1e5c8f03dde8fab3a7353211988d # v3.26.7
with:
sarif_file: results.sarif
+1 -1
View File
@@ -9,7 +9,7 @@
{
"label": "worker",
"type": "shell",
"command": "invoke int.worker",
"command": "invoke worker",
"problemMatcher": [],
},
{
+1 -1
View File
@@ -56,7 +56,7 @@ services:
inventree-dev-worker:
image: inventree-dev-image
build: *build_config
command: invoke int.worker
command: invoke worker
depends_on:
- inventree-dev-server
volumes:
+1 -1
View File
@@ -83,7 +83,7 @@ services:
# If you wish to specify a particular InvenTree version, do so here
image: inventree/inventree:${INVENTREE_TAG:-stable}
container_name: inventree-worker
command: invoke int.worker
command: invoke worker
depends_on:
- inventree-server
env_file:
+8
View File
@@ -56,3 +56,11 @@ If no match is found for the scanned barcode, the following error message is dis
## App Integration
Barcode scanning is a key feature of the [companion mobile app](../app/barcode.md).
## Barcode History
If enabled, InvenTree can retain logs of the most recent barcode scans. This can be very useful for debugging or auditing purpopes.
Refer to the [barcode settings](../settings/global.md#barcodes) to enable barcode history logging.
The barcode history can be viewed via the admin panel in the web interface.
+6
View File
@@ -4,6 +4,12 @@ title: Panel Mixin
## PanelMixin
!!! warning "Legacy User Interface"
This plugin mixin class is designed specifically for the the *legacy* user interface (which is rendered on the server using django templates). The new user interface (which is rendered on the client using React) does not support this mixin class. Instead, refer to the new [User Interface Mixin](./ui.md) class.
!!! warning "Deprecated Class"
This mixin class is considered deprecated, and will be removed in the 1.0.0 release.
The `PanelMixin` enables plugins to render custom content to "panels" on individual pages in the web interface.
Most pages in the web interface support multiple panels, which are selected via the sidebar menu on the left side of the screen:
+102
View File
@@ -0,0 +1,102 @@
---
title: User Interface Mixin
---
## User Interface Mixin
The *User Interface* mixin class provides a set of methods to implement custom functionality for the InvenTree web interface.
### Enable User Interface Mixin
To enable user interface plugins, the global setting `ENABLE_PLUGINS_INTERFACE` must be enabled, in the [plugin settings](../../settings/global.md#plugin-settings).
## 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:
{{ includefile("src/frontend/src/components/plugins/PluginContext.tsx", title="Plugin Context", fmt="javascript") }}
## Custom Panels
Many of the pages in the InvenTree web interface are built using a series of "panels" which are displayed on the page. Custom panels can be added to these pages, by implementing the `get_ui_panels` method:
::: plugin.base.integration.UserInterfaceMixin.UserInterfaceMixin.get_ui_panels
options:
show_bases: False
show_root_heading: False
show_root_toc_entry: False
show_sources: True
summary: False
members: []
The custom panels can display content which is generated either on the server side, or on the client side (see below).
### Server Side Rendering
The panel content can be generated on the server side, by returning a 'content' attribute in the response. This 'content' attribute is expected to be raw HTML, and is rendered directly into the page. This is particularly useful for displaying static content.
Server-side rendering is simple to implement, and can make use of the powerful Django templating system.
Refer to the [sample plugin](#sample-plugin) for an example of how to implement server side rendering for custom panels.
**Advantages:**
- Simple to implement
- Can use Django templates to render content
- Has access to the full InvenTree database, and content not available on the client side (via the API)
**Disadvantages:**
- Content is rendered on the server side, and cannot be updated without a page refresh
- Content is not interactive
### Client Side Rendering
The panel content can also be generated on the client side, by returning a 'source' attribute in the response. This 'source' attribute is expected to be a URL which points to a JavaScript file which will be loaded by the client.
Refer to the [sample plugin](#sample-plugin) for an example of how to implement client side rendering for custom panels.
#### Panel Render Function
The JavaScript file must implement a `renderPanel` function, which is called by the client when the panel is rendered. This function is passed two parameters:
- `target`: The HTML element which the panel content should be rendered into
- `context`: A dictionary of context data which can be used to render the panel content
**Example**
```javascript
export function renderPanel(target, context) {
target.innerHTML = "<h1>Hello, world!</h1>";
}
```
#### Panel Visibility Function
The JavaScript file can also implement a `isPanelHidden` function, which is called by the client to determine if the panel is displayed. This function is passed a single parameter, *context* - which is the same as the context data passed to the `renderPanel` function.
The `isPanelHidden` function should return a boolean value, which determines if the panel is displayed or not, based on the context data.
If the `isPanelHidden` function is not implemented, the panel will be displayed by default.
**Example**
```javascript
export function isPanelHidden(context) {
// Only visible for active parts
return context.model == 'part' && context.instance?.active;
}
```
## Sample Plugin
A sample plugin which implements custom user interface functionality is provided in the InvenTree source code:
::: plugin.samples.integration.user_interface_sample.SampleUserInterfacePlugin
options:
show_bases: False
show_root_heading: False
show_root_toc_entry: False
show_source: True
members: []
+1 -1
View File
@@ -107,7 +107,7 @@ The background worker process must be started separately to the web-server appli
From the top-level source directory, run the following command from a separate terminal, while the server is already running:
```
invoke int.worker
invoke worker
```
!!! info "Supervisor"
+3 -3
View File
@@ -90,6 +90,8 @@ Configuration of barcode functionality:
{{ globalsetting("BARCODE_WEBCAM_SUPPORT") }}
{{ globalsetting("BARCODE_SHOW_TEXT") }}
{{ globalsetting("BARCODE_GENERATION_PLUGIN") }}
{{ globalsetting("BARCODE_STORE_RESULTS") }}
{{ globalsetting("BARCODE_RESULTS_MAX_NUM") }}
### Pricing and Currency
@@ -121,8 +123,6 @@ Configuration of report generation:
{{ globalsetting("REPORT_DEFAULT_PAGE_SIZE") }}
{{ globalsetting("REPORT_DEBUG_MODE") }}
{{ globalsetting("REPORT_LOG_ERRORS") }}
{{ globalsetting("REPORT_ENABLE_TEST_REPORT") }}
{{ globalsetting("REPORT_ATTACH_TEST_REPORT") }}
### Parts
@@ -208,7 +208,6 @@ Refer to the [return order settings](../order/return_order.md#return-order-setti
### Plugin Settings
| Name | Description | Default | Units |
| ---- | ----------- | ------- | ----- |
{{ globalsetting("PLUGIN_ON_STARTUP") }}
@@ -218,3 +217,4 @@ Refer to the [return order settings](../order/return_order.md#return-order-setti
{{ globalsetting("ENABLE_PLUGINS_APP") }}
{{ globalsetting("ENABLE_PLUGINS_SCHEDULE") }}
{{ globalsetting("ENABLE_PLUGINS_EVENTS") }}
{{ globalsetting("ENABLE_PLUGINS_INTERFACE") }}
+1 -1
View File
@@ -52,7 +52,7 @@ source ./env/bin/activate
### Start Background Worker
```
(env) invoke int.worker
(env) invoke worker
```
This will start the background process manager in the current shell.
+1 -1
View File
@@ -26,7 +26,7 @@ The InvenTree server tries to locate the `config.yaml` configuration file on sta
The configuration file *template* can be found on [GitHub]({{ sourcefile("src/backend/InvenTree/config_template.yaml") }}), and is shown below:
{{ includefile("src/backend/InvenTree/config_template.yaml", "Configuration File Template", format="yaml") }}
{{ includefile("src/backend/InvenTree/config_template.yaml", "Configuration File Template", fmt="yaml") }}
!!! info "Template File"
The default configuration file (as defined by the template linked above) will be copied to the specified configuration file location on first run, if a configuration file is not found in that location.
+1 -1
View File
@@ -247,7 +247,7 @@ index 8adee63..dc3993c 100644
- image: inventree/inventree:${INVENTREE_TAG:-stable}
+ image: inventree/inventree:${INVENTREE_TAG:-stable}-custom
+ pull_policy: never
command: invoke int.worker
command: invoke worker
depends_on:
- inventree-server
```
+1
View File
@@ -213,6 +213,7 @@ nav:
- Schedule Mixin: extend/plugins/schedule.md
- Settings Mixin: extend/plugins/settings.md
- URL Mixin: extend/plugins/urls.md
- User Interface Mixin: extend/plugins/ui.md
- Validation Mixin: extend/plugins/validation.md
- Machines:
- Overview: extend/machines/overview.md
+110 -93
View File
@@ -173,9 +173,9 @@ idna==3.7 \
# anyio
# httpx
# requests
importlib-metadata==8.4.0 \
--hash=sha256:66f342cc6ac9818fc6ff340576acd24d65ba0b3efabb2b4ac08b598965a4a2f1 \
--hash=sha256:9a547d3bc3608b025f93d403fdd1aae741c24fbb8314df4b155675742ce303c5
importlib-metadata==8.5.0 \
--hash=sha256:45e54197d28b7a7f1559e60b95e7c567032b602131fbd588f1497f47880aa68b \
--hash=sha256:71522656f0abace1d072b9e5481a48f07c138e00f079c38c8f883823f9c26bd7
# via
# markdown
# mkdocs
@@ -301,17 +301,17 @@ mkdocs-get-deps==0.2.0 \
--hash=sha256:162b3d129c7fad9b19abfdcb9c1458a651628e4b1dea628ac68790fb3061c60c \
--hash=sha256:2bf11d0b133e77a0dd036abeeb06dec8775e46efa526dc70667d8863eefc6134
# via mkdocs
mkdocs-git-revision-date-localized-plugin==1.2.8 \
--hash=sha256:6e09c308bb27bcf36b211d17b74152ecc2837cdfc351237f70cffc723ef0fd99 \
--hash=sha256:c7ec3b1481ca23134269e84927bd8a5dc1aa359c0e515b832dbd5d25019b5748
mkdocs-git-revision-date-localized-plugin==1.2.9 \
--hash=sha256:dea5c8067c23df30275702a1708885500fadf0abfb595b60e698bffc79c7a423 \
--hash=sha256:df9a50873fba3a42ce9123885f8c53d589e90ef6c2443fe3280ef1e8d33c8f65
# via -r docs/requirements.in
mkdocs-include-markdown-plugin==6.2.2 \
--hash=sha256:d293950f6499d2944291ca7b9bc4a60e652bbfd3e3a42b564f6cceee268694e7 \
--hash=sha256:f2bd5026650492a581d2fd44be6c22f90391910d76582b96a34c264f2d17875d
# via -r docs/requirements.in
mkdocs-macros-plugin==1.0.5 \
--hash=sha256:f60e26f711f5a830ddf1e7980865bf5c0f1180db56109803cdd280073c1a050a \
--hash=sha256:fe348d75f01c911f362b6d998c57b3d85b505876dde69db924f2c512c395c328
mkdocs-macros-plugin==1.2.0 \
--hash=sha256:3e442f8f37aa69710a69b5389e6b6cd0f54f4fcaee354aa57a61735ba8f97d27 \
--hash=sha256:7603b85cb336d669e29a8a9cc3af8b90767ffdf6021b3e023d5ec2e0a1f927a7
# via -r docs/requirements.in
mkdocs-material==9.5.34 \
--hash=sha256:1e60ddf716cfb5679dfd65900b8a25d277064ed82d9a53cd5190e3f894df7840 \
@@ -342,7 +342,9 @@ neoteroi-mkdocs==1.1.0 \
packaging==24.0 \
--hash=sha256:2ddfb553fdf02fb784c234c7ba6ccc288296ceabec964ad2eae3777778130bc5 \
--hash=sha256:eb82c5e3e56209074766e6885bb04b8c38a0c015d0a30036ebe7ece34c9989e9
# via mkdocs
# via
# mkdocs
# mkdocs-macros-plugin
paginate==0.5.6 \
--hash=sha256:5e6007b6a9398177a7e1648d04fdd9f8c9766a1a945bceac82f1929e8c78af2d
# via mkdocs-material
@@ -443,86 +445,101 @@ pyyaml-env-tag==0.1 \
--hash=sha256:70092675bda14fdec33b31ba77e7543de9ddc88f2e5b99160396572d11525bdb \
--hash=sha256:af31106dec8a4d68c60207c1886031cbf839b68aa7abccdb19868200532c2069
# via mkdocs
regex==2024.7.24 \
--hash=sha256:01b689e887f612610c869421241e075c02f2e3d1ae93a037cb14f88ab6a8934c \
--hash=sha256:04ce29e2c5fedf296b1a1b0acc1724ba93a36fb14031f3abfb7abda2806c1535 \
--hash=sha256:0ffe3f9d430cd37d8fa5632ff6fb36d5b24818c5c986893063b4e5bdb84cdf24 \
--hash=sha256:18300a1d78cf1290fa583cd8b7cde26ecb73e9f5916690cf9d42de569c89b1ce \
--hash=sha256:185e029368d6f89f36e526764cf12bf8d6f0e3a2a7737da625a76f594bdfcbfc \
--hash=sha256:19c65b00d42804e3fbea9708f0937d157e53429a39b7c61253ff15670ff62cb5 \
--hash=sha256:228b0d3f567fafa0633aee87f08b9276c7062da9616931382993c03808bb68ce \
--hash=sha256:23acc72f0f4e1a9e6e9843d6328177ae3074b4182167e34119ec7233dfeccf53 \
--hash=sha256:25419b70ba00a16abc90ee5fce061228206173231f004437730b67ac77323f0d \
--hash=sha256:2dfbb8baf8ba2c2b9aa2807f44ed272f0913eeeba002478c4577b8d29cde215c \
--hash=sha256:2f1baff13cc2521bea83ab2528e7a80cbe0ebb2c6f0bfad15be7da3aed443908 \
--hash=sha256:33e2614a7ce627f0cdf2ad104797d1f68342d967de3695678c0cb84f530709f8 \
--hash=sha256:3426de3b91d1bc73249042742f45c2148803c111d1175b283270177fdf669024 \
--hash=sha256:382281306e3adaaa7b8b9ebbb3ffb43358a7bbf585fa93821300a418bb975281 \
--hash=sha256:3d974d24edb231446f708c455fd08f94c41c1ff4f04bcf06e5f36df5ef50b95a \
--hash=sha256:3f3b6ca8eae6d6c75a6cff525c8530c60e909a71a15e1b731723233331de4169 \
--hash=sha256:3fac296f99283ac232d8125be932c5cd7644084a30748fda013028c815ba3364 \
--hash=sha256:416c0e4f56308f34cdb18c3f59849479dde5b19febdcd6e6fa4d04b6c31c9faa \
--hash=sha256:438d9f0f4bc64e8dea78274caa5af971ceff0f8771e1a2333620969936ba10be \
--hash=sha256:43affe33137fcd679bdae93fb25924979517e011f9dea99163f80b82eadc7e53 \
--hash=sha256:44fc61b99035fd9b3b9453f1713234e5a7c92a04f3577252b45feefe1b327759 \
--hash=sha256:45104baae8b9f67569f0f1dca5e1f1ed77a54ae1cd8b0b07aba89272710db61e \
--hash=sha256:4fdd1384619f406ad9037fe6b6eaa3de2749e2e12084abc80169e8e075377d3b \
--hash=sha256:538d30cd96ed7d1416d3956f94d54e426a8daf7c14527f6e0d6d425fcb4cca52 \
--hash=sha256:558a57cfc32adcf19d3f791f62b5ff564922942e389e3cfdb538a23d65a6b610 \
--hash=sha256:5eefee9bfe23f6df09ffb6dfb23809f4d74a78acef004aa904dc7c88b9944b05 \
--hash=sha256:64bd50cf16bcc54b274e20235bf8edbb64184a30e1e53873ff8d444e7ac656b2 \
--hash=sha256:65fd3d2e228cae024c411c5ccdffae4c315271eee4a8b839291f84f796b34eca \
--hash=sha256:66b4c0731a5c81921e938dcf1a88e978264e26e6ac4ec96a4d21ae0354581ae0 \
--hash=sha256:68a8f8c046c6466ac61a36b65bb2395c74451df2ffb8458492ef49900efed293 \
--hash=sha256:6a1141a1dcc32904c47f6846b040275c6e5de0bf73f17d7a409035d55b76f289 \
--hash=sha256:6b9fc7e9cc983e75e2518496ba1afc524227c163e43d706688a6bb9eca41617e \
--hash=sha256:6f51f9556785e5a203713f5efd9c085b4a45aecd2a42573e2b5041881b588d1f \
--hash=sha256:7214477bf9bd195894cf24005b1e7b496f46833337b5dedb7b2a6e33f66d962c \
--hash=sha256:731fcd76bbdbf225e2eb85b7c38da9633ad3073822f5ab32379381e8c3c12e94 \
--hash=sha256:74007a5b25b7a678459f06559504f1eec2f0f17bca218c9d56f6a0a12bfffdad \
--hash=sha256:7a5486ca56c8869070a966321d5ab416ff0f83f30e0e2da1ab48815c8d165d46 \
--hash=sha256:7c479f5ae937ec9985ecaf42e2e10631551d909f203e31308c12d703922742f9 \
--hash=sha256:7df9ea48641da022c2a3c9c641650cd09f0cd15e8908bf931ad538f5ca7919c9 \
--hash=sha256:7e37e809b9303ec3a179085415cb5f418ecf65ec98cdfe34f6a078b46ef823ee \
--hash=sha256:80c811cfcb5c331237d9bad3bea2c391114588cf4131707e84d9493064d267f9 \
--hash=sha256:836d3cc225b3e8a943d0b02633fb2f28a66e281290302a79df0e1eaa984ff7c1 \
--hash=sha256:84c312cdf839e8b579f504afcd7b65f35d60b6285d892b19adea16355e8343c9 \
--hash=sha256:86b17ba823ea76256b1885652e3a141a99a5c4422f4a869189db328321b73799 \
--hash=sha256:871e3ab2838fbcb4e0865a6e01233975df3a15e6fce93b6f99d75cacbd9862d1 \
--hash=sha256:88ecc3afd7e776967fa16c80f974cb79399ee8dc6c96423321d6f7d4b881c92b \
--hash=sha256:8bc593dcce679206b60a538c302d03c29b18e3d862609317cb560e18b66d10cf \
--hash=sha256:8fd5afd101dcf86a270d254364e0e8dddedebe6bd1ab9d5f732f274fa00499a5 \
--hash=sha256:945352286a541406f99b2655c973852da7911b3f4264e010218bbc1cc73168f2 \
--hash=sha256:973335b1624859cb0e52f96062a28aa18f3a5fc77a96e4a3d6d76e29811a0e6e \
--hash=sha256:994448ee01864501912abf2bad9203bffc34158e80fe8bfb5b031f4f8e16da51 \
--hash=sha256:9cfd009eed1a46b27c14039ad5bbc5e71b6367c5b2e6d5f5da0ea91600817506 \
--hash=sha256:a2ec4419a3fe6cf8a4795752596dfe0adb4aea40d3683a132bae9c30b81e8d73 \
--hash=sha256:a4997716674d36a82eab3e86f8fa77080a5d8d96a389a61ea1d0e3a94a582cf7 \
--hash=sha256:a512eed9dfd4117110b1881ba9a59b31433caed0c4101b361f768e7bcbaf93c5 \
--hash=sha256:a82465ebbc9b1c5c50738536fdfa7cab639a261a99b469c9d4c7dcbb2b3f1e57 \
--hash=sha256:ae2757ace61bc4061b69af19e4689fa4416e1a04840f33b441034202b5cd02d4 \
--hash=sha256:b16582783f44fbca6fcf46f61347340c787d7530d88b4d590a397a47583f31dd \
--hash=sha256:ba2537ef2163db9e6ccdbeb6f6424282ae4dea43177402152c67ef869cf3978b \
--hash=sha256:bf7a89eef64b5455835f5ed30254ec19bf41f7541cd94f266ab7cbd463f00c41 \
--hash=sha256:c0abb5e4e8ce71a61d9446040c1e86d4e6d23f9097275c5bd49ed978755ff0fe \
--hash=sha256:c414cbda77dbf13c3bc88b073a1a9f375c7b0cb5e115e15d4b73ec3a2fbc6f59 \
--hash=sha256:c51edc3541e11fbe83f0c4d9412ef6c79f664a3745fab261457e84465ec9d5a8 \
--hash=sha256:c5e69fd3eb0b409432b537fe3c6f44ac089c458ab6b78dcec14478422879ec5f \
--hash=sha256:c918b7a1e26b4ab40409820ddccc5d49871a82329640f5005f73572d5eaa9b5e \
--hash=sha256:c9bb87fdf2ab2370f21e4d5636e5317775e5d51ff32ebff2cf389f71b9b13750 \
--hash=sha256:ca5b2028c2f7af4e13fb9fc29b28d0ce767c38c7facdf64f6c2cd040413055f1 \
--hash=sha256:d0a07763776188b4db4c9c7fb1b8c494049f84659bb387b71c73bbc07f189e96 \
--hash=sha256:d33a0021893ede5969876052796165bab6006559ab845fd7b515a30abdd990dc \
--hash=sha256:d55588cba7553f0b6ec33130bc3e114b355570b45785cebdc9daed8c637dd440 \
--hash=sha256:dac8e84fff5d27420f3c1e879ce9929108e873667ec87e0c8eeb413a5311adfe \
--hash=sha256:eaef80eac3b4cfbdd6de53c6e108b4c534c21ae055d1dbea2de6b3b8ff3def38 \
--hash=sha256:eb462f0e346fcf41a901a126b50f8781e9a474d3927930f3490f38a6e73b6950 \
--hash=sha256:eb563dd3aea54c797adf513eeec819c4213d7dbfc311874eb4fd28d10f2ff0f2 \
--hash=sha256:f273674b445bcb6e4409bf8d1be67bc4b58e8b46fd0d560055d515b8830063cd \
--hash=sha256:f6442f0f0ff81775eaa5b05af8a0ffa1dda36e9cf6ec1e0d3d245e8564b684ce \
--hash=sha256:fb168b5924bef397b5ba13aabd8cf5df7d3d93f10218d7b925e360d436863f66 \
--hash=sha256:fbf8c2f00904eaf63ff37718eb13acf8e178cb940520e47b2f05027f5bb34ce3 \
--hash=sha256:fe4ebef608553aff8deb845c7f4f1d0740ff76fa672c011cc0bacb2a00fbde86
regex==2024.9.11 \
--hash=sha256:01c2acb51f8a7d6494c8c5eafe3d8e06d76563d8a8a4643b37e9b2dd8a2ff623 \
--hash=sha256:02087ea0a03b4af1ed6ebab2c54d7118127fee8d71b26398e8e4b05b78963199 \
--hash=sha256:040562757795eeea356394a7fb13076ad4f99d3c62ab0f8bdfb21f99a1f85664 \
--hash=sha256:042c55879cfeb21a8adacc84ea347721d3d83a159da6acdf1116859e2427c43f \
--hash=sha256:079400a8269544b955ffa9e31f186f01d96829110a3bf79dc338e9910f794fca \
--hash=sha256:07f45f287469039ffc2c53caf6803cd506eb5f5f637f1d4acb37a738f71dd066 \
--hash=sha256:09d77559e80dcc9d24570da3745ab859a9cf91953062e4ab126ba9d5993688ca \
--hash=sha256:0cbff728659ce4bbf4c30b2a1be040faafaa9eca6ecde40aaff86f7889f4ab39 \
--hash=sha256:0e12c481ad92d129c78f13a2a3662317e46ee7ef96c94fd332e1c29131875b7d \
--hash=sha256:0ea51dcc0835eea2ea31d66456210a4e01a076d820e9039b04ae8d17ac11dee6 \
--hash=sha256:0ffbcf9221e04502fc35e54d1ce9567541979c3fdfb93d2c554f0ca583a19b35 \
--hash=sha256:1494fa8725c285a81d01dc8c06b55287a1ee5e0e382d8413adc0a9197aac6408 \
--hash=sha256:16e13a7929791ac1216afde26f712802e3df7bf0360b32e4914dca3ab8baeea5 \
--hash=sha256:18406efb2f5a0e57e3a5881cd9354c1512d3bb4f5c45d96d110a66114d84d23a \
--hash=sha256:18e707ce6c92d7282dfce370cd205098384b8ee21544e7cb29b8aab955b66fa9 \
--hash=sha256:220e92a30b426daf23bb67a7962900ed4613589bab80382be09b48896d211e92 \
--hash=sha256:23b30c62d0f16827f2ae9f2bb87619bc4fba2044911e2e6c2eb1af0161cdb766 \
--hash=sha256:23f9985c8784e544d53fc2930fc1ac1a7319f5d5332d228437acc9f418f2f168 \
--hash=sha256:297f54910247508e6e5cae669f2bc308985c60540a4edd1c77203ef19bfa63ca \
--hash=sha256:2b08fce89fbd45664d3df6ad93e554b6c16933ffa9d55cb7e01182baaf971508 \
--hash=sha256:2cce2449e5927a0bf084d346da6cd5eb016b2beca10d0013ab50e3c226ffc0df \
--hash=sha256:313ea15e5ff2a8cbbad96ccef6be638393041b0a7863183c2d31e0c6116688cf \
--hash=sha256:323c1f04be6b2968944d730e5c2091c8c89767903ecaa135203eec4565ed2b2b \
--hash=sha256:35f4a6f96aa6cb3f2f7247027b07b15a374f0d5b912c0001418d1d55024d5cb4 \
--hash=sha256:3b37fa423beefa44919e009745ccbf353d8c981516e807995b2bd11c2c77d268 \
--hash=sha256:3ce4f1185db3fbde8ed8aa223fc9620f276c58de8b0d4f8cc86fd1360829edb6 \
--hash=sha256:46989629904bad940bbec2106528140a218b4a36bb3042d8406980be1941429c \
--hash=sha256:4838e24ee015101d9f901988001038f7f0d90dc0c3b115541a1365fb439add62 \
--hash=sha256:49b0e06786ea663f933f3710a51e9385ce0cba0ea56b67107fd841a55d56a231 \
--hash=sha256:4db21ece84dfeefc5d8a3863f101995de646c6cb0536952c321a2650aa202c36 \
--hash=sha256:54c4a097b8bc5bb0dfc83ae498061d53ad7b5762e00f4adaa23bee22b012e6ba \
--hash=sha256:54d9ff35d4515debf14bc27f1e3b38bfc453eff3220f5bce159642fa762fe5d4 \
--hash=sha256:55b96e7ce3a69a8449a66984c268062fbaa0d8ae437b285428e12797baefce7e \
--hash=sha256:57fdd2e0b2694ce6fc2e5ccf189789c3e2962916fb38779d3e3521ff8fe7a822 \
--hash=sha256:587d4af3979376652010e400accc30404e6c16b7df574048ab1f581af82065e4 \
--hash=sha256:5b513b6997a0b2f10e4fd3a1313568e373926e8c252bd76c960f96fd039cd28d \
--hash=sha256:5ddcd9a179c0a6fa8add279a4444015acddcd7f232a49071ae57fa6e278f1f71 \
--hash=sha256:6113c008a7780792efc80f9dfe10ba0cd043cbf8dc9a76ef757850f51b4edc50 \
--hash=sha256:635a1d96665f84b292e401c3d62775851aedc31d4f8784117b3c68c4fcd4118d \
--hash=sha256:64ce2799bd75039b480cc0360907c4fb2f50022f030bf9e7a8705b636e408fad \
--hash=sha256:69dee6a020693d12a3cf892aba4808fe168d2a4cef368eb9bf74f5398bfd4ee8 \
--hash=sha256:6a2644a93da36c784e546de579ec1806bfd2763ef47babc1b03d765fe560c9f8 \
--hash=sha256:6b41e1adc61fa347662b09398e31ad446afadff932a24807d3ceb955ed865cc8 \
--hash=sha256:6c188c307e8433bcb63dc1915022deb553b4203a70722fc542c363bf120a01fd \
--hash=sha256:6edd623bae6a737f10ce853ea076f56f507fd7726bee96a41ee3d68d347e4d16 \
--hash=sha256:73d6d2f64f4d894c96626a75578b0bf7d9e56dcda8c3d037a2118fdfe9b1c664 \
--hash=sha256:7a22ccefd4db3f12b526eccb129390942fe874a3a9fdbdd24cf55773a1faab1a \
--hash=sha256:7fb89ee5d106e4a7a51bce305ac4efb981536301895f7bdcf93ec92ae0d91c7f \
--hash=sha256:846bc79ee753acf93aef4184c040d709940c9d001029ceb7b7a52747b80ed2dd \
--hash=sha256:85ab7824093d8f10d44330fe1e6493f756f252d145323dd17ab6b48733ff6c0a \
--hash=sha256:8dee5b4810a89447151999428fe096977346cf2f29f4d5e29609d2e19e0199c9 \
--hash=sha256:8e5fb5f77c8745a60105403a774fe2c1759b71d3e7b4ca237a5e67ad066c7199 \
--hash=sha256:98eeee2f2e63edae2181c886d7911ce502e1292794f4c5ee71e60e23e8d26b5d \
--hash=sha256:9d4a76b96f398697fe01117093613166e6aa8195d63f1b4ec3f21ab637632963 \
--hash=sha256:9e8719792ca63c6b8340380352c24dcb8cd7ec49dae36e963742a275dfae6009 \
--hash=sha256:a0b2b80321c2ed3fcf0385ec9e51a12253c50f146fddb2abbb10f033fe3d049a \
--hash=sha256:a4cc92bb6db56ab0c1cbd17294e14f5e9224f0cc6521167ef388332604e92679 \
--hash=sha256:a738b937d512b30bf75995c0159c0ddf9eec0775c9d72ac0202076c72f24aa96 \
--hash=sha256:a8f877c89719d759e52783f7fe6e1c67121076b87b40542966c02de5503ace42 \
--hash=sha256:a906ed5e47a0ce5f04b2c981af1c9acf9e8696066900bf03b9d7879a6f679fc8 \
--hash=sha256:ae2941333154baff9838e88aa71c1d84f4438189ecc6021a12c7573728b5838e \
--hash=sha256:b0d0a6c64fcc4ef9c69bd5b3b3626cc3776520a1637d8abaa62b9edc147a58f7 \
--hash=sha256:b5b029322e6e7b94fff16cd120ab35a253236a5f99a79fb04fda7ae71ca20ae8 \
--hash=sha256:b7aaa315101c6567a9a45d2839322c51c8d6e81f67683d529512f5bcfb99c802 \
--hash=sha256:be1c8ed48c4c4065ecb19d882a0ce1afe0745dfad8ce48c49586b90a55f02366 \
--hash=sha256:c0256beda696edcf7d97ef16b2a33a8e5a875affd6fa6567b54f7c577b30a137 \
--hash=sha256:c157bb447303070f256e084668b702073db99bbb61d44f85d811025fcf38f784 \
--hash=sha256:c57d08ad67aba97af57a7263c2d9006d5c404d721c5f7542f077f109ec2a4a29 \
--hash=sha256:c69ada171c2d0e97a4b5aa78fbb835e0ffbb6b13fc5da968c09811346564f0d3 \
--hash=sha256:c94bb0a9f1db10a1d16c00880bdebd5f9faf267273b8f5bd1878126e0fbde771 \
--hash=sha256:cb130fccd1a37ed894824b8c046321540263013da72745d755f2d35114b81a60 \
--hash=sha256:ced479f601cd2f8ca1fd7b23925a7e0ad512a56d6e9476f79b8f381d9d37090a \
--hash=sha256:d05ac6fa06959c4172eccd99a222e1fbf17b5670c4d596cb1e5cde99600674c4 \
--hash=sha256:d552c78411f60b1fdaafd117a1fca2f02e562e309223b9d44b7de8be451ec5e0 \
--hash=sha256:dd4490a33eb909ef5078ab20f5f000087afa2a4daa27b4c072ccb3cb3050ad84 \
--hash=sha256:df5cbb1fbc74a8305b6065d4ade43b993be03dbe0f8b30032cced0d7740994bd \
--hash=sha256:e28f9faeb14b6f23ac55bfbbfd3643f5c7c18ede093977f1df249f73fd22c7b1 \
--hash=sha256:e464b467f1588e2c42d26814231edecbcfe77f5ac414d92cbf4e7b55b2c2a776 \
--hash=sha256:e4c22e1ac1f1ec1e09f72e6c44d8f2244173db7eb9629cc3a346a8d7ccc31142 \
--hash=sha256:e53b5fbab5d675aec9f0c501274c467c0f9a5d23696cfc94247e1fb56501ed89 \
--hash=sha256:e93f1c331ca8e86fe877a48ad64e77882c0c4da0097f2212873a69bbfea95d0c \
--hash=sha256:e997fd30430c57138adc06bba4c7c2968fb13d101e57dd5bb9355bf8ce3fa7e8 \
--hash=sha256:e9a091b0550b3b0207784a7d6d0f1a00d1d1c8a11699c1a4d93db3fbefc3ad35 \
--hash=sha256:eab4bb380f15e189d1313195b062a6aa908f5bd687a0ceccd47c8211e9cf0d4a \
--hash=sha256:eb1ae19e64c14c7ec1995f40bd932448713d3c73509e82d8cd7744dc00e29e86 \
--hash=sha256:ecea58b43a67b1b79805f1a0255730edaf5191ecef84dbc4cc85eb30bc8b63b9 \
--hash=sha256:ee439691d8c23e76f9802c42a95cfeebf9d47cf4ffd06f18489122dbb0a7ad64 \
--hash=sha256:eee9130eaad130649fd73e5cd92f60e55708952260ede70da64de420cdcad554 \
--hash=sha256:f47cd43a5bfa48f86925fe26fbdd0a488ff15b62468abb5d2a1e092a4fb10e85 \
--hash=sha256:f6fff13ef6b5f29221d6904aa816c34701462956aa72a77f1f151a8ec4f56aeb \
--hash=sha256:f745ec09bc1b0bd15cfc73df6fa4f726dcc26bb16c23a03f9e3367d357eeedd0 \
--hash=sha256:f8404bf61298bb6f8224bb9176c1424548ee1181130818fcd2cbffddc768bed8 \
--hash=sha256:f9268774428ec173654985ce55fc6caf4c6d11ade0f6f914d48ef4719eb05ebb \
--hash=sha256:faa3c142464efec496967359ca99696c896c591c56c53506bac1ad465f66e919
# via mkdocs-material
requests==2.32.3 \
--hash=sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760 \
@@ -595,7 +612,7 @@ wcmatch==8.5.2 \
--hash=sha256:17d3ad3758f9d0b5b4dedc770b65420d4dac62e680229c287bf24c9db856a478 \
--hash=sha256:a70222b86dea82fb382dd87b73278c10756c138bd6f8f714e2183128887b9eb2
# via mkdocs-include-markdown-plugin
zipp==3.20.1 \
--hash=sha256:9960cd8967c8f85a56f920d5d507274e74f9ff813a0ab8889a5b5be2daf44064 \
--hash=sha256:c22b14cc4763c5a5b04134207736c107db42e9d3ef2d9779d465f5f1bcba572b
zipp==3.20.2 \
--hash=sha256:a817ac80d6cf4b23bf7f2828b7cabf326f15a001bea8b1f9b49631780ba28350 \
--hash=sha256:bc9eb26f4506fda01b81bcde0ca78103b6e62f991b381fec825435c836edbc29
# via importlib-metadata
+13 -1
View File
@@ -1,13 +1,25 @@
"""InvenTree API version information."""
# InvenTree API version
INVENTREE_API_VERSION = 253
INVENTREE_API_VERSION = 257
"""Increment this API version number whenever there is a significant change to the API that any clients need to know about."""
INVENTREE_API_TEXT = """
v257 - 2024-09-22 : https://github.com/inventree/InvenTree/pull/8150
- Adds API endpoint for reporting barcode scan history
v256 - 2024-09-19 : https://github.com/inventree/InvenTree/pull/7704
- Adjustments for "stocktake" (stock history) API endpoints
v255 - 2024-09-19 : https://github.com/inventree/InvenTree/pull/8145
- Enables copying line items when duplicating an order
v254 - 2024-09-14 : https://github.com/inventree/InvenTree/pull/7470
- Implements new API endpoints for enabling custom UI functionality via plugins
v253 - 2024-09-14 : https://github.com/inventree/InvenTree/pull/7944
- Adjustments for user API endpoints
@@ -10,6 +10,8 @@ Additionally, update the following files with the new locale code:
- /src/frontend/.linguirc file
- /src/frontend/src/contexts/LanguageContext.tsx
(and then run "invoke int.frontend-trans")
"""
from django.utils.translation import gettext_lazy as _
@@ -34,6 +36,7 @@ LOCALES = [
('it', _('Italian')),
('ja', _('Japanese')),
('ko', _('Korean')),
('lt', _('Lithuanian')),
('lv', _('Latvian')),
('nl', _('Dutch')),
('no', _('Norwegian')),
@@ -8,6 +8,7 @@ class Command(BaseCommand):
def handle(self, *args, **kwargs):
"""Run the management command."""
from plugin.staticfiles import collect_plugins_static_files
import plugin.staticfiles
collect_plugins_static_files()
plugin.staticfiles.collect_plugins_static_files()
plugin.staticfiles.clear_plugins_static_files()
@@ -180,5 +180,9 @@ class RetrieveUpdateDestroyAPI(CleanMixin, generics.RetrieveUpdateDestroyAPIView
"""View for retrieve, update and destroy API."""
class RetrieveDestroyAPI(generics.RetrieveDestroyAPIView):
"""View for retrieve and destroy API."""
class UpdateAPI(CleanMixin, generics.UpdateAPIView):
"""View for update API."""
+1 -1
View File
@@ -439,7 +439,7 @@ class ReferenceIndexingMixin(models.Model):
)
# Check that the reference field can be rebuild
cls.rebuild_reference_field(value, validate=True)
return cls.rebuild_reference_field(value, validate=True)
@classmethod
def rebuild_reference_field(cls, reference, validate=False):
+41 -26
View File
@@ -133,6 +133,34 @@ STATIC_URL = '/static/'
# Web URL endpoint for served media files
MEDIA_URL = '/media/'
# Are plugins enabled?
PLUGINS_ENABLED = get_boolean_setting(
'INVENTREE_PLUGINS_ENABLED', 'plugins_enabled', False
)
PLUGINS_INSTALL_DISABLED = get_boolean_setting(
'INVENTREE_PLUGIN_NOINSTALL', 'plugin_noinstall', False
)
PLUGIN_FILE = config.get_plugin_file()
# Plugin test settings
PLUGIN_TESTING = get_setting(
'INVENTREE_PLUGIN_TESTING', 'PLUGIN_TESTING', TESTING
) # Are plugins being tested?
PLUGIN_TESTING_SETUP = get_setting(
'INVENTREE_PLUGIN_TESTING_SETUP', 'PLUGIN_TESTING_SETUP', False
) # Load plugins from setup hooks in testing?
PLUGIN_TESTING_EVENTS = False # Flag if events are tested right now
PLUGIN_RETRY = get_setting(
'INVENTREE_PLUGIN_RETRY', 'PLUGIN_RETRY', 3, typecast=int
) # How often should plugin loading be tried?
PLUGIN_FILE_CHECKED = False # Was the plugin file checked?
STATICFILES_DIRS = []
# Translated Template settings
@@ -153,6 +181,12 @@ if DEBUG and 'collectstatic' not in sys.argv:
if web_dir.exists():
STATICFILES_DIRS.append(web_dir)
# Append directory for sample plugin static content (if in debug mode)
if PLUGINS_ENABLED:
print('Adding plugin sample static content')
STATICFILES_DIRS.append(BASE_DIR.joinpath('plugin', 'samples', 'static'))
print('-', STATICFILES_DIRS[-1])
STATFILES_I18_PROCESSORS = ['InvenTree.context.status_codes']
# Color Themes Directory
@@ -169,10 +203,11 @@ DBBACKUP_STORAGE = get_setting(
# Default backup configuration
DBBACKUP_STORAGE_OPTIONS = get_setting(
'INVENTREE_BACKUP_OPTIONS', 'backup_options', None
'INVENTREE_BACKUP_OPTIONS',
'backup_options',
default_value={'location': config.get_backup_dir()},
typecast=dict,
)
if DBBACKUP_STORAGE_OPTIONS is None:
DBBACKUP_STORAGE_OPTIONS = {'location': config.get_backup_dir()}
INVENTREE_ADMIN_ENABLED = get_boolean_setting(
'INVENTREE_ADMIN_ENABLED', config_key='admin_enabled', default_value=True
@@ -555,6 +590,9 @@ for key in db_keys:
# Check that required database configuration options are specified
required_keys = ['ENGINE', 'NAME']
# Ensure all database keys are upper case
db_config = {key.upper(): value for key, value in db_config.items()}
for key in required_keys:
if key not in db_config: # pragma: no cover
error_msg = f'Missing required database configuration value {key}'
@@ -1254,29 +1292,6 @@ IGNORED_ERRORS = [Http404, django.core.exceptions.PermissionDenied]
MAINTENANCE_MODE_RETRY_AFTER = 10
MAINTENANCE_MODE_STATE_BACKEND = 'InvenTree.backends.InvenTreeMaintenanceModeBackend'
# Are plugins enabled?
PLUGINS_ENABLED = get_boolean_setting(
'INVENTREE_PLUGINS_ENABLED', 'plugins_enabled', False
)
PLUGINS_INSTALL_DISABLED = get_boolean_setting(
'INVENTREE_PLUGIN_NOINSTALL', 'plugin_noinstall', False
)
PLUGIN_FILE = config.get_plugin_file()
# Plugin test settings
PLUGIN_TESTING = get_setting(
'INVENTREE_PLUGIN_TESTING', 'PLUGIN_TESTING', TESTING
) # Are plugins being tested?
PLUGIN_TESTING_SETUP = get_setting(
'INVENTREE_PLUGIN_TESTING_SETUP', 'PLUGIN_TESTING_SETUP', False
) # Load plugins from setup hooks in testing?
PLUGIN_TESTING_EVENTS = False # Flag if events are tested right now
PLUGIN_RETRY = get_setting(
'INVENTREE_PLUGIN_RETRY', 'PLUGIN_RETRY', 3, typecast=int
) # How often should plugin loading be tried?
PLUGIN_FILE_CHECKED = False # Was the plugin file checked?
# Flag to allow table events during testing
TESTING_TABLE_EVENTS = False
@@ -291,6 +291,18 @@ class InvenTreeAPITestCase(ExchangeRateMixin, UserMixin, APITestCase):
self.assertLess(n, value, msg=msg)
@classmethod
def setUpTestData(cls):
"""Setup for API tests.
- Ensure that all global settings are assigned default values.
"""
from common.models import InvenTreeSetting
InvenTreeSetting.build_default_values()
super().setUpTestData()
def check_response(self, url, response, expected_code=None):
"""Debug output for an unexpected response."""
# Check that the response returned the expected status code
+1 -1
View File
@@ -484,7 +484,7 @@ if settings.ENABLE_PLATFORM_FRONTEND:
urlpatterns += frontendpatterns
# Append custom plugin URLs (if plugin support is enabled)
# Append custom plugin URLs (if custom plugin support is enabled)
if settings.PLUGINS_ENABLED:
urlpatterns.append(get_plugin_urls())
+25
View File
@@ -0,0 +1,25 @@
"""Queryset filtering helper functions for the Build app."""
from django.db import models
from django.db.models import Sum, Q
from django.db.models.functions import Coalesce
def annotate_allocated_quantity(queryset: Q) -> Q:
"""
Annotate the 'allocated' quantity for each build item in the queryset.
Arguments:
queryset: The BuildLine queryset to annotate
"""
queryset = queryset.prefetch_related('allocations')
return queryset.annotate(
allocated=Coalesce(
Sum('allocations__quantity'), 0,
output_field=models.DecimalField()
)
)
+33 -19
View File
@@ -9,7 +9,7 @@ from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models, transaction
from django.db.models import Sum, Q
from django.db.models import F, Sum, Q
from django.db.models.functions import Coalesce
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
@@ -24,6 +24,7 @@ from rest_framework import serializers
from build.status_codes import BuildStatus, BuildStatusGroups
from stock.status_codes import StockStatus, StockHistoryCode
from build.filters import annotate_allocated_quantity
from build.validators import generate_next_build_reference, validate_build_order_reference
from generic.states import StateTransitionMixin
@@ -124,8 +125,7 @@ class Build(
def save(self, *args, **kwargs):
"""Custom save method for the BuildOrder model"""
self.validate_reference_field(self.reference)
self.reference_int = self.rebuild_reference_field(self.reference)
self.reference_int = self.validate_reference_field(self.reference)
# Check part when initially creating the build order
if not self.pk or self.has_field_changed('part'):
@@ -987,12 +987,13 @@ class Build(
items_to_save = []
items_to_delete = []
lines = self.untracked_line_items
lines = lines.prefetch_related('allocations')
lines = self.untracked_line_items.all()
lines = lines.exclude(bom_item__consumable=True)
lines = annotate_allocated_quantity(lines)
for build_line in lines:
reduce_by = build_line.allocated_quantity() - build_line.quantity
reduce_by = build_line.allocated - build_line.quantity
if reduce_by <= 0:
continue
@@ -1290,18 +1291,20 @@ class Build(
"""Returns a list of BuildLine objects which have not been fully allocated."""
lines = self.build_lines.all()
# Remove any 'consumable' line items
lines = lines.exclude(bom_item__consumable=True)
if tracked is True:
lines = lines.filter(bom_item__sub_part__trackable=True)
elif tracked is False:
lines = lines.filter(bom_item__sub_part__trackable=False)
unallocated_lines = []
lines = annotate_allocated_quantity(lines)
for line in lines:
if not line.is_fully_allocated():
unallocated_lines.append(line)
# Filter out any lines which have been fully allocated
lines = lines.filter(allocated__lt=F('quantity'))
return unallocated_lines
return lines
def is_fully_allocated(self, tracked=None):
"""Test if the BuildOrder has been fully allocated.
@@ -1314,19 +1317,24 @@ class Build(
Returns:
True if the BuildOrder has been fully allocated, otherwise False
"""
lines = self.unallocated_lines(tracked=tracked)
return len(lines) == 0
return self.unallocated_lines(tracked=tracked).count() == 0
def is_output_fully_allocated(self, output):
"""Determine if the specified output (StockItem) has been fully allocated for this build
Args:
output: StockItem object
output: StockItem object (the "in production" output to test against)
To determine if the output has been fully allocated,
we need to test all "trackable" BuildLine objects
"""
for line in self.build_lines.filter(bom_item__sub_part__trackable=True):
lines = self.build_lines.filter(bom_item__sub_part__trackable=True)
lines = lines.exclude(bom_item__consumable=True)
# Find any lines which have not been fully allocated
for line in lines:
# Grab all BuildItem objects which point to this output
allocations = BuildItem.objects.filter(
build_line=line,
@@ -1350,11 +1358,14 @@ class Build(
Returns:
True if any BuildLine has been over-allocated.
"""
for line in self.build_lines.all():
if line.is_overallocated():
return True
return False
lines = self.build_lines.all().exclude(bom_item__consumable=True)
lines = annotate_allocated_quantity(lines)
# Find any lines which have been over-allocated
lines = lines.filter(allocated__gt=F('quantity'))
return lines.count() > 0
@property
def is_active(self):
@@ -1692,6 +1703,9 @@ class BuildItem(InvenTree.models.InvenTreeMetadataModel):
- If the referenced part is trackable, the stock item will be *installed* into the build output
- If the referenced part is *not* trackable, the stock item will be *consumed* by the build order
TODO: This is quite expensive (in terms of number of database hits) - and requires some thought
"""
item = self.stock_item
+9
View File
@@ -35,6 +35,15 @@ class AttachmentAdmin(admin.ModelAdmin):
search_fields = ('content_type', 'comment')
@admin.register(common.models.BarcodeScanResult)
class BarcodeScanResultAdmin(admin.ModelAdmin):
"""Admin interface for BarcodeScanResult objects."""
list_display = ('data', 'timestamp', 'user', 'endpoint', 'result')
list_filter = ('user', 'endpoint', 'result')
@admin.register(common.models.ProjectCode)
class ProjectCodeAdmin(ImportExportModelAdmin):
"""Admin settings for ProjectCode."""
@@ -0,0 +1,34 @@
# Generated by Django 4.2.15 on 2024-09-21 06:05
import InvenTree.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('common', '0029_inventreecustomuserstatemodel'),
]
operations = [
migrations.CreateModel(
name='BarcodeScanResult',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('data', models.CharField(help_text='Barcode data', max_length=250, verbose_name='Data')),
('timestamp', models.DateTimeField(auto_now_add=True, help_text='Date and time of the barcode scan', verbose_name='Timestamp')),
('endpoint', models.CharField(blank=True, help_text='URL endpoint which processed the barcode', max_length=250, null=True, verbose_name='Path')),
('context', models.JSONField(blank=True, help_text='Context data for the barcode scan', max_length=1000, null=True, verbose_name='Context')),
('response', models.JSONField(blank=True, help_text='Response data from the barcode scan', max_length=1000, null=True, verbose_name='Response')),
('result', models.BooleanField(default=False, help_text='Was the barcode scan successful?', verbose_name='Result')),
('user', models.ForeignKey(blank=True, help_text='User who scanned the barcode', null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='User')),
],
options={
'verbose_name': 'Barcode Scan',
},
bases=(InvenTree.models.PluginValidationMixin, models.Model),
),
]
+84
View File
@@ -43,6 +43,7 @@ from taggit.managers import TaggableManager
import build.validators
import common.currency
import common.validators
import InvenTree.exceptions
import InvenTree.fields
import InvenTree.helpers
import InvenTree.models
@@ -1398,6 +1399,18 @@ class InvenTreeSetting(BaseInvenTreeSetting):
'default': True,
'validator': bool,
},
'BARCODE_STORE_RESULTS': {
'name': _('Store Barcode Results'),
'description': _('Store barcode scan results in the database'),
'default': False,
'validator': bool,
},
'BARCODE_RESULTS_MAX_NUM': {
'name': _('Barcode Scans Maximum Count'),
'description': _('Maximum number of barcode scan results to store'),
'default': 100,
'validator': [int, MinValueValidator(1)],
},
'BARCODE_INPUT_DELAY': {
'name': _('Barcode Input Delay'),
'description': _('Barcode input processing delay time'),
@@ -2095,6 +2108,13 @@ class InvenTreeSetting(BaseInvenTreeSetting):
'validator': bool,
'after_save': reload_plugin_registry,
},
'ENABLE_PLUGINS_INTERFACE': {
'name': _('Enable interface integration'),
'description': _('Enable plugins to integrate into the user interface'),
'default': False,
'validator': bool,
'after_save': reload_plugin_registry,
},
'PROJECT_CODES_ENABLED': {
'name': _('Enable project codes'),
'description': _('Enable project codes for tracking projects'),
@@ -3438,3 +3458,67 @@ class InvenTreeCustomUserStateModel(models.Model):
})
return super().clean()
class BarcodeScanResult(InvenTree.models.InvenTreeModel):
"""Model for storing barcode scans results."""
BARCODE_SCAN_MAX_LEN = 250
class Meta:
"""Model meta options."""
verbose_name = _('Barcode Scan')
data = models.CharField(
max_length=BARCODE_SCAN_MAX_LEN,
verbose_name=_('Data'),
help_text=_('Barcode data'),
blank=False,
null=False,
)
user = models.ForeignKey(
User,
on_delete=models.SET_NULL,
blank=True,
null=True,
verbose_name=_('User'),
help_text=_('User who scanned the barcode'),
)
timestamp = models.DateTimeField(
auto_now_add=True,
verbose_name=_('Timestamp'),
help_text=_('Date and time of the barcode scan'),
)
endpoint = models.CharField(
max_length=250,
verbose_name=_('Path'),
help_text=_('URL endpoint which processed the barcode'),
blank=True,
null=True,
)
context = models.JSONField(
max_length=1000,
verbose_name=_('Context'),
help_text=_('Context data for the barcode scan'),
blank=True,
null=True,
)
response = models.JSONField(
max_length=1000,
verbose_name=_('Response'),
help_text=_('Response data from the barcode scan'),
blank=True,
null=True,
)
result = models.BooleanField(
verbose_name=_('Result'),
help_text=_('Was the barcode scan successful?'),
default=False,
)
+14
View File
@@ -436,6 +436,13 @@ class SupplierPriceBreakList(ListCreateAPI):
serializer_class = SupplierPriceBreakSerializer
filterset_class = SupplierPriceBreakFilter
def get_queryset(self):
"""Return annotated queryset for the SupplierPriceBreak list endpoint."""
queryset = super().get_queryset()
queryset = SupplierPriceBreakSerializer.annotate_queryset(queryset)
return queryset
def get_serializer(self, *args, **kwargs):
"""Return serializer instance for this endpoint."""
try:
@@ -468,6 +475,13 @@ class SupplierPriceBreakDetail(RetrieveUpdateDestroyAPI):
queryset = SupplierPriceBreak.objects.all()
serializer_class = SupplierPriceBreakSerializer
def get_queryset(self):
"""Return annotated queryset for the SupplierPriceBreak list endpoint."""
queryset = super().get_queryset()
queryset = SupplierPriceBreakSerializer.annotate_queryset(queryset)
return queryset
manufacturer_part_api_urls = [
path(
@@ -512,6 +512,13 @@ class SupplierPriceBreakSerializer(
if not part_detail:
self.fields.pop('part_detail', None)
@staticmethod
def annotate_queryset(queryset):
"""Prefetch related fields for the queryset."""
queryset = queryset.select_related('part', 'part__supplier', 'part__part')
return queryset
quantity = InvenTreeDecimalField()
price = InvenTreeMoneySerializer(allow_null=True, required=True, label=_('Price'))
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
+22 -56
View File
@@ -5,7 +5,6 @@ from typing import cast
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.db import transaction
from django.db.models import F, Q
from django.http.response import JsonResponse
from django.urls import include, path, re_path
@@ -14,7 +13,6 @@ from django.utils.translation import gettext_lazy as _
from django_filters import rest_framework as rest_filters
from django_ical.views import ICalFeed
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
import common.models
@@ -214,54 +212,6 @@ class PurchaseOrderList(PurchaseOrderMixin, DataExportViewMixin, ListCreateAPI):
filterset_class = PurchaseOrderFilter
def create(self, request, *args, **kwargs):
"""Save user information on create."""
data = self.clean_data(request.data)
duplicate_order = data.pop('duplicate_order', None)
duplicate_line_items = str2bool(data.pop('duplicate_line_items', False))
duplicate_extra_lines = str2bool(data.pop('duplicate_extra_lines', False))
if duplicate_order is not None:
try:
duplicate_order = models.PurchaseOrder.objects.get(pk=duplicate_order)
except (ValueError, models.PurchaseOrder.DoesNotExist):
raise ValidationError({
'duplicate_order': [_('No matching purchase order found')]
})
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
with transaction.atomic():
order = serializer.save()
order.created_by = request.user
order.save()
# Duplicate line items from other order if required
if duplicate_order is not None:
if duplicate_line_items:
for line in duplicate_order.lines.all():
# Copy the line across to the new order
line.pk = None
line.order = order
line.received = 0
line.save()
if duplicate_extra_lines:
for line in duplicate_order.extra_lines.all():
# Copy the line across to the new order
line.pk = None
line.order = order
line.save()
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data, status=status.HTTP_201_CREATED, headers=headers
)
def filter_queryset(self, queryset):
"""Custom queryset filtering."""
# Perform basic filtering
@@ -1041,11 +991,30 @@ class SalesOrderShipmentFilter(rest_filters.FilterSet):
return queryset.filter(delivery_date=None)
class SalesOrderShipmentList(ListCreateAPI):
"""API list endpoint for SalesOrderShipment model."""
class SalesOrderShipmentMixin:
"""Mixin class for SalesOrderShipment endpoints."""
queryset = models.SalesOrderShipment.objects.all()
serializer_class = serializers.SalesOrderShipmentSerializer
def get_queryset(self, *args, **kwargs):
"""Return annotated queryset for this endpoint."""
queryset = super().get_queryset(*args, **kwargs)
queryset = queryset.prefetch_related(
'order',
'order__customer',
'allocations',
'allocations__item',
'allocations__item__part',
)
return queryset
class SalesOrderShipmentList(SalesOrderShipmentMixin, ListCreateAPI):
"""API list endpoint for SalesOrderShipment model."""
filterset_class = SalesOrderShipmentFilter
filter_backends = SEARCH_ORDER_FILTER_ALIAS
@@ -1053,12 +1022,9 @@ class SalesOrderShipmentList(ListCreateAPI):
ordering_fields = ['delivery_date', 'shipment_date']
class SalesOrderShipmentDetail(RetrieveUpdateDestroyAPI):
class SalesOrderShipmentDetail(SalesOrderShipmentMixin, RetrieveUpdateDestroyAPI):
"""API detail endpooint for SalesOrderShipment model."""
queryset = models.SalesOrderShipment.objects.all()
serializer_class = serializers.SalesOrderShipmentSerializer
class SalesOrderShipmentComplete(CreateAPI):
"""API endpoint for completing (shipping) a SalesOrderShipment."""
+26
View File
@@ -247,6 +247,16 @@ class Order(
'contact': _('Contact does not match selected company')
})
def clean_line_item(self, line):
"""Clean a line item for this order.
Used when duplicating an existing line item,
to ensure it is 'fresh'.
"""
line.pk = None
line.target_date = None
line.order = self
def report_context(self):
"""Generate context data for the reporting interface."""
return {
@@ -379,6 +389,11 @@ class PurchaseOrder(TotalPriceMixin, Order):
verbose_name = _('Purchase Order')
def clean_line_item(self, line):
"""Clean a line item for this PurchaseOrder."""
super().clean_line_item(line)
line.received = 0
def report_context(self):
"""Return report context data for this PurchaseOrder."""
return {**super().report_context(), 'supplier': self.supplier}
@@ -892,6 +907,11 @@ class SalesOrder(TotalPriceMixin, Order):
verbose_name = _('Sales Order')
def clean_line_item(self, line):
"""Clean a line item for this SalesOrder."""
super().clean_line_item(line)
line.shipped = 0
def report_context(self):
"""Generate report context data for this SalesOrder."""
return {**super().report_context(), 'customer': self.customer}
@@ -2083,6 +2103,12 @@ class ReturnOrder(TotalPriceMixin, Order):
verbose_name = _('Return Order')
def clean_line_item(self, line):
"""Clean a line item for this ReturnOrder."""
super().clean_line_item(line)
line.received_date = None
line.outcome = ReturnOrderLineStatus.PENDING.value
def report_context(self):
"""Generate report context data for this ReturnOrder."""
return {**super().report_context(), 'customer': self.customer}
+95 -1
View File
@@ -74,10 +74,39 @@ class TotalPriceMixin(serializers.Serializer):
)
class DuplicateOrderSerializer(serializers.Serializer):
"""Serializer for specifying options when duplicating an order."""
class Meta:
"""Metaclass options."""
fields = ['order_id', 'copy_lines', 'copy_extra_lines']
order_id = serializers.IntegerField(
required=True, label=_('Order ID'), help_text=_('ID of the order to duplicate')
)
copy_lines = serializers.BooleanField(
required=False,
default=True,
label=_('Copy Lines'),
help_text=_('Copy line items from the original order'),
)
copy_extra_lines = serializers.BooleanField(
required=False,
default=True,
label=_('Copy Extra Lines'),
help_text=_('Copy extra line items from the original order'),
)
class AbstractOrderSerializer(DataImportExportSerializerMixin, serializers.Serializer):
"""Abstract serializer class which provides fields common to all order types."""
export_exclude_fields = ['notes']
export_exclude_fields = ['notes', 'duplicate']
import_exclude_fields = ['notes', 'duplicate']
# Number of line items in this order
line_items = serializers.IntegerField(read_only=True, label=_('Line Items'))
@@ -127,6 +156,13 @@ class AbstractOrderSerializer(DataImportExportSerializerMixin, serializers.Seria
required=False, allow_null=True, label=_('Creation Date')
)
duplicate = DuplicateOrderSerializer(
label=_('Duplicate Order'),
help_text=_('Specify options for duplicating this order'),
required=False,
write_only=True,
)
def validate_reference(self, reference):
"""Custom validation for the reference field."""
self.Meta.model.validate_reference_field(reference)
@@ -166,9 +202,49 @@ class AbstractOrderSerializer(DataImportExportSerializerMixin, serializers.Seria
'notes',
'barcode_hash',
'overdue',
'duplicate',
*extra_fields,
]
def clean_line_item(self, line):
"""Clean a line item object (when duplicating)."""
line.pk = None
line.order = self
@transaction.atomic
def create(self, validated_data):
"""Create a new order object.
Optionally, copy line items from an existing order.
"""
duplicate = validated_data.pop('duplicate', None)
instance = super().create(validated_data)
if duplicate:
order_id = duplicate.get('order_id', None)
copy_lines = duplicate.get('copy_lines', True)
copy_extra_lines = duplicate.get('copy_extra_lines', True)
try:
copy_from = instance.__class__.objects.get(pk=order_id)
except Exception:
# If the order ID is invalid, raise a validation error
raise ValidationError(_('Invalid order ID'))
if copy_lines:
for line in copy_from.lines.all():
instance.clean_line_item(line)
line.save()
if copy_extra_lines:
for line in copy_from.extra_lines.all():
line.pk = None
line.order = instance
line.save()
return instance
class AbstractLineItemSerializer:
"""Abstract serializer for LineItem object."""
@@ -259,6 +335,12 @@ class PurchaseOrderSerializer(
if supplier_detail is not True:
self.fields.pop('supplier_detail', None)
def skip_create_fields(self):
"""Skip these fields when instantiating a new object."""
fields = super().skip_create_fields()
return [*fields, 'duplicate']
@staticmethod
def annotate_queryset(queryset):
"""Add extra information to the queryset.
@@ -900,6 +982,12 @@ class SalesOrderSerializer(
if customer_detail is not True:
self.fields.pop('customer_detail', None)
def skip_create_fields(self):
"""Skip these fields when instantiating a new object."""
fields = super().skip_create_fields()
return [*fields, 'duplicate']
@staticmethod
def annotate_queryset(queryset):
"""Add extra information to the queryset.
@@ -1692,6 +1780,12 @@ class ReturnOrderSerializer(
if customer_detail is not True:
self.fields.pop('customer_detail', None)
def skip_create_fields(self):
"""Skip these fields when instantiating a new object."""
fields = super().skip_create_fields()
return [*fields, 'duplicate']
@staticmethod
def annotate_queryset(queryset):
"""Custom annotation for the serializer queryset."""
+16 -8
View File
@@ -439,18 +439,22 @@ class PurchaseOrderTest(OrderTest):
del data['reference']
# Duplicate with non-existent PK to provoke error
data['duplicate_order'] = 10000001
data['duplicate_line_items'] = True
data['duplicate_extra_lines'] = False
data['duplicate'] = {
'order_id': 10000001,
'copy_lines': True,
'copy_extra_lines': False,
}
data['reference'] = 'PO-9999'
# Duplicate via the API
response = self.post(reverse('api-po-list'), data, expected_code=400)
data['duplicate_order'] = 1
data['duplicate_line_items'] = True
data['duplicate_extra_lines'] = False
data['duplicate'] = {
'order_id': 1,
'copy_lines': True,
'copy_extra_lines': False,
}
data['reference'] = 'PO-9999'
@@ -466,8 +470,12 @@ class PurchaseOrderTest(OrderTest):
self.assertEqual(po_dup.lines.count(), po.lines.count())
data['reference'] = 'PO-9998'
data['duplicate_line_items'] = False
data['duplicate_extra_lines'] = True
data['duplicate'] = {
'order_id': 1,
'copy_lines': False,
'copy_extra_lines': True,
}
response = self.post(reverse('api-po-list'), data, expected_code=201)
+12
View File
@@ -1715,6 +1715,13 @@ class PartStocktakeReportList(ListAPI):
ordering = '-pk'
class PartStocktakeReportDetail(RetrieveUpdateDestroyAPI):
"""API endpoint for detail view of a single PartStocktakeReport object."""
queryset = PartStocktakeReport.objects.all()
serializer_class = part_serializers.PartStocktakeReportSerializer
class PartStocktakeReportGenerate(CreateAPI):
"""API endpoint for manually generating a new PartStocktakeReport."""
@@ -2184,6 +2191,11 @@ part_api_urls = [
PartStocktakeReportGenerate.as_view(),
name='api-part-stocktake-report-generate',
),
path(
'<int:pk>/',
PartStocktakeReportDetail.as_view(),
name='api-part-stocktake-report-detail',
),
path(
'',
PartStocktakeReportList.as_view(),
@@ -1193,6 +1193,7 @@ class PartStocktakeReportSerializer(InvenTree.serializers.InvenTreeModelSerializ
model = PartStocktakeReport
fields = ['pk', 'date', 'report', 'part_count', 'user', 'user_detail']
read_only_fields = ['date', 'report', 'part_count', 'user']
user_detail = InvenTree.serializers.UserSerializer(
source='user', read_only=True, many=False
+55
View File
@@ -11,12 +11,15 @@ from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema
from rest_framework import permissions, status
from rest_framework.exceptions import NotFound
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
import plugin.serializers as PluginSerializers
from common.api import GlobalSettingsPermissions
from common.settings import get_global_setting
from InvenTree.api import MetadataView
from InvenTree.exceptions import log_error
from InvenTree.filters import SEARCH_ORDER_FILTER
from InvenTree.mixins import (
CreateAPI,
@@ -414,6 +417,43 @@ class RegistryStatusView(APIView):
return Response(result)
class PluginPanelList(APIView):
"""API endpoint for listing all available plugin panels."""
permission_classes = [IsAuthenticated]
serializer_class = PluginSerializers.PluginPanelSerializer
@extend_schema(responses={200: PluginSerializers.PluginPanelSerializer(many=True)})
def get(self, request):
"""Show available plugin panels."""
target_model = request.query_params.get('target_model', None)
target_id = request.query_params.get('target_id', None)
panels = []
if get_global_setting('ENABLE_PLUGINS_INTERFACE'):
# Extract all plugins from the registry which provide custom panels
for _plugin in registry.with_mixin('ui', active=True):
try:
# Allow plugins to fill this data out
plugin_panels = _plugin.get_ui_panels(
target_model, target_id, request
)
if plugin_panels and type(plugin_panels) is list:
for panel in plugin_panels:
panel['plugin'] = _plugin.slug
# TODO: Validate each panel before inserting
panels.append(panel)
except Exception:
# Custom panels could not load
# Log the error and continue
log_error(f'{_plugin.slug}.get_ui_panels')
return Response(PluginSerializers.PluginPanelSerializer(panels, many=True).data)
class PluginMetadataView(MetadataView):
"""Metadata API endpoint for the PluginConfig model."""
@@ -428,6 +468,21 @@ plugin_api_urls = [
path(
'plugins/',
include([
path(
'ui/',
include([
path(
'panels/',
include([
path(
'',
PluginPanelList.as_view(),
name='api-plugin-panel-list',
)
]),
)
]),
),
# Plugin management
path('reload/', PluginReload.as_view(), name='api-plugin-reload'),
path('install/', PluginInstall.as_view(), name='api-plugin-install'),
+254 -73
View File
@@ -3,19 +3,27 @@
import logging
from django.db.models import F
from django.urls import path
from django.urls import include, path
from django.utils.translation import gettext_lazy as _
from django_filters import rest_framework as rest_filters
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import permissions, status
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
import common.models
import order.models
import plugin.base.barcodes.helper
import stock.models
from common.settings import get_global_setting
from InvenTree.api import BulkDeleteMixin
from InvenTree.exceptions import log_error
from InvenTree.filters import SEARCH_ORDER_FILTER
from InvenTree.helpers import hash_barcode
from InvenTree.mixins import ListAPI, RetrieveDestroyAPI
from InvenTree.permissions import IsStaffOrReadOnly
from plugin import registry
from users.models import RuleSet
@@ -30,6 +38,70 @@ class BarcodeView(CreateAPIView):
# Default serializer class (can be overridden)
serializer_class = barcode_serializers.BarcodeSerializer
def log_scan(self, request, response=None, result=False):
"""Log a barcode scan to the database.
Arguments:
request: HTTP request object
response: Optional response data
"""
from common.models import BarcodeScanResult
# Extract context data from the request
context = {**request.GET.dict(), **request.POST.dict(), **request.data}
barcode = context.pop('barcode', '')
# Exit if storing barcode scans is disabled
if not get_global_setting('BARCODE_STORE_RESULTS', backup=False, create=False):
return
# Ensure that the response data is stringified first, otherwise cannot be JSON encoded
if type(response) is dict:
response = {key: str(value) for key, value in response.items()}
elif response is None:
pass
else:
response = str(response)
# Ensure that the context data is stringified first, otherwise cannot be JSON encoded
if type(context) is dict:
context = {key: str(value) for key, value in context.items()}
elif context is None:
pass
else:
context = str(context)
# Ensure data is not too long
if len(barcode) > BarcodeScanResult.BARCODE_SCAN_MAX_LEN:
barcode = barcode[: BarcodeScanResult.BARCODE_SCAN_MAX_LEN]
try:
BarcodeScanResult.objects.create(
data=barcode,
user=request.user,
endpoint=request.path,
response=response,
result=result,
context=context,
)
# Ensure that we do not store too many scans
max_scans = int(get_global_setting('BARCODE_RESULTS_MAX_NUM', create=False))
num_scans = BarcodeScanResult.objects.count()
if num_scans > max_scans:
n = num_scans - max_scans
old_scan_ids = (
BarcodeScanResult.objects.all()
.order_by('timestamp')
.values_list('pk', flat=True)[:n]
)
BarcodeScanResult.objects.filter(pk__in=old_scan_ids).delete()
except Exception:
# Gracefully log error to database
log_error(f'{self.__class__.__name__}.log_scan')
def queryset(self):
"""This API view does not have a queryset."""
return None
@@ -40,7 +112,13 @@ class BarcodeView(CreateAPIView):
def create(self, request, *args, **kwargs):
"""Handle create method - override default create."""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
try:
serializer.is_valid(raise_exception=True)
except Exception as exc:
self.log_scan(request, response={'error': str(exc)}, result=False)
raise exc
data = serializer.validated_data
barcode = str(data.pop('barcode')).strip()
@@ -119,15 +197,19 @@ class BarcodeScan(BarcodeView):
kwargs:
Any custom fields passed by the specific serializer
"""
result = self.scan_barcode(barcode, request, **kwargs)
response = self.scan_barcode(barcode, request, **kwargs)
if result['plugin'] is None:
result['error'] = _('No match found for barcode data')
if response['plugin'] is None:
response['error'] = _('No match found for barcode data')
self.log_scan(request, response, False)
raise ValidationError(response)
raise ValidationError(result)
response['success'] = _('Match found for barcode data')
result['success'] = _('Match found for barcode data')
return Response(result)
# Log the scan result
self.log_scan(request, response, True)
return Response(response)
@extend_schema_view(
@@ -333,7 +415,7 @@ class BarcodePOAllocate(BarcodeView):
supplier_parts = company.models.SupplierPart.objects.filter(supplier=supplier)
if not part and not supplier_part and not manufacturer_part:
raise ValidationError({'error': _('No matching part data found')})
raise ValidationError(_('No matching part data found'))
if part and (part_id := part.get('pk', None)):
supplier_parts = supplier_parts.filter(part__pk=part_id)
@@ -349,12 +431,10 @@ class BarcodePOAllocate(BarcodeView):
)
if supplier_parts.count() == 0:
raise ValidationError({'error': _('No matching supplier parts found')})
raise ValidationError(_('No matching supplier parts found'))
if supplier_parts.count() > 1:
raise ValidationError({
'error': _('Multiple matching supplier parts found')
})
raise ValidationError(_('Multiple matching supplier parts found'))
# At this stage, we have a single matching supplier part
return supplier_parts.first()
@@ -364,25 +444,32 @@ class BarcodePOAllocate(BarcodeView):
# The purchase order is provided as part of the request
purchase_order = kwargs.get('purchase_order')
result = self.scan_barcode(barcode, request, **kwargs)
response = self.scan_barcode(barcode, request, **kwargs)
if result['plugin'] is None:
result['error'] = _('No match found for barcode data')
raise ValidationError(result)
if response['plugin'] is None:
response['error'] = _('No matching plugin found for barcode data')
supplier_part = self.get_supplier_part(
purchase_order,
part=result.get('part', None),
supplier_part=result.get('supplierpart', None),
manufacturer_part=result.get('manufacturerpart', None),
)
result['success'] = _('Matched supplier part')
result['supplierpart'] = supplier_part.format_matched_response()
else:
try:
supplier_part = self.get_supplier_part(
purchase_order,
part=response.get('part', None),
supplier_part=response.get('supplierpart', None),
manufacturer_part=response.get('manufacturerpart', None),
)
response['success'] = _('Matched supplier part')
response['supplierpart'] = supplier_part.format_matched_response()
except ValidationError as e:
response['error'] = str(e)
# TODO: Determine the 'quantity to order' for the supplier part
return Response(result)
self.log_scan(request, response, 'success' in response)
if 'error' in response:
raise ValidationError
return Response(response)
class BarcodePOReceive(BarcodeView):
@@ -427,6 +514,7 @@ class BarcodePOReceive(BarcodeView):
if result := internal_barcode_plugin.scan(barcode):
if 'stockitem' in result:
response['error'] = _('Item has already been received')
self.log_scan(request, response, False)
raise ValidationError(response)
# Now, look just for "supplier-barcode" plugins
@@ -464,11 +552,13 @@ class BarcodePOReceive(BarcodeView):
# A plugin has not been found!
if plugin is None:
response['error'] = _('No match for supplier barcode')
self.log_scan(request, response, 'success' in response)
if 'error' in response:
raise ValidationError(response)
elif 'error' in response:
raise ValidationError(response)
else:
return Response(response)
return Response(response)
class BarcodeSOAllocate(BarcodeView):
@@ -489,7 +579,11 @@ class BarcodeSOAllocate(BarcodeView):
serializer_class = barcode_serializers.BarcodeSOAllocateSerializer
def get_line_item(self, stock_item, **kwargs):
"""Return the matching line item for the provided stock item."""
"""Return the matching line item for the provided stock item.
Raises:
ValidationError: If no single matching line item is found
"""
# Extract sales order object (required field)
sales_order = kwargs['sales_order']
@@ -506,22 +600,24 @@ class BarcodeSOAllocate(BarcodeView):
)
if lines.count() > 1:
raise ValidationError({'error': _('Multiple matching line items found')})
raise ValidationError(_('Multiple matching line items found'))
if lines.count() == 0:
raise ValidationError({'error': _('No matching line item found')})
raise ValidationError(_('No matching line item found'))
return lines.first()
def get_shipment(self, **kwargs):
"""Extract the shipment from the provided kwargs, or guess."""
"""Extract the shipment from the provided kwargs, or guess.
Raises:
ValidationError: If the shipment does not match the sales order
"""
sales_order = kwargs['sales_order']
if shipment := kwargs.get('shipment', None):
if shipment.order != sales_order:
raise ValidationError({
'error': _('Shipment does not match sales order')
})
raise ValidationError(_('Shipment does not match sales order'))
return shipment
@@ -536,37 +632,55 @@ class BarcodeSOAllocate(BarcodeView):
return None
def handle_barcode(self, barcode: str, request, **kwargs):
"""Handle barcode scan for sales order allocation."""
"""Handle barcode scan for sales order allocation.
Arguments:
barcode: Raw barcode data
request: HTTP request object
kwargs:
sales_order: SalesOrder ID value (required)
line: SalesOrderLineItem ID value (optional)
shipment: SalesOrderShipment ID value (optional)
"""
logger.debug("BarcodeSOAllocate: scanned barcode - '%s'", barcode)
result = self.scan_barcode(barcode, request, **kwargs)
response = self.scan_barcode(barcode, request, **kwargs)
if result['plugin'] is None:
result['error'] = _('No match found for barcode data')
raise ValidationError(result)
if 'sales_order' not in kwargs:
# SalesOrder ID *must* be provided
response['error'] = _('No sales order provided')
elif response['plugin'] is None:
# Check that the barcode at least matches a plugin
response['error'] = _('No matching plugin found for barcode data')
else:
try:
stock_item_id = response['stockitem'].get('pk', None)
stock_item = stock.models.StockItem.objects.get(pk=stock_item_id)
except Exception:
response['error'] = _('Barcode does not match an existing stock item')
# Check that the scanned barcode was a StockItem
if 'stockitem' not in result:
result['error'] = _('Barcode does not match an existing stock item')
raise ValidationError(result)
try:
stock_item_id = result['stockitem'].get('pk', None)
stock_item = stock.models.StockItem.objects.get(pk=stock_item_id)
except (ValueError, stock.models.StockItem.DoesNotExist):
result['error'] = _('Barcode does not match an existing stock item')
raise ValidationError(result)
if 'error' in response:
self.log_scan(request, response, False)
raise ValidationError(response)
# At this stage, we have a valid StockItem object
# Extract any other data from the kwargs
line_item = self.get_line_item(stock_item, **kwargs)
sales_order = kwargs['sales_order']
shipment = self.get_shipment(**kwargs)
if stock_item is not None and line_item is not None:
if stock_item.part != line_item.part:
result['error'] = _('Stock item does not match line item')
raise ValidationError(result)
try:
# Extract any other data from the kwargs
# Note: This may raise a ValidationError at some point - we break on the first error
sales_order = kwargs['sales_order']
line_item = self.get_line_item(stock_item, **kwargs)
shipment = self.get_shipment(**kwargs)
if stock_item is not None and line_item is not None:
if stock_item.part != line_item.part:
response['error'] = _('Stock item does not match line item')
except ValidationError as e:
response['error'] = str(e)
if 'error' in response:
self.log_scan(request, response, False)
raise ValidationError(response)
quantity = kwargs.get('quantity', None)
@@ -574,11 +688,12 @@ class BarcodeSOAllocate(BarcodeView):
if stock_item.serialized:
quantity = 1
if quantity is None:
elif quantity is None:
quantity = line_item.quantity - line_item.shipped
quantity = min(quantity, stock_item.unallocated_quantity())
response = {
**response,
'stock_item': stock_item.pk if stock_item else None,
'part': stock_item.part.pk if stock_item else None,
'sales_order': sales_order.pk if sales_order else None,
@@ -590,25 +705,91 @@ class BarcodeSOAllocate(BarcodeView):
if stock_item is not None and quantity is not None:
if stock_item.unallocated_quantity() < quantity:
response['error'] = _('Insufficient stock available')
raise ValidationError(response)
# If we have sufficient information, we can allocate the stock item
if all(x is not None for x in [line_item, sales_order, shipment, quantity]):
order.models.SalesOrderAllocation.objects.create(
line=line_item, shipment=shipment, item=stock_item, quantity=quantity
)
# If we have sufficient information, we can allocate the stock item
elif all(
x is not None for x in [line_item, sales_order, shipment, quantity]
):
order.models.SalesOrderAllocation.objects.create(
line=line_item,
shipment=shipment,
item=stock_item,
quantity=quantity,
)
response['success'] = _('Stock item allocated to sales order')
response['success'] = _('Stock item allocated to sales order')
else:
response['error'] = _('Not enough information')
response['action_required'] = True
self.log_scan(request, response, 'success' in response)
if 'error' in response:
raise ValidationError(response)
else:
return Response(response)
response['error'] = _('Not enough information')
response['action_required'] = True
raise ValidationError(response)
class BarcodeScanResultMixin:
"""Mixin class for BarcodeScan API endpoints."""
queryset = common.models.BarcodeScanResult.objects.all()
serializer_class = barcode_serializers.BarcodeScanResultSerializer
permission_classes = [permissions.IsAuthenticated, IsStaffOrReadOnly]
def get_queryset(self):
"""Return the queryset for the BarcodeScan API."""
queryset = super().get_queryset()
# Pre-fetch user data
queryset = queryset.prefetch_related('user')
return queryset
class BarcodeScanResultFilter(rest_filters.FilterSet):
"""Custom filterset for the BarcodeScanResult API."""
class Meta:
"""Meta class for the BarcodeScanResultFilter."""
model = common.models.BarcodeScanResult
fields = ['user', 'result']
class BarcodeScanResultList(BarcodeScanResultMixin, BulkDeleteMixin, ListAPI):
"""List API endpoint for BarcodeScan objects."""
filterset_class = BarcodeScanResultFilter
filter_backends = SEARCH_ORDER_FILTER
ordering_fields = ['user', 'plugin', 'timestamp', 'endpoint', 'result']
ordering = '-timestamp'
search_fields = ['plugin']
class BarcodeScanResultDetail(BarcodeScanResultMixin, RetrieveDestroyAPI):
"""Detail endpoint for a BarcodeScan object."""
barcode_api_urls = [
# Barcode scan history
path(
'history/',
include([
path(
'<int:pk>/',
BarcodeScanResultDetail.as_view(),
name='api-barcode-scan-result-detail',
),
path(
'', BarcodeScanResultList.as_view(), name='api-barcode-scan-result-list'
),
]),
),
# Generate a barcode for a database object
path('generate/', BarcodeGenerate.as_view(), name='api-barcode-generate'),
# Link a third-party barcode to an item (e.g. Part / StockItem / etc)
@@ -5,12 +5,39 @@ from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
import common.models
import order.models
import plugin.base.barcodes.helper
import stock.models
from InvenTree.serializers import UserSerializer
from order.status_codes import PurchaseOrderStatus, SalesOrderStatus
class BarcodeScanResultSerializer(serializers.ModelSerializer):
"""Serializer for barcode scan results."""
class Meta:
"""Meta class for BarcodeScanResultSerializer."""
model = common.models.BarcodeScanResult
fields = [
'pk',
'data',
'timestamp',
'endpoint',
'context',
'response',
'result',
'user',
'user_detail',
]
read_only_fields = fields
user_detail = UserSerializer(source='user', read_only=True)
class BarcodeSerializer(serializers.Serializer):
"""Generic serializer for receiving barcode data."""
@@ -4,6 +4,8 @@ from django.urls import reverse
import company.models
import order.models
from common.models import BarcodeScanResult
from common.settings import set_global_setting
from InvenTree.unit_test import InvenTreeAPITestCase
from part.models import Part
from stock.models import StockItem
@@ -89,6 +91,11 @@ class BarcodeAPITest(InvenTreeAPITestCase):
"""Test that we can lookup a stock item based on ID."""
item = StockItem.objects.first()
# Save barcode scan results to database
set_global_setting('BARCODE_STORE_RESULTS', True)
n = BarcodeScanResult.objects.count()
response = self.post(
self.scan_url, {'barcode': item.format_barcode()}, expected_code=200
)
@@ -97,6 +104,20 @@ class BarcodeAPITest(InvenTreeAPITestCase):
self.assertIn('barcode_data', response.data)
self.assertEqual(response.data['stockitem']['pk'], item.pk)
self.assertEqual(BarcodeScanResult.objects.count(), n + 1)
result = BarcodeScanResult.objects.last()
self.assertTrue(result.result)
self.assertEqual(result.data, item.format_barcode())
response = result.response
self.assertEqual(response['plugin'], 'InvenTreeBarcode')
for k in ['barcode_data', 'stockitem', 'success']:
self.assertIn(k, response)
def test_invalid_item(self):
"""Test response for invalid stock item."""
response = self.post(
@@ -309,7 +330,7 @@ class SOAllocateTest(InvenTreeAPITestCase):
'123456789', sales_order=self.sales_order.pk, expected_code=400
)
self.assertIn('No match found for barcode', str(result['error']))
self.assertIn('No matching plugin found for barcode data', str(result['error']))
# Test with a barcode that matches a *different* stock item
item = StockItem.objects.exclude(pk=self.stock_item.pk).first()
@@ -0,0 +1,80 @@
"""UserInterfaceMixin class definition.
Allows integration of custom UI elements into the React user interface.
"""
import logging
from typing import TypedDict
from rest_framework.request import Request
logger = logging.getLogger('inventree')
class CustomPanel(TypedDict):
"""Type definition for a custom panel.
Attributes:
name: The name of the panel (required, used as a DOM identifier).
label: The label of the panel (required, human readable).
icon: The icon of the panel (optional, must be a valid icon identifier).
content: The content of the panel (optional, raw HTML).
source: The source of the panel (optional, path to a JavaScript file).
"""
name: str
label: str
icon: str
content: str
source: str
class UserInterfaceMixin:
"""Plugin mixin class which handles injection of custom elements into the front-end interface.
- All content is accessed via the API, as requested by the user interface.
- This means that content can be dynamically generated, based on the current state of the system.
The following custom UI methods are available:
- get_ui_panels: Return a list of custom panels to be injected into the UI
"""
class MixinMeta:
"""Metaclass for this plugin mixin."""
MIXIN_NAME = 'ui'
def __init__(self):
"""Register mixin."""
super().__init__()
self.add_mixin('ui', True, __class__)
def get_ui_panels(
self, instance_type: str, instance_id: int, request: Request, **kwargs
) -> list[CustomPanel]:
"""Return a list of custom panels to be injected into the UI.
Args:
instance_type: The type of object being viewed (e.g. 'part')
instance_id: The ID of the object being viewed (e.g. 123)
request: HTTPRequest object (including user information)
Returns:
list: A list of custom panels to be injected into the UI
- The returned list should contain a dict for each custom panel to be injected into the UI:
- The following keys can be specified:
{
'name': 'panel_name', # The name of the panel (required, must be unique)
'label': 'Panel Title', # The title of the panel (required, human readable)
'icon': 'icon-name', # Icon name (optional, must be a valid icon identifier)
'content': '<p>Panel content</p>', # HTML content to be rendered in the panel (optional)
'source': 'static/plugin/panel.js', # Path to a JavaScript file to be loaded (optional)
}
- Either 'source' or 'content' must be provided
"""
# Default implementation returns an empty list
return []
@@ -8,7 +8,8 @@ from django.urls import include, path, re_path, reverse
from error_report.models import Error
from InvenTree.unit_test import InvenTreeTestCase
from common.models import InvenTreeSetting
from InvenTree.unit_test import InvenTreeAPITestCase, InvenTreeTestCase
from plugin import InvenTreePlugin
from plugin.base.integration.PanelMixin import PanelMixin
from plugin.helpers import MixinNotImplementedError
@@ -341,7 +342,10 @@ class APICallMixinTest(BaseMixinDefinition, TestCase):
class PanelMixinTests(InvenTreeTestCase):
"""Test that the PanelMixin plugin operates correctly."""
"""Test that the PanelMixin plugin operates correctly.
TODO: This class will be removed in the future, as the PanelMixin is deprecated.
"""
fixtures = ['category', 'part', 'location', 'stock']
@@ -475,3 +479,100 @@ class PanelMixinTests(InvenTreeTestCase):
plugin = Wrong()
plugin.get_custom_panels('abc', 'abc')
class UserInterfaceMixinTests(InvenTreeAPITestCase):
"""Test the UserInterfaceMixin plugin mixin class."""
roles = 'all'
fixtures = ['part', 'category', 'location', 'stock']
@classmethod
def setUpTestData(cls):
"""Set up the test case."""
super().setUpTestData()
# Ensure that the 'sampleui' plugin is installed and active
registry.set_plugin_state('sampleui', True)
# Ensure that UI plugins are enabled
InvenTreeSetting.set_setting('ENABLE_PLUGINS_INTERFACE', True, change_user=None)
def test_installed(self):
"""Test that the sample UI plugin is installed and active."""
plugin = registry.get_plugin('sampleui')
self.assertTrue(plugin.is_active())
plugins = registry.with_mixin('ui')
self.assertGreater(len(plugins), 0)
def test_panels(self):
"""Test that the sample UI plugin provides custom panels."""
from part.models import Part
plugin = registry.get_plugin('sampleui')
_part = Part.objects.first()
# Ensure that the part is active
_part.active = True
_part.save()
url = reverse('api-plugin-panel-list')
query_data = {'target_model': 'part', 'target_id': _part.pk}
# Enable *all* plugin settings
plugin.set_setting('ENABLE_PART_PANELS', True)
plugin.set_setting('ENABLE_PURCHASE_ORDER_PANELS', True)
plugin.set_setting('ENABLE_BROKEN_PANELS', True)
plugin.set_setting('ENABLE_DYNAMIC_PANEL', True)
# Request custom panel information for a part instance
response = self.get(url, data=query_data)
# There should be 4 active panels for the part by default
self.assertEqual(4, len(response.data))
_part.active = False
_part.save()
response = self.get(url, data=query_data)
# As the part is not active, only 3 panels left
self.assertEqual(3, len(response.data))
# Disable the "ENABLE_PART_PANELS" setting, and try again
plugin.set_setting('ENABLE_PART_PANELS', False)
response = self.get(url, data=query_data)
# There should still be 3 panels
self.assertEqual(3, len(response.data))
# Check for the correct panel names
self.assertEqual(response.data[0]['name'], 'sample_panel')
self.assertIn('content', response.data[0])
self.assertNotIn('source', response.data[0])
self.assertEqual(response.data[1]['name'], 'broken_panel')
self.assertEqual(response.data[1]['source'], '/this/does/not/exist.js')
self.assertNotIn('content', response.data[1])
self.assertEqual(response.data[2]['name'], 'dynamic_panel')
self.assertEqual(response.data[2]['source'], '/static/plugin/sample_panel.js')
self.assertNotIn('content', response.data[2])
# Next, disable the global setting for UI integration
InvenTreeSetting.set_setting(
'ENABLE_PLUGINS_INTERFACE', False, change_user=None
)
response = self.get(url, data=query_data)
# There should be no panels available
self.assertEqual(0, len(response.data))
# Set the setting back to True for subsequent tests
InvenTreeSetting.set_setting('ENABLE_PLUGINS_INTERFACE', True, change_user=None)
+11
View File
@@ -10,6 +10,7 @@ from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
import plugin.models
import plugin.staticfiles
from InvenTree.exceptions import log_error
logger = logging.getLogger('inventree')
@@ -119,6 +120,10 @@ def install_plugins_file():
log_error('pip')
return False
# Update static files
plugin.staticfiles.collect_plugins_static_files()
plugin.staticfiles.clear_plugins_static_files()
# At this point, the plugins file has been installed
return True
@@ -256,6 +261,9 @@ def install_plugin(url=None, packagename=None, user=None, version=None):
registry.reload_plugins(full_reload=True, force_reload=True, collect=True)
# Update static files
plugin.staticfiles.collect_plugins_static_files()
return ret
@@ -320,6 +328,9 @@ def uninstall_plugin(cfg: plugin.models.PluginConfig, user=None, delete_config=T
# Remove the plugin configuration from the database
cfg.delete()
# Remove static files associated with this plugin
plugin.staticfiles.clear_plugin_static_files(cfg.key)
# Reload the plugin registry
registry.reload_plugins(full_reload=True, force_reload=True, collect=True)
@@ -14,6 +14,7 @@ from plugin.base.integration.ReportMixin import ReportMixin
from plugin.base.integration.ScheduleMixin import ScheduleMixin
from plugin.base.integration.SettingsMixin import SettingsMixin
from plugin.base.integration.UrlsMixin import UrlsMixin
from plugin.base.integration.UserInterfaceMixin import UserInterfaceMixin
from plugin.base.integration.ValidationMixin import ValidationMixin
from plugin.base.label.mixins import LabelPrintingMixin
from plugin.base.locate.mixins import LocateMixin
@@ -38,5 +39,7 @@ __all__ = [
'SingleNotificationMethod',
'SupplierBarcodeMixin',
'UrlsMixin',
'UrlsMixin',
'UserInterfaceMixin',
'ValidationMixin',
]
+4 -3
View File
@@ -742,11 +742,12 @@ class PluginsRegistry:
def plugin_settings_keys(self):
"""A list of keys which are used to store plugin settings."""
return [
'ENABLE_PLUGINS_URL',
'ENABLE_PLUGINS_NAVIGATION',
'ENABLE_PLUGINS_APP',
'ENABLE_PLUGINS_SCHEDULE',
'ENABLE_PLUGINS_EVENTS',
'ENABLE_PLUGINS_INTERFACE',
'ENABLE_PLUGINS_NAVIGATION',
'ENABLE_PLUGINS_SCHEDULE',
'ENABLE_PLUGINS_URL',
]
def calculate_plugin_hash(self):
@@ -0,0 +1,30 @@
{% load i18n %}
<h4>Custom Plugin Panel</h4>
<p>
This content has been rendered by a custom plugin, and will be displayed for any "part" instance
(as long as the plugin is enabled).
This content has been rendered on the server, using the django templating system.
</p>
<h5>Part Details</h5>
<table class='table table-striped table-condensed'>
<tr>
<th>Part Name</th>
<td>{{ part.name }}</td>
</tr>
<tr>
<th>Part Description</th>
<td>{{ part.description }}</td>
</tr>
<tr>
<th>Part Category</th>
<td>{{ part.category.pathstring }}</td>
</tr>
<tr>
<th>Part IPN</th>
<td>{% if part.IPN %}{{ part.IPN }}{% else %}<i>No IPN specified</i>{% endif %}</td>
</tr>
</table>
@@ -0,0 +1,124 @@
"""Sample plugin which demonstrates user interface integrations."""
from django.utils.translation import gettext_lazy as _
from part.models import Part
from plugin import InvenTreePlugin
from plugin.helpers import render_template, render_text
from plugin.mixins import SettingsMixin, UserInterfaceMixin
class SampleUserInterfacePlugin(SettingsMixin, UserInterfaceMixin, InvenTreePlugin):
"""A sample plugin which demonstrates user interface integrations."""
NAME = 'SampleUI'
SLUG = 'sampleui'
TITLE = 'Sample User Interface Plugin'
DESCRIPTION = 'A sample plugin which demonstrates user interface integrations'
VERSION = '1.0'
SETTINGS = {
'ENABLE_PART_PANELS': {
'name': _('Enable Part Panels'),
'description': _('Enable custom panels for Part views'),
'default': True,
'validator': bool,
},
'ENABLE_PURCHASE_ORDER_PANELS': {
'name': _('Enable Purchase Order Panels'),
'description': _('Enable custom panels for Purchase Order views'),
'default': False,
'validator': bool,
},
'ENABLE_BROKEN_PANELS': {
'name': _('Enable Broken Panels'),
'description': _('Enable broken panels for testing'),
'default': True,
'validator': bool,
},
'ENABLE_DYNAMIC_PANEL': {
'name': _('Enable Dynamic Panel'),
'description': _('Enable dynamic panels for testing'),
'default': True,
'validator': bool,
},
}
def get_ui_panels(self, instance_type: str, instance_id: int, request, **kwargs):
"""Return a list of custom panels to be injected into the UI."""
panels = []
# First, add a custom panel which will appear on every type of page
# This panel will contain a simple message
content = render_text(
"""
This is a <i>sample panel</i> which appears on every page.
It renders a simple string of <b>HTML</b> content.
<br>
<h5>Instance Details:</h5>
<ul>
<li>Instance Type: {{ instance_type }}</li>
<li>Instance ID: {{ instance_id }}</li>
</ul>
""",
context={'instance_type': instance_type, 'instance_id': instance_id},
)
panels.append({
'name': 'sample_panel',
'label': 'Sample Panel',
'content': content,
})
# A broken panel which tries to load a non-existent JS file
if self.get_setting('ENABLE_BROKEN_PANElS'):
panels.append({
'name': 'broken_panel',
'label': 'Broken Panel',
'source': '/this/does/not/exist.js',
})
# A dynamic panel which will be injected into the UI (loaded from external file)
if self.get_setting('ENABLE_DYNAMIC_PANEL'):
panels.append({
'name': 'dynamic_panel',
'label': 'Dynamic Part Panel',
'source': '/static/plugin/sample_panel.js',
'icon': 'part',
})
# Next, add a custom panel which will appear on the 'part' page
# Note that this content is rendered from a template file,
# using the django templating system
if self.get_setting('ENABLE_PART_PANELS') and instance_type == 'part':
try:
part = Part.objects.get(pk=instance_id)
except (Part.DoesNotExist, ValueError):
part = None
# Note: This panel will *only* be available if the part is active
if part and part.active:
content = render_template(
self, 'uidemo/custom_part_panel.html', context={'part': part}
)
panels.append({
'name': 'part_panel',
'label': 'Part Panel',
'content': content,
})
# Next, add a custom panel which will appear on the 'purchaseorder' page
if (
self.get_setting('ENABLE_PURCHASE_ORDER_PANELS')
and instance_type == 'purchaseorder'
):
panels.append({
'name': 'purchase_order_panel',
'label': 'Purchase Order Panel',
'content': 'This is a custom panel which appears on the <b>Purchase Order</b> view page.',
})
return panels
@@ -0,0 +1,47 @@
/**
* A sample panel plugin for InvenTree.
*
* This plugin file is dynamically loaded,
* as specified in the plugin/samples/integration/user_interface_sample.py
*
* It provides a simple example of how panels can be dynamically rendered,
* as well as dynamically hidden, based on the provided context.
*/
export function renderPanel(target, context) {
if (!target) {
console.error("No target provided to renderPanel");
return;
}
target.innerHTML = `
<h4>Dynamic Panel Content</h4>
<p>This panel has been dynamically rendered by the plugin system.</p>
<p>It can be hidden or displayed based on the provided context.</p>
<hr>
<h5>Context:</h5>
<ul>
<li>Username: ${context.user.username()}</li>
<li>Is Staff: ${context.user.isStaff() ? "YES": "NO"}</li>
<li>Model Type: ${context.model}</li>
<li>Instance ID: ${context.id}</li>
`;
}
// Dynamically hide the panel based on the provided context
export function isPanelHidden(context) {
// Hide the panel if the user is not staff
if (!context?.user?.isStaff()) {
return true;
}
// Only display for active parts
return context.model != 'part' || !context.instance || !context.instance.active;
}
@@ -301,3 +301,46 @@ class PluginRelationSerializer(serializers.PrimaryKeyRelatedField):
def to_representation(self, value):
"""Return the 'key' of the PluginConfig object."""
return value.key
class PluginPanelSerializer(serializers.Serializer):
"""Serializer for a plugin panel."""
class Meta:
"""Meta for serializer."""
fields = [
'plugin',
'name',
'label',
# Following fields are optional
'icon',
'content',
'source',
]
# Required fields
plugin = serializers.CharField(
label=_('Plugin Key'), required=True, allow_blank=False
)
name = serializers.CharField(
label=_('Panel Name'), required=True, allow_blank=False
)
label = serializers.CharField(
label=_('Panel Title'), required=True, allow_blank=False
)
# Optional fields
icon = serializers.CharField(
label=_('Panel Icon'), required=False, allow_blank=True
)
content = serializers.CharField(
label=_('Panel Content (HTML)'), required=False, allow_blank=True
)
source = serializers.CharField(
label=_('Panel Source (javascript)'), required=False, allow_blank=True
)
@@ -32,6 +32,8 @@ def clear_static_dir(path, recursive=True):
# Finally, delete the directory itself to remove orphan folders when uninstalling a plugin
staticfiles_storage.delete(path)
logger.info('Cleared static directory: %s', path)
def collect_plugins_static_files():
"""Copy static files from all installed plugins into the static directory."""
@@ -43,6 +45,26 @@ def collect_plugins_static_files():
copy_plugin_static_files(slug, check_reload=False)
def clear_plugins_static_files():
"""Clear out static files for plugins which are no longer active."""
installed_plugins = set(registry.plugins.keys())
path = 'plugins/'
# Check that the directory actually exists
if not staticfiles_storage.exists(path):
return
# Get all static files in the 'plugins' static directory
dirs, _files = staticfiles_storage.listdir('plugins/')
for d in dirs:
# Check if the directory is a plugin directory
if d not in installed_plugins:
# Clear out the static files for this plugin
clear_static_dir(f'plugins/{d}/', recursive=True)
def copy_plugin_static_files(slug, check_reload=True):
"""Copy static files for the specified plugin."""
if check_reload:
@@ -93,3 +115,8 @@ def copy_plugin_static_files(slug, check_reload=True):
copied += 1
logger.info("Copied %s static files for plugin '%s'.", copied, slug)
def clear_plugin_static_files(slug: str, recursive: bool = True):
"""Clear static files for the specified plugin."""
clear_static_dir(f'plugins/{slug}/', recursive=recursive)
@@ -17,6 +17,8 @@
{% include "InvenTree/settings/setting.html" with key="BARCODE_WEBCAM_SUPPORT" icon="fa-video" %}
{% include "InvenTree/settings/setting.html" with key="BARCODE_SHOW_TEXT" icon="fa-closed-captioning" %}
{% include "InvenTree/settings/setting.html" with key="BARCODE_GENERATION_PLUGIN" icon="fa-qrcode" %}
{% include "InvenTree/settings/setting.html" with key="BARCODE_STORE_RESULTS" icon="fa-qrcode" %}
{% include "InvenTree/settings/setting.html" with key="BARCODE_RESULTS_MAX_NUM" icon="fa-qrcode" %}
</tbody>
</table>
@@ -98,7 +98,8 @@ function purchaseOrderFields(options={}) {
return fields;
}
}
},
disabled: !!options.duplicate_order,
},
supplier_reference: {},
project_code: {
@@ -155,35 +156,13 @@ function purchaseOrderFields(options={}) {
// Add fields for order duplication (only if required)
if (options.duplicate_order) {
fields.duplicate_order = {
fields.duplicate__order_id = {
value: options.duplicate_order,
group: 'duplicate',
required: 'true',
type: 'related field',
model: 'purchaseorder',
filters: {
supplier_detail: true,
},
api_url: '{% url "api-po-list" %}',
label: '{% trans "Purchase Order" %}',
help_text: '{% trans "Select purchase order to duplicate" %}',
hidden: true,
};
fields.duplicate_line_items = {
value: true,
group: 'duplicate',
type: 'boolean',
label: '{% trans "Duplicate Line Items" %}',
help_text: '{% trans "Duplicate all line items from the selected order" %}',
};
fields.duplicate_extra_lines = {
value: true,
group: 'duplicate',
type: 'boolean',
label: '{% trans "Duplicate Extra Lines" %}',
help_text: '{% trans "Duplicate extra line items from the selected order" %}',
};
fields.duplicate__copy_lines = {};
fields.duplicate__copy_extra_lines = {};
}
if (!global_settings.PROJECT_CODES_ENABLED) {
+1
View File
@@ -241,6 +241,7 @@ class RuleSet(models.Model):
'plugin_pluginconfig',
'plugin_pluginsetting',
'plugin_notificationusersetting',
'common_barcodescanresult',
'common_newsfeedentry',
'taggit_tag',
'taggit_taggeditem',
+1
View File
@@ -19,6 +19,7 @@
"it",
"ja",
"ko",
"lt",
"lv",
"nl",
"no",
+13 -13
View File
@@ -11,7 +11,7 @@
"compile": "lingui compile --typescript"
},
"dependencies": {
"@codemirror/autocomplete": "^6.18.0",
"@codemirror/autocomplete": "^6.18.1",
"@codemirror/lang-liquid": "^6.2.1",
"@codemirror/language": "^6.10.2",
"@codemirror/lint": "^6.8.1",
@@ -37,11 +37,11 @@
"@mantine/notifications": "^7.12.2",
"@mantine/spotlight": "^7.12.2",
"@mantine/vanilla-extract": "^7.12.2",
"@sentry/react": "^8.29.0",
"@tabler/icons-react": "^3.15.0",
"@tanstack/react-query": "^5.55.4",
"@uiw/codemirror-theme-vscode": "^4.23.1",
"@uiw/react-codemirror": "^4.23.1",
"@sentry/react": "^8.30.0",
"@tabler/icons-react": "^3.17.0",
"@tanstack/react-query": "^5.56.2",
"@uiw/codemirror-theme-vscode": "^4.23.2",
"@uiw/react-codemirror": "^4.23.2",
"@uiw/react-split": "^5.9.3",
"@vanilla-extract/css": "^1.15.5",
"axios": "^1.7.7",
@@ -49,7 +49,7 @@
"codemirror": "^6.0.1",
"dayjs": "^1.11.13",
"easymde": "^2.18.0",
"embla-carousel-react": "^8.2.1",
"embla-carousel-react": "^8.3.0",
"fuse.js": "^7.0.0",
"html5-qrcode": "^2.3.8",
"mantine-datatable": "^7.12.4",
@@ -71,13 +71,13 @@
"@babel/core": "^7.25.2",
"@babel/preset-react": "^7.24.7",
"@babel/preset-typescript": "^7.24.7",
"@codecov/vite-plugin": "^1.0.0",
"@codecov/vite-plugin": "^1.1.0",
"@lingui/cli": "^4.11.4",
"@lingui/macro": "^4.11.4",
"@playwright/test": "^1.47.0",
"@types/node": "^22.5.4",
"@playwright/test": "^1.47.1",
"@types/node": "^22.5.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.5",
"@types/react": "^18.3.6",
"@types/react-dom": "^18.3.0",
"@types/react-grid-layout": "^1.3.5",
"@types/react-router-dom": "^5.3.3",
@@ -87,8 +87,8 @@
"babel-plugin-macros": "^3.1.0",
"nyc": "^17.0.0",
"rollup-plugin-license": "^3.5.2",
"typescript": "^5.5.4",
"vite": "^5.4.3",
"typescript": "^5.6.2",
"vite": "^5.4.6",
"vite-plugin-babel-macros": "^1.0.6",
"vite-plugin-istanbul": "^6.0.2"
}
+2 -1
View File
@@ -38,7 +38,8 @@ export default defineConfig({
{
command: 'invoke dev.server -a 127.0.0.1:8000',
env: {
INVENTREE_DEBUG: 'True'
INVENTREE_DEBUG: 'True',
INVENTREE_PLUGINS_ENABLED: 'True'
},
url: 'http://127.0.0.1:8000/api/',
reuseExistingServer: !process.env.CI,
+4 -4
View File
@@ -4,7 +4,7 @@ import { ErrorBoundary, FallbackRender } from '@sentry/react';
import { IconExclamationCircle } from '@tabler/icons-react';
import { ReactNode, useCallback } from 'react';
function DefaultFallback({ title }: { title: String }): ReactNode {
function DefaultFallback({ title }: Readonly<{ title: string }>): ReactNode {
return (
<Alert
color="red"
@@ -20,11 +20,11 @@ export function Boundary({
children,
label,
fallback
}: {
}: Readonly<{
children: ReactNode;
label: string;
fallback?: React.ReactElement | FallbackRender | undefined;
}): ReactNode {
fallback?: React.ReactElement | FallbackRender;
}>): ReactNode {
const onError = useCallback(
(error: unknown, componentStack: string | undefined, eventId: string) => {
console.error(`Error rendering component: ${label}`);
@@ -14,13 +14,13 @@ export function DashboardItemProxy({
url,
params,
autoupdate = true
}: {
}: Readonly<{
id: string;
text: string;
url: ApiEndpoints;
params: any;
autoupdate: boolean;
}) {
}>) {
function fetchData() {
return api
.get(`${apiUrl(url)}?search=&offset=0&limit=25`, { params: params })
@@ -22,7 +22,7 @@ export type AdminButtonProps = {
* - The user has "superuser" role
* - The user has at least read rights for the selected item
*/
export default function AdminButton(props: AdminButtonProps) {
export default function AdminButton(props: Readonly<AdminButtonProps>) {
const user = useUserState();
const enabled: boolean = useMemo(() => {
@@ -9,12 +9,12 @@ export function ButtonMenu({
actions,
tooltip = '',
label = ''
}: {
}: Readonly<{
icon: any;
actions: React.ReactNode[];
label?: string;
tooltip?: string;
}) {
}>) {
return (
<Menu shadow="xs">
<Menu.Target>
@@ -3,6 +3,7 @@ import {
ActionIcon,
Button,
CopyButton as MantineCopyButton,
MantineSize,
Text,
Tooltip
} from '@mantine/core';
@@ -11,11 +12,15 @@ import { InvenTreeIcon } from '../../functions/icons';
export function CopyButton({
value,
label
}: {
label,
content,
size
}: Readonly<{
value: any;
label?: JSX.Element;
}) {
label?: string;
content?: JSX.Element;
size?: MantineSize;
}>) {
const ButtonComponent = label ? Button : ActionIcon;
return (
@@ -26,15 +31,19 @@ export function CopyButton({
color={copied ? 'teal' : 'gray'}
onClick={copy}
variant="transparent"
size="sm"
size={size ?? 'sm'}
>
{copied ? (
<InvenTreeIcon icon="check" />
) : (
<InvenTreeIcon icon="copy" />
)}
{label && <Text ml={10}>{label}</Text>}
{content}
{label && (
<Text p={size ?? 'sm'} size={size ?? 'sm'}>
{label}
</Text>
)}
</ButtonComponent>
</Tooltip>
)}
@@ -6,12 +6,12 @@ export function EditButton({
editing,
disabled,
saveIcon
}: {
}: Readonly<{
setEditing: (value?: React.SetStateAction<boolean> | undefined) => void;
editing: boolean;
disabled?: boolean;
saveIcon?: JSX.Element;
}) {
}>) {
saveIcon = saveIcon || <IconDeviceFloppy />;
return (
<ActionIcon

Some files were not shown because too many files have changed in this diff Show More