inventree-wurth-barcode 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Simone Amadori
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: inventree-wurth-barcode
3
+ Version: 0.1.1
4
+ Summary: InvenTree plugin: scan the barcodes of the Würth Elektronik labels (part lookup and purchase order receiving)
5
+ Author-email: Simone Amadori <simone@amadori.bs.it>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Kamaar/inventree-wurth-barcode
8
+ Project-URL: Repository, https://github.com/Kamaar/inventree-wurth-barcode
9
+ Project-URL: Issues, https://github.com/Kamaar/inventree-wurth-barcode/issues
10
+ Keywords: inventree,plugin,barcode,wurth,wurth-elektronik,datamatrix
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Framework :: InvenTree
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Dynamic: license-file
18
+
19
+ # Würth Elektronik Barcode
20
+
21
+ [InvenTree](https://inventree.org) plugin (>= 1.0) that reads the barcodes of the **Würth Elektronik** labels, from the
22
+ web interface and from the **InvenTree app**: scanning a label opens the part, and inside a purchase order it receives
23
+ the line item with the quantity of the label.
24
+
25
+ ## The labels
26
+
27
+ The Würth Elektronik labels (reels, bags, samples) carry the ANSI MH10.8.2 data identifiers:
28
+
29
+ | Identifier | Field | Example |
30
+ |---|---|---|
31
+ | `1P` | Part number (Würth order code = manufacturer part number) | `609 002 134 21` |
32
+ | `Q` | Quantity | `10` |
33
+ | `1T` | Lot number | `298010012537000` |
34
+ | `16D` | Production date | `20250908` |
35
+
36
+ The **DataMatrix** holds all of them (ISO/IEC 15434 format 06:
37
+ `[)>␞06␝1P60900213421␝Q10␝1T298010012537000␝16D20250908␞␄`); each **Code 128** barcode holds one field. The plugin
38
+ reads the DataMatrix and the part number barcode (`1P…`).
39
+
40
+ The label names no supplier: it is recognised by its content, a numeric `1P` and none of the fields that distributors
41
+ add to their own labels (DigiKey `P` / `30P`, Mouser and DigiKey `11K`), so it is not confused with them.
42
+
43
+ ## What a scan does
44
+
45
+ - **Part lookup** (scan from the home page, web or app):
46
+ - the **supplier part** of the Würth supplier, with the order code as SKU;
47
+ - the **manufacturer part** of Würth Elektronik with the order code as MPN, also when the part is bought from a
48
+ distributor (e.g. Mouser).
49
+
50
+ Spaces are ignored: `609 002 134 21` and `60900213421` are the same code.
51
+ - **Purchase order receiving** (*Purchase order → Scan to receive*, web or app): in a placed order of the Würth supplier
52
+ the line item of the part is received with the quantity of the label, into the destination of the line or of the
53
+ order.
54
+
55
+ ## Installation
56
+
57
+ The plugin is on [PyPI](https://pypi.org/project/inventree-wurth-barcode/):
58
+
59
+ - **from the InvenTree UI** (*Settings → Plugins → Install plugin*): *Package Name* `inventree-wurth-barcode`;
60
+ - **or with `plugins.txt`** (next to `config.yaml`, or the file set by `INVENTREE_PLUGIN_FILE`): a line
61
+ `inventree-wurth-barcode`.
62
+
63
+ Then activate **Würth Elektronik Barcode** in *Settings → Plugins* and restart server and worker. The plugin has no
64
+ database tables: no migrations are needed. With Docker, install it in **both** the server and the worker container
65
+ (different versions cause the *Plugin Registry Mismatch* error, INVE-E20):
66
+
67
+ ```bash
68
+ docker compose exec inventree-server invoke plugins
69
+ docker compose exec inventree-worker invoke plugins
70
+ docker compose restart inventree-server inventree-worker
71
+ ```
72
+
73
+ With the package installer (`.deb`): `sudo inventree run invoke plugins`, then `sudo inventree restart`.
74
+
75
+ The **InvenTree app** needs no change: it sends the scanned barcodes to the server, which passes them to the active
76
+ barcode plugins.
77
+
78
+ ## Settings
79
+
80
+ | Setting | Notes |
81
+ |---|---|
82
+ | `SUPPLIER_ID` | Supplier company of the parts bought from Würth Elektronik. If empty, the only supplier whose name contains *Würth*, *Wurth* or *Wuerth* is used (and saved) |
83
+ | `MANUFACTURER_ID` | Manufacturer company of the Würth Elektronik parts. If empty, found by name as above |
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ python -m pytest # parser tests, no InvenTree needed
89
+ ruff check wurth_barcode tests
90
+ ```
91
+
92
+ `tests/integration` runs on a real InvenTree (`INVENTREE_SRC` set): the GitLab CI uses the
93
+ `inventree/inventree:stable` image with a SQLite database. Sample labels and their decoded barcodes are in
94
+ `docs/samples`.
95
+
96
+ ## License
97
+
98
+ MIT
@@ -0,0 +1,80 @@
1
+ # Würth Elektronik Barcode
2
+
3
+ [InvenTree](https://inventree.org) plugin (>= 1.0) that reads the barcodes of the **Würth Elektronik** labels, from the
4
+ web interface and from the **InvenTree app**: scanning a label opens the part, and inside a purchase order it receives
5
+ the line item with the quantity of the label.
6
+
7
+ ## The labels
8
+
9
+ The Würth Elektronik labels (reels, bags, samples) carry the ANSI MH10.8.2 data identifiers:
10
+
11
+ | Identifier | Field | Example |
12
+ |---|---|---|
13
+ | `1P` | Part number (Würth order code = manufacturer part number) | `609 002 134 21` |
14
+ | `Q` | Quantity | `10` |
15
+ | `1T` | Lot number | `298010012537000` |
16
+ | `16D` | Production date | `20250908` |
17
+
18
+ The **DataMatrix** holds all of them (ISO/IEC 15434 format 06:
19
+ `[)>␞06␝1P60900213421␝Q10␝1T298010012537000␝16D20250908␞␄`); each **Code 128** barcode holds one field. The plugin
20
+ reads the DataMatrix and the part number barcode (`1P…`).
21
+
22
+ The label names no supplier: it is recognised by its content, a numeric `1P` and none of the fields that distributors
23
+ add to their own labels (DigiKey `P` / `30P`, Mouser and DigiKey `11K`), so it is not confused with them.
24
+
25
+ ## What a scan does
26
+
27
+ - **Part lookup** (scan from the home page, web or app):
28
+ - the **supplier part** of the Würth supplier, with the order code as SKU;
29
+ - the **manufacturer part** of Würth Elektronik with the order code as MPN, also when the part is bought from a
30
+ distributor (e.g. Mouser).
31
+
32
+ Spaces are ignored: `609 002 134 21` and `60900213421` are the same code.
33
+ - **Purchase order receiving** (*Purchase order → Scan to receive*, web or app): in a placed order of the Würth supplier
34
+ the line item of the part is received with the quantity of the label, into the destination of the line or of the
35
+ order.
36
+
37
+ ## Installation
38
+
39
+ The plugin is on [PyPI](https://pypi.org/project/inventree-wurth-barcode/):
40
+
41
+ - **from the InvenTree UI** (*Settings → Plugins → Install plugin*): *Package Name* `inventree-wurth-barcode`;
42
+ - **or with `plugins.txt`** (next to `config.yaml`, or the file set by `INVENTREE_PLUGIN_FILE`): a line
43
+ `inventree-wurth-barcode`.
44
+
45
+ Then activate **Würth Elektronik Barcode** in *Settings → Plugins* and restart server and worker. The plugin has no
46
+ database tables: no migrations are needed. With Docker, install it in **both** the server and the worker container
47
+ (different versions cause the *Plugin Registry Mismatch* error, INVE-E20):
48
+
49
+ ```bash
50
+ docker compose exec inventree-server invoke plugins
51
+ docker compose exec inventree-worker invoke plugins
52
+ docker compose restart inventree-server inventree-worker
53
+ ```
54
+
55
+ With the package installer (`.deb`): `sudo inventree run invoke plugins`, then `sudo inventree restart`.
56
+
57
+ The **InvenTree app** needs no change: it sends the scanned barcodes to the server, which passes them to the active
58
+ barcode plugins.
59
+
60
+ ## Settings
61
+
62
+ | Setting | Notes |
63
+ |---|---|
64
+ | `SUPPLIER_ID` | Supplier company of the parts bought from Würth Elektronik. If empty, the only supplier whose name contains *Würth*, *Wurth* or *Wuerth* is used (and saved) |
65
+ | `MANUFACTURER_ID` | Manufacturer company of the Würth Elektronik parts. If empty, found by name as above |
66
+
67
+ ## Development
68
+
69
+ ```bash
70
+ python -m pytest # parser tests, no InvenTree needed
71
+ ruff check wurth_barcode tests
72
+ ```
73
+
74
+ `tests/integration` runs on a real InvenTree (`INVENTREE_SRC` set): the GitLab CI uses the
75
+ `inventree/inventree:stable` image with a SQLite database. Sample labels and their decoded barcodes are in
76
+ `docs/samples`.
77
+
78
+ ## License
79
+
80
+ MIT
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: inventree-wurth-barcode
3
+ Version: 0.1.1
4
+ Summary: InvenTree plugin: scan the barcodes of the Würth Elektronik labels (part lookup and purchase order receiving)
5
+ Author-email: Simone Amadori <simone@amadori.bs.it>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Kamaar/inventree-wurth-barcode
8
+ Project-URL: Repository, https://github.com/Kamaar/inventree-wurth-barcode
9
+ Project-URL: Issues, https://github.com/Kamaar/inventree-wurth-barcode/issues
10
+ Keywords: inventree,plugin,barcode,wurth,wurth-elektronik,datamatrix
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Framework :: InvenTree
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Dynamic: license-file
18
+
19
+ # Würth Elektronik Barcode
20
+
21
+ [InvenTree](https://inventree.org) plugin (>= 1.0) that reads the barcodes of the **Würth Elektronik** labels, from the
22
+ web interface and from the **InvenTree app**: scanning a label opens the part, and inside a purchase order it receives
23
+ the line item with the quantity of the label.
24
+
25
+ ## The labels
26
+
27
+ The Würth Elektronik labels (reels, bags, samples) carry the ANSI MH10.8.2 data identifiers:
28
+
29
+ | Identifier | Field | Example |
30
+ |---|---|---|
31
+ | `1P` | Part number (Würth order code = manufacturer part number) | `609 002 134 21` |
32
+ | `Q` | Quantity | `10` |
33
+ | `1T` | Lot number | `298010012537000` |
34
+ | `16D` | Production date | `20250908` |
35
+
36
+ The **DataMatrix** holds all of them (ISO/IEC 15434 format 06:
37
+ `[)>␞06␝1P60900213421␝Q10␝1T298010012537000␝16D20250908␞␄`); each **Code 128** barcode holds one field. The plugin
38
+ reads the DataMatrix and the part number barcode (`1P…`).
39
+
40
+ The label names no supplier: it is recognised by its content, a numeric `1P` and none of the fields that distributors
41
+ add to their own labels (DigiKey `P` / `30P`, Mouser and DigiKey `11K`), so it is not confused with them.
42
+
43
+ ## What a scan does
44
+
45
+ - **Part lookup** (scan from the home page, web or app):
46
+ - the **supplier part** of the Würth supplier, with the order code as SKU;
47
+ - the **manufacturer part** of Würth Elektronik with the order code as MPN, also when the part is bought from a
48
+ distributor (e.g. Mouser).
49
+
50
+ Spaces are ignored: `609 002 134 21` and `60900213421` are the same code.
51
+ - **Purchase order receiving** (*Purchase order → Scan to receive*, web or app): in a placed order of the Würth supplier
52
+ the line item of the part is received with the quantity of the label, into the destination of the line or of the
53
+ order.
54
+
55
+ ## Installation
56
+
57
+ The plugin is on [PyPI](https://pypi.org/project/inventree-wurth-barcode/):
58
+
59
+ - **from the InvenTree UI** (*Settings → Plugins → Install plugin*): *Package Name* `inventree-wurth-barcode`;
60
+ - **or with `plugins.txt`** (next to `config.yaml`, or the file set by `INVENTREE_PLUGIN_FILE`): a line
61
+ `inventree-wurth-barcode`.
62
+
63
+ Then activate **Würth Elektronik Barcode** in *Settings → Plugins* and restart server and worker. The plugin has no
64
+ database tables: no migrations are needed. With Docker, install it in **both** the server and the worker container
65
+ (different versions cause the *Plugin Registry Mismatch* error, INVE-E20):
66
+
67
+ ```bash
68
+ docker compose exec inventree-server invoke plugins
69
+ docker compose exec inventree-worker invoke plugins
70
+ docker compose restart inventree-server inventree-worker
71
+ ```
72
+
73
+ With the package installer (`.deb`): `sudo inventree run invoke plugins`, then `sudo inventree restart`.
74
+
75
+ The **InvenTree app** needs no change: it sends the scanned barcodes to the server, which passes them to the active
76
+ barcode plugins.
77
+
78
+ ## Settings
79
+
80
+ | Setting | Notes |
81
+ |---|---|
82
+ | `SUPPLIER_ID` | Supplier company of the parts bought from Würth Elektronik. If empty, the only supplier whose name contains *Würth*, *Wurth* or *Wuerth* is used (and saved) |
83
+ | `MANUFACTURER_ID` | Manufacturer company of the Würth Elektronik parts. If empty, found by name as above |
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ python -m pytest # parser tests, no InvenTree needed
89
+ ruff check wurth_barcode tests
90
+ ```
91
+
92
+ `tests/integration` runs on a real InvenTree (`INVENTREE_SRC` set): the GitLab CI uses the
93
+ `inventree/inventree:stable` image with a SQLite database. Sample labels and their decoded barcodes are in
94
+ `docs/samples`.
95
+
96
+ ## License
97
+
98
+ MIT
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ inventree_wurth_barcode.egg-info/PKG-INFO
5
+ inventree_wurth_barcode.egg-info/SOURCES.txt
6
+ inventree_wurth_barcode.egg-info/dependency_links.txt
7
+ inventree_wurth_barcode.egg-info/entry_points.txt
8
+ inventree_wurth_barcode.egg-info/top_level.txt
9
+ tests/test_parser.py
10
+ wurth_barcode/__init__.py
11
+ wurth_barcode/core.py
12
+ wurth_barcode/parser.py
@@ -0,0 +1,2 @@
1
+ [inventree_plugins]
2
+ WurthBarcodePlugin = wurth_barcode.core:WurthBarcodePlugin
@@ -0,0 +1,56 @@
1
+ # Packaging for the WurthBarcodePlugin InvenTree plugin.
2
+ # Structure follows the InvenTree plugin-creator template:
3
+ # https://github.com/inventree/plugin-creator
4
+
5
+ [build-system]
6
+ requires = ["setuptools", "wheel"]
7
+ build-backend = "setuptools.build_meta"
8
+
9
+ [project]
10
+ name = "inventree-wurth-barcode"
11
+ description = "InvenTree plugin: scan the barcodes of the Würth Elektronik labels (part lookup and purchase order receiving)"
12
+ dynamic = ["version"]
13
+ authors = [
14
+ { name = "Simone Amadori", email = "simone@amadori.bs.it" },
15
+ ]
16
+ readme = "README.md"
17
+ license = "MIT"
18
+ keywords = ["inventree", "plugin", "barcode", "wurth", "wurth-elektronik", "datamatrix"]
19
+ requires-python = ">=3.10"
20
+ dependencies = []
21
+ classifiers = [
22
+ "Programming Language :: Python :: 3",
23
+ "Operating System :: OS Independent",
24
+ "Framework :: InvenTree",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/Kamaar/inventree-wurth-barcode"
29
+ Repository = "https://github.com/Kamaar/inventree-wurth-barcode"
30
+ Issues = "https://github.com/Kamaar/inventree-wurth-barcode/issues"
31
+
32
+ [project.entry-points."inventree_plugins"]
33
+ WurthBarcodePlugin = "wurth_barcode.core:WurthBarcodePlugin"
34
+
35
+ [dependency-groups]
36
+ dev = [
37
+ "pytest>=8",
38
+ "ruff>=0.6",
39
+ ]
40
+
41
+ [tool.setuptools.packages.find]
42
+ where = [""]
43
+ include = ["wurth_barcode*"]
44
+
45
+ [tool.setuptools.dynamic]
46
+ version = { attr = "wurth_barcode.PLUGIN_VERSION" }
47
+
48
+ [tool.pytest.ini_options]
49
+ testpaths = ["tests"]
50
+
51
+ [tool.ruff]
52
+ src = ["wurth_barcode"]
53
+ exclude = [".git", "__pycache__", ".venv", "build", "dist"]
54
+
55
+ [tool.ruff.lint]
56
+ ignore = ["I001", "PIE790", "RUF012"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,78 @@
1
+ """Parser of the Würth Elektronik label barcodes (no InvenTree needed)."""
2
+
3
+ import json
4
+ import pathlib
5
+
6
+ import pytest
7
+
8
+ from wurth_barcode import parser
9
+
10
+ SAMPLES = json.loads(
11
+ (pathlib.Path(__file__).resolve().parent.parent / 'docs' / 'samples' / 'barcodes.json').read_text(encoding='utf-8')
12
+ )
13
+
14
+
15
+ def test_label_datamatrix_samples():
16
+ assert parser.parse(SAMPLES['IMG20261127082800']['datamatrix']) == {
17
+ '1P': '60900213421',
18
+ 'Q': '10',
19
+ '1T': '298010012537000',
20
+ '16D': '20250908',
21
+ }
22
+ assert parser.parse(SAMPLES['IMG20261127083011']['datamatrix']) == {
23
+ '1P': '94518200',
24
+ 'Q': '20',
25
+ '1T': '300010032430000',
26
+ '16D': '20240724',
27
+ }
28
+
29
+
30
+ def test_control_pictures_are_accepted():
31
+ # Some apps show / send the Unicode control pictures instead of the control characters
32
+ data = '[)>␞06␝1P94518200␝Q20␝1T300010032430000␝16D20240724␞␄'
33
+ assert parser.parse(data)['1P'] == '94518200'
34
+
35
+
36
+ def test_without_trailer():
37
+ assert parser.parse('[)>\x1e06\x1d1P94518200\x1dQ20')['Q'] == '20'
38
+
39
+
40
+ @pytest.mark.parametrize('data', ['1P94518200', '1P609 002 134 21', ' 1P60900213421 '])
41
+ def test_single_part_number_barcode(data):
42
+ assert parser.parse(data) == {'1P': parser.compact_code(data.strip()[2:])}
43
+
44
+
45
+ @pytest.mark.parametrize(
46
+ 'data',
47
+ [
48
+ '',
49
+ 'Q20',
50
+ '1T300010032430000',
51
+ '1PSN74HC00N',
52
+ # DigiKey: customer part 'P', DigiKey number '30P'
53
+ '[)>\x1e06\x1dP296-1234-ND\x1d1P60900213421\x1d30P732-5315-ND\x1dQ10\x1e\x04',
54
+ # Mouser: packing list '11K'
55
+ '[)>\x1e06\x1dK123\x1d14K001\x1d1P60900213421\x1dQ10\x1d11K0123456\x1e\x04',
56
+ # Not a numeric order code
57
+ '[)>\x1e06\x1d1PGRM155R71H104KE14D\x1dQ10000\x1e\x04',
58
+ # Another barcode format
59
+ '{"part": 12}',
60
+ ],
61
+ )
62
+ def test_not_a_wurth_label(data):
63
+ assert parser.parse(data) is None
64
+
65
+
66
+ def test_identifiers_are_not_confused():
67
+ fields = parser.split_fields('[)>\x1e06\x1d16D20240724\x1d1T123\x1d1P94518200\x1dQ5\x1e\x04')
68
+ assert fields == {'16D': '20240724', '1T': '123', '1P': '94518200', 'Q': '5'}
69
+
70
+
71
+ def test_order_and_country_fields():
72
+ fields = parser.parse('[)>\x1e06\x1dK4500012345\x1d1K987654\x1d1P94518200\x1dQ20\x1d4LDE\x1e\x04')
73
+ assert fields['K'] == '4500012345' and fields['1K'] == '987654' and fields['4L'] == 'DE'
74
+
75
+
76
+ @pytest.mark.parametrize(('value', 'expected'), [('20250908', '2025-09-08'), ('2025', ''), ('', '')])
77
+ def test_production_date(value, expected):
78
+ assert parser.production_date(value) == expected
@@ -0,0 +1,2 @@
1
+ PLUGIN_VERSION = "0.1.1"
2
+ PLUGIN_DATE = "2026-11-27"
@@ -0,0 +1,236 @@
1
+ """Scan Würth Elektronik label barcodes in InvenTree (web interface and app)."""
2
+
3
+ from django.db.models import Q, Value
4
+ from django.db.models.functions import Replace
5
+ from django.utils.translation import gettext_lazy as _
6
+
7
+ from plugin import InvenTreePlugin
8
+ from plugin.mixins import SettingsMixin, SupplierBarcodeMixin
9
+
10
+ from . import PLUGIN_DATE, PLUGIN_VERSION, parser
11
+
12
+ # Company names of Würth Elektronik (with or without the umlaut)
13
+ WURTH_NAMES = Q(name__icontains='würth') | Q(name__icontains='wurth') | Q(name__icontains='wuerth')
14
+
15
+
16
+ def _compact(field: str):
17
+ """The field without spaces, for a comparison with the compact order code."""
18
+ return Replace(field, Value(' '), Value(''))
19
+
20
+
21
+ class WurthBarcodePlugin(SupplierBarcodeMixin, SettingsMixin, InvenTreePlugin):
22
+ """Würth Elektronik label barcodes: part lookup and purchase order receiving."""
23
+
24
+ NAME = 'WurthBarcodePlugin'
25
+ SLUG = 'wurth-barcode'
26
+ TITLE = 'Würth Elektronik Barcode'
27
+ DESCRIPTION = 'Scan the barcodes of the Würth Elektronik labels (part number, quantity, lot)'
28
+ VERSION = PLUGIN_VERSION
29
+ PUBLISH_DATE = PLUGIN_DATE
30
+ AUTHOR = 'Simone Amadori'
31
+ LICENSE = 'MIT'
32
+ WEBSITE = 'https://github.com/Kamaar/inventree-wurth-barcode'
33
+
34
+ MIN_VERSION = '1.0.0'
35
+
36
+ DEFAULT_SUPPLIER_NAME = 'Würth Elektronik'
37
+
38
+ SETTINGS = {
39
+ 'SUPPLIER_ID': {
40
+ 'name': _('Supplier'),
41
+ 'description': _(
42
+ 'Supplier company of the parts bought from Würth Elektronik. '
43
+ 'If empty, a supplier whose name contains "Würth" or "Wurth" is used'
44
+ ),
45
+ 'model': 'company.company',
46
+ 'model_filters': {'is_supplier': True},
47
+ },
48
+ 'MANUFACTURER_ID': {
49
+ 'name': _('Manufacturer'),
50
+ 'description': _(
51
+ 'Manufacturer company of the Würth Elektronik parts. '
52
+ 'If empty, a manufacturer whose name contains "Würth" or "Wurth" is used'
53
+ ),
54
+ 'model': 'company.company',
55
+ 'model_filters': {'is_manufacturer': True},
56
+ },
57
+ }
58
+
59
+ # ---------------------------------------------------------------- barcode fields
60
+
61
+ def extract_barcode_fields(self, barcode_data: str) -> dict[str, str]:
62
+ """Standard InvenTree field names of a Würth label ({} if it is not one)."""
63
+ fields = parser.parse(barcode_data)
64
+
65
+ if not fields:
66
+ return {}
67
+
68
+ code = fields['1P']
69
+ result = {
70
+ # The Würth order code is also the manufacturer part number
71
+ self.SUPPLIER_PART_NUMBER: code,
72
+ self.MANUFACTURER_PART_NUMBER: code,
73
+ }
74
+
75
+ for identifier, name in (
76
+ ('Q', self.QUANTITY),
77
+ ('1T', self.LOT_CODE),
78
+ ('K', self.CUSTOMER_ORDER_NUMBER),
79
+ ('1K', self.SUPPLIER_ORDER_NUMBER),
80
+ ('4L', self.COUNTRY_OF_ORIGIN),
81
+ ):
82
+ if fields.get(identifier):
83
+ result[name] = fields[identifier]
84
+
85
+ if date := parser.production_date(fields.get('16D', '')):
86
+ result[self.DATE_CODE] = date
87
+
88
+ return result
89
+
90
+ # ---------------------------------------------------------------- scans
91
+
92
+ def scan(self, barcode_data: str, user, **kwargs):
93
+ """Scan of a barcode (None if it is not a Würth label or nothing matches)."""
94
+ # The plugin object lives as long as the server: the supplier is looked up again for every scan
95
+ self.__dict__.pop('_supplier', None)
96
+ return super().scan(barcode_data, user, **kwargs)
97
+
98
+ def scan_receive_item(self, barcode_data: str, user, **kwargs):
99
+ """Receive a purchase order line item from a Würth label.
100
+
101
+ Scanned inside a purchase order (web or app), the supplier is the one of the order:
102
+ the supplier part is looked up there, also when it is not the Würth supplier of the
103
+ settings. The lot of the label becomes the batch code of the received stock.
104
+ """
105
+ self.__dict__.pop('_supplier', None)
106
+ order = kwargs.get('purchase_order')
107
+
108
+ if kwargs.get('supplier') is None and getattr(order, 'supplier', None) is not None:
109
+ kwargs['supplier'] = order.supplier
110
+
111
+ self._receive_supplier = kwargs.get('supplier')
112
+ self._batch_order = order if hasattr(order, 'receive_line_item') else None
113
+
114
+ try:
115
+ if self._batch_order is not None:
116
+ self._wrap_batch_code(barcode_data, self._batch_order)
117
+
118
+ return super().scan_receive_item(barcode_data, user, **kwargs)
119
+ finally:
120
+ if self._batch_order is not None:
121
+ self._batch_order.__dict__.pop('receive_line_item', None)
122
+
123
+ self._receive_supplier = None
124
+ self._batch_order = None
125
+
126
+ def _wrap_batch_code(self, barcode_data: str, order):
127
+ """Receive the line of this order with the lot of the label as batch code."""
128
+ fields = parser.parse(barcode_data) or {}
129
+ lot = fields.get('1T')
130
+
131
+ if not lot:
132
+ return
133
+
134
+ receive = order.receive_line_item
135
+
136
+ def receive_with_batch(*args, **kwargs):
137
+ kwargs.setdefault('batch_code', lot)
138
+ return receive(*args, **kwargs)
139
+
140
+ # Only on this order object, for this scan
141
+ order.receive_line_item = receive_with_batch
142
+
143
+ # ---------------------------------------------------------------- companies
144
+
145
+ def _company(self, setting: str, **flags):
146
+ """The company selected in a setting, or the only one named as Würth (saved in the setting)."""
147
+ from company.models import Company
148
+
149
+ if pk := self.get_setting(setting):
150
+ company = Company.objects.filter(pk=pk).first()
151
+
152
+ if company is not None:
153
+ return company
154
+
155
+ # The selected company was deleted: look it up again by name
156
+
157
+ companies = list(Company.objects.filter(WURTH_NAMES, **flags)[:2])
158
+
159
+ if len(companies) != 1:
160
+ return None
161
+
162
+ self.set_setting(setting, companies[0].pk)
163
+ return companies[0]
164
+
165
+ def get_supplier(self, cache: bool = False):
166
+ """The Würth Elektronik supplier (SUPPLIER_ID, or found by name)."""
167
+ if cache and hasattr(self, '_supplier'):
168
+ return self._supplier
169
+
170
+ supplier = self._company('SUPPLIER_ID', is_supplier=True)
171
+
172
+ if cache:
173
+ self._supplier = supplier
174
+
175
+ return supplier
176
+
177
+ def get_manufacturer(self):
178
+ """The Würth Elektronik manufacturer (MANUFACTURER_ID, or found by name)."""
179
+ return self._company('MANUFACTURER_ID', is_manufacturer=True)
180
+
181
+ # ---------------------------------------------------------------- lookups
182
+
183
+ def _manufacturer_parts(self):
184
+ """Manufacturer parts with the order code as MPN (spaces ignored)."""
185
+ from company.models import ManufacturerPart
186
+
187
+ code = self.manufacturer_part_number
188
+
189
+ if not code:
190
+ return ManufacturerPart.objects.none()
191
+
192
+ return ManufacturerPart.objects.annotate(mpn_compact=_compact('MPN')).filter(mpn_compact=code)
193
+
194
+ def get_manufacturer_part(self):
195
+ """The Würth manufacturer part of the label (unique match required)."""
196
+ parts = self._manufacturer_parts()
197
+ companies = [c for c in (self.get_manufacturer(), self.get_supplier(cache=True)) if c is not None]
198
+
199
+ if companies:
200
+ narrowed = parts.filter(manufacturer__in=companies)
201
+
202
+ if narrowed.count() == 1:
203
+ return narrowed.first()
204
+
205
+ # The order codes are long numbers: a unique MPN is the Würth part
206
+ if parts.count() == 1:
207
+ return parts.first()
208
+
209
+ return None
210
+
211
+ def get_supplier_part(self):
212
+ """The supplier part of the Würth supplier (or of the order being received).
213
+
214
+ By SKU, otherwise by the MPN of its manufacturer part.
215
+ """
216
+ from company.models import SupplierPart
217
+
218
+ code = self.supplier_part_number
219
+ # Receiving in a purchase order: the supplier of the order
220
+ supplier = getattr(self, '_receive_supplier', None) or self.get_supplier(cache=True)
221
+
222
+ if not code or supplier is None:
223
+ return None
224
+
225
+ parts = SupplierPart.objects.filter(supplier=supplier)
226
+ by_sku = parts.annotate(sku_compact=_compact('SKU')).filter(sku_compact=code)
227
+
228
+ if by_sku.count() == 1:
229
+ return by_sku.first()
230
+
231
+ by_mpn = parts.filter(manufacturer_part__in=self._manufacturer_parts())
232
+
233
+ if by_mpn.count() == 1:
234
+ return by_mpn.first()
235
+
236
+ return None
@@ -0,0 +1,102 @@
1
+ """Würth Elektronik label barcodes (no Django: unit tested on its own).
2
+
3
+ The labels carry ANSI MH10.8.2 data identifiers:
4
+
5
+ - DataMatrix, ISO/IEC 15434 format 06:
6
+ '[)>␞06␝1P60900213421␝Q10␝1T298010012537000␝16D20250908␞␄'
7
+ - one Code 128 barcode per field: '1P60900213421', 'Q10', '1T298010012537000'
8
+
9
+ 1P is the Würth order code, which is also the manufacturer part number (printed with
10
+ spaces: '609 002 134 21'). The label names no supplier, so it is recognised by its
11
+ content: a numeric 1P and none of the fields which distributors add to their own
12
+ labels (DigiKey 'P' / '30P', Mouser and DigiKey '11K' packing list).
13
+ """
14
+
15
+ import re
16
+
17
+ HEADER = '[)>\x1e06\x1d'
18
+ TRAILER = '\x1e\x04'
19
+ GROUP_SEPARATOR = '\x1d'
20
+
21
+ # Some scanners and apps send the Unicode "control pictures" instead of the control characters
22
+ CONTROL_PICTURES = {'␞': '\x1e', '␝': '\x1d', '␄': '\x04'}
23
+
24
+ # Data identifiers, longest first: '16D' must not be read as '1' + '6D'
25
+ IDENTIFIERS = ('16D', '30P', '11K', '1P', '1T', '1K', '4L', '9D', '10D', 'P', 'Q', 'K', '1V')
26
+
27
+ # Fields of distributor labels: a label with one of them is not a Würth label
28
+ DISTRIBUTOR_IDENTIFIERS = {'P', '30P', '11K'}
29
+
30
+ # Würth Elektronik order codes are numbers (744031100, 60900213421, 94518200)
31
+ ORDER_CODE = re.compile(r'^\d{6,14}$')
32
+ SINGLE_PART_NUMBER = re.compile(r'^1P(\d{6,14})$')
33
+
34
+
35
+ def normalize(data: str) -> str:
36
+ """Raw scanner text, with the control pictures replaced by the control characters."""
37
+ text = str(data or '').strip()
38
+
39
+ for picture, char in CONTROL_PICTURES.items():
40
+ text = text.replace(picture, char)
41
+
42
+ return text
43
+
44
+
45
+ def compact_code(code: str) -> str:
46
+ """'609 002 134 21' -> '60900213421'."""
47
+ return re.sub(r'\s+', '', str(code or ''))
48
+
49
+
50
+ def split_fields(data: str) -> dict[str, str]:
51
+ """Data identifier -> value of an ISO/IEC 15434 format 06 barcode ({} if it is not one)."""
52
+ text = normalize(data)
53
+
54
+ if not text.startswith(HEADER):
55
+ return {}
56
+
57
+ text = text[len(HEADER):].removesuffix(TRAILER).rstrip('\x1e\x04')
58
+ fields = {}
59
+
60
+ for field in text.split(GROUP_SEPARATOR):
61
+ for identifier in IDENTIFIERS:
62
+ if field.startswith(identifier):
63
+ fields.setdefault(identifier, field[len(identifier):].strip())
64
+ break
65
+
66
+ return fields
67
+
68
+
69
+ def parse(data: str) -> dict[str, str] | None:
70
+ """The fields of a Würth Elektronik label, or None if the barcode is not one.
71
+
72
+ Returns the data identifiers found ('1P', 'Q', '1T', '16D', and 'K' / '1K' / '4L'
73
+ when present), with '1P' without spaces.
74
+ """
75
+ text = normalize(data)
76
+
77
+ # A single Code 128 barcode of the label: only the part number identifies the product
78
+ if match := SINGLE_PART_NUMBER.match(compact_code(text)):
79
+ return {'1P': match.group(1)}
80
+
81
+ fields = split_fields(text)
82
+
83
+ if not fields or DISTRIBUTOR_IDENTIFIERS & fields.keys():
84
+ return None
85
+
86
+ code = compact_code(fields.get('1P', ''))
87
+
88
+ if not ORDER_CODE.match(code):
89
+ return None
90
+
91
+ fields['1P'] = code
92
+ return fields
93
+
94
+
95
+ def production_date(value: str) -> str:
96
+ """'20250908' -> '2025-09-08' ('' if the value is not a date)."""
97
+ value = str(value or '').strip()
98
+
99
+ if re.match(r'^\d{8}$', value):
100
+ return f'{value[:4]}-{value[4:6]}-{value[6:]}'
101
+
102
+ return ''