diff --git a/barcode_gs1/README.rst b/barcode_gs1/README.rst new file mode 100644 index 0000000..8439222 --- /dev/null +++ b/barcode_gs1/README.rst @@ -0,0 +1,238 @@ +.. image:: https://odoo-community.org/readme-banner-image + :target: https://odoo-community.org/get-involved?utm_source=readme + :alt: Odoo Community Association + +=========== +Barcode GS1 +=========== + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:7b6424f4b2b745e0e0bdeb5ac492b6dfaad961cb4e7e9424bdbc03d38f1c09d9 + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png + :target: https://odoo-community.org/page/development-status + :alt: Beta +.. |badge2| image:: https://img.shields.io/badge/license-AGPL--3-blue.png + :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html + :alt: License: AGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fbarcode--interface-lightgray.png?logo=github + :target: https://github.com/OCA/barcode-interface/tree/17.0/barcode_gs1 + :alt: OCA/barcode-interface +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/barcode-interface-17-0/barcode-interface-17-0-barcode_gs1 + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png + :target: https://runboat.odoo-community.org/builds?repo=OCA/barcode-interface&target_branch=17.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module adds **GS1 barcode parsing** to the Barcode suite. + +It registers a GS1 parser into the ``barcode_scanner`` base — through +the ``barcode_parsers`` registry, without patching the base. Scanned +GS1-128 barcodes, whether written with parenthesised application +identifiers (``(01)...(10)...``) or as raw FNC1-separated data, are +decoded into structured fields: GTIN (AI 01), batch/lot (10), serial +(21), production/pack/best-before/ expiry dates (11/13/15/16/17), count +(30/37), net weight and other measures (310n–360n), amounts payable +(390n–393n), SSCC (00) and location GLNs (410/413/414). + +What each application identifier means is read from **Odoo's own GS1 +nomenclature** (``barcode.nomenclature`` and its rules, as shipped by +the standard *Barcode - GS1 Nomenclature* module), so a rule added or +adapted in Settings applies to the scanner too. Identifiers the +nomenclature does not define fall back to the ones built into this +module, so an unknown AI in the middle of a barcode never cuts the rest +of the scan short. + +Numeric identifiers — GTIN, SSCC, GLN — are only accepted when their +**check digit** matches, so a misread is reported instead of quietly +resolving to the wrong product. + +Every screen then receives the parsed data alongside the raw scan, so a +single GS1 scan can identify the product and fill lot, expiry and +quantity at once. Non-GS1 codes fall through to the base EAN13 parser, +so the module is safe to install next to the rest of the suite. + +**Table of contents** + +.. contents:: + :local: + +Configuration +============= + +No configuration is needed: once installed, GS1 barcodes are parsed +wherever the app reads a scan. Two things can be adjusted. + +Application identifiers +----------------------- + +The application identifiers are read from a GS1 +``barcode.nomenclature``: the one set on the company when it is a GS1 +nomenclature, otherwise the first GS1 nomenclature found (the *Default +GS1 Nomenclature* Odoo ships). Its GS1-128 rules are fetched once, when +the barcode app opens. + +To teach the scanner a new application identifier, add a rule under +*Inventory → Configuration → Barcode Nomenclatures* — no code change. A +rule whose *Type* is one the app understands (product, lot, quantity, +weighted product, priced product, package, package type, expiration +date, best before date, pack date, location, destination location) lands +on the matching field of the parsed scan (see Usage); the value of any +other rule is still available in ``ais``. + +Identifiers the nomenclature does not define keep working through the +ones built into the module, and if the nomenclature cannot be read at +all the module falls back to them entirely. + +Scanners that cannot send FNC1 +------------------------------ + +GS1 ends a variable-length value with FNC1 unless it is the last element +of the barcode, and a keyboard-wedge scanner often sends nothing in its +place. Odoo has a field for exactly that — *FNC1 Separator* on the +nomenclature — so configure the scanner to send one of those characters +(``#`` out of the box) and the scan is read as printed. + +Usage +===== + +Install ``barcode_gs1`` alongside ``barcode_scanner`` (and a feature +module such as ``barcode_stock``). Once installed, GS1 barcodes are +parsed automatically wherever the app reads a scan. + +A scanned GS1 barcode produces a parsed object such as: + +:: + + { + type: "gs1", + value: "", // GTIN (AI 01), in the form products store + gtin: "", // the GTIN exactly as scanned (14 digits) + productCodes: [...], // every form the GTIN may be stored as + lot: "", // AI 10 (falls back to the serial, AI 21) + serial: "", // AI 21 + expiry: "YYYY-MM-DD", // AI 17, or 15/16 when no 17 is present + useDate: "YYYY-MM-DD", // AI 15 / 16 (best before, sell by) + packDate: "YYYY-MM-DD", // AI 13 + productionDate: "...", // AI 11 + qty: , // AI 30 / 37; null when the label states no count + count: , // AI 30 / 37 (pieces), kept next to the weight + weight: , // AI 31xx–36xx, the measure of the goods + weightUom: {id, name}, // the unit that measure is in, per the rule + measures: [{ai, value, uom}, ...], // every measure, gross weight included + price: , // AI 390n–393n (amount payable) + currency: "", // the numeric code AI 391n / 393n carries + sscc: "", // AI 00 (logistic unit) + location: "", // AI 414 + locationDest: "", // AI 410 / 413 + ais: {"01": "...", "10": "...", ...}, + errors: [...], // what could not be read, e.g. a bad check digit + } + +Both parenthesised barcodes — ``(01)09501101020917(10)LOT123(17)261231`` +— and raw FNC1-separated scans are supported. + +GS1 always carries the GTIN zero-padded to 14 digits, while a product +stores the short code printed on the item. ``value`` therefore holds the +padding-free form Odoo stores (13 digits, as ``sanitize_ean`` produces), +which is what the screens match the product against; ``productCodes`` +lists the other lengths a barcode may have been stored as, +longest-standing form first. + +Variable-length values +---------------------- + +GS1 ends a variable-length value (a lot, a serial…) with FNC1, except +when it is the last element of the barcode, where none is needed. The +parser reads it that way: up to the next separator, or to the end of the +barcode (see Configuration for scanners that cannot send FNC1). + +Only when that reading is impossible — a value longer than its rule +allows — was a separator clearly dropped. The value then ends at the +next element that reads cleanly: a specific numeric identifier (never an +alphanumeric one, nor a catch-all range) with a value, a real date or a +right check digit. Anything short of that is ambiguous — ``21 5830192`` +is the serial 5830192, or the serial 58 followed by a count of 192 — and +is read as GS1 says, as one value. + +Misreads are refused +-------------------- + +A GTIN, SSCC or GLN is only accepted when its check digit (GS1 modulo +10) matches. A misread identifier is left empty and reported in +``errors`` instead of resolving to the wrong product or pallet. + +In the warehouse app +-------------------- + +What the warehouse app does with it (with ``barcode_stock`` installed): + +- the quantity picked is the piece count the label states (AI 30/37). A + label without one picks a single unit, or the pack's quantity when its + GTIN is a packaging barcode. A measure such as a net weight is decoded + but not taken as the quantity: that depends on the unit the product is + stocked in; +- the lot or serial is looked up for the scanned product and preselected + in the move wizard; on a receipt an unknown lot opens the create-lot + flow with the name and, when ``product_expiry`` is installed, the + expiry date prefilled; +- on a delivery or an internal transfer, a lot that is not available is + reported instead of silently picking another one. + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +------- + +* Binhex + +Contributors +------------ + +- `Antonio David Ruban Espinal `__ +- `Zuzanna Elzbieta Szalaty + Szalaty `__ + +Maintainers +----------- + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +.. |maintainer-szalatyzuzanna| image:: https://github.com/szalatyzuzanna.png?size=40px + :target: https://github.com/szalatyzuzanna + :alt: szalatyzuzanna + +Current `maintainer `__: + +|maintainer-szalatyzuzanna| + +This module is part of the `OCA/barcode-interface `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/barcode_gs1/__init__.py b/barcode_gs1/__init__.py new file mode 100644 index 0000000..739473c --- /dev/null +++ b/barcode_gs1/__init__.py @@ -0,0 +1,2 @@ +# barcode_gs1 has no Python models; it registers a GS1 barcode parser into the +# barcode_scanner framework from the frontend assets. diff --git a/barcode_gs1/__manifest__.py b/barcode_gs1/__manifest__.py new file mode 100644 index 0000000..dcdc41d --- /dev/null +++ b/barcode_gs1/__manifest__.py @@ -0,0 +1,26 @@ +{ + "name": "Barcode GS1", + "version": "17.0.1.0.0", + "category": "Hidden", + "summary": "GS1 barcode parsing (GS1-128, application identifiers)", + "author": "Binhex, Odoo Community Association (OCA)", + "website": "https://github.com/OCA/barcode-interface", + "maintainers": ["szalatyzuzanna"], + "license": "AGPL-3", + "depends": [ + "barcode_scanner", + "barcodes_gs1_nomenclature", + ], + "assets": { + "web.assets_backend": [ + "barcode_gs1/static/src/js/gs1_nomenclature.esm.js", + "barcode_gs1/static/src/js/gs1_parser.esm.js", + "barcode_gs1/static/src/js/gs1_startup.esm.js", + ], + "web.assets_unit_tests": [ + "barcode_gs1/static/tests/**/*", + ], + }, + "installable": True, + "auto_install": False, +} diff --git a/barcode_gs1/i18n/barcode_gs1.pot b/barcode_gs1/i18n/barcode_gs1.pot new file mode 100644 index 0000000..aadee09 --- /dev/null +++ b/barcode_gs1/i18n/barcode_gs1.pot @@ -0,0 +1,13 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 18.0\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: \n" diff --git a/barcode_gs1/i18n/fr.po b/barcode_gs1/i18n/fr.po new file mode 100644 index 0000000..d211c03 --- /dev/null +++ b/barcode_gs1/i18n/fr.po @@ -0,0 +1,14 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 18.0\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: Automatically generated\n" +"Language-Team: none\n" +"Language: fr\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: nplurals=2; plural=n > 1;\n" diff --git a/barcode_gs1/i18n/it.po b/barcode_gs1/i18n/it.po new file mode 100644 index 0000000..c0d5085 --- /dev/null +++ b/barcode_gs1/i18n/it.po @@ -0,0 +1,14 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 18.0\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: Automatically generated\n" +"Language-Team: none\n" +"Language: it\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: nplurals=2; plural=n != 1;\n" diff --git a/barcode_gs1/pyproject.toml b/barcode_gs1/pyproject.toml new file mode 100644 index 0000000..4231d0c --- /dev/null +++ b/barcode_gs1/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/barcode_gs1/readme/CONFIGURE.md b/barcode_gs1/readme/CONFIGURE.md new file mode 100644 index 0000000..e379d92 --- /dev/null +++ b/barcode_gs1/readme/CONFIGURE.md @@ -0,0 +1,29 @@ +No configuration is needed: once installed, GS1 barcodes are parsed wherever +the app reads a scan. Two things can be adjusted. + +## Application identifiers + +The application identifiers are read from a GS1 ``barcode.nomenclature``: the +one set on the company when it is a GS1 nomenclature, otherwise the first GS1 +nomenclature found (the *Default GS1 Nomenclature* Odoo ships). Its GS1-128 +rules are fetched once, when the barcode app opens. + +To teach the scanner a new application identifier, add a rule under +*Inventory → Configuration → Barcode Nomenclatures* — no code change. A rule +whose *Type* is one the app understands (product, lot, quantity, weighted +product, priced product, package, package type, expiration date, best before +date, pack date, location, destination location) lands on the matching field of +the parsed scan (see Usage); the value of any other rule is still available in +``ais``. + +Identifiers the nomenclature does not define keep working through the ones built +into the module, and if the nomenclature cannot be read at all the module falls +back to them entirely. + +## Scanners that cannot send FNC1 + +GS1 ends a variable-length value with FNC1 unless it is the last element of the +barcode, and a keyboard-wedge scanner often sends nothing in its place. Odoo has +a field for exactly that — *FNC1 Separator* on the nomenclature — so configure +the scanner to send one of those characters (``#`` out of the box) and the scan +is read as printed. diff --git a/barcode_gs1/readme/CONTRIBUTORS.md b/barcode_gs1/readme/CONTRIBUTORS.md new file mode 100644 index 0000000..7a07748 --- /dev/null +++ b/barcode_gs1/readme/CONTRIBUTORS.md @@ -0,0 +1,2 @@ +* [Antonio David Ruban Espinal](https://github.com/antoniodavid) +* [Zuzanna Elzbieta Szalaty Szalaty](https://github.com/szalatyzuzanna) diff --git a/barcode_gs1/readme/DESCRIPTION.md b/barcode_gs1/readme/DESCRIPTION.md new file mode 100644 index 0000000..3fa5305 --- /dev/null +++ b/barcode_gs1/readme/DESCRIPTION.md @@ -0,0 +1,26 @@ +This module adds **GS1 barcode parsing** to the Barcode suite. + +It registers a GS1 parser into the `barcode_scanner` base — through the +`barcode_parsers` registry, without patching the base. Scanned GS1-128 +barcodes, whether written with parenthesised application identifiers +(`(01)...(10)...`) or as raw FNC1-separated data, are decoded into structured +fields: GTIN (AI 01), batch/lot (10), serial (21), production/pack/best-before/ +expiry dates (11/13/15/16/17), count (30/37), net weight and other measures +(310n–360n), amounts payable (390n–393n), SSCC (00) and location GLNs +(410/413/414). + +What each application identifier means is read from **Odoo's own GS1 +nomenclature** (`barcode.nomenclature` and its rules, as shipped by the +standard *Barcode - GS1 Nomenclature* module), so a rule added or adapted in +Settings applies to the scanner too. Identifiers the nomenclature does not +define fall back to the ones built into this module, so an unknown AI in the +middle of a barcode never cuts the rest of the scan short. + +Numeric identifiers — GTIN, SSCC, GLN — are only accepted when their **check +digit** matches, so a misread is reported instead of quietly resolving to the +wrong product. + +Every screen then receives the parsed data alongside the raw scan, so a single +GS1 scan can identify the product and fill lot, expiry and quantity at once. +Non-GS1 codes fall through to the base EAN13 parser, so the module is safe to +install next to the rest of the suite. diff --git a/barcode_gs1/readme/USAGE.md b/barcode_gs1/readme/USAGE.md new file mode 100644 index 0000000..38c398c --- /dev/null +++ b/barcode_gs1/readme/USAGE.md @@ -0,0 +1,73 @@ +Install ``barcode_gs1`` alongside ``barcode_scanner`` (and a feature module such +as ``barcode_stock``). Once installed, GS1 barcodes are parsed automatically +wherever the app reads a scan. + +A scanned GS1 barcode produces a parsed object such as: + + { + type: "gs1", + value: "", // GTIN (AI 01), in the form products store + gtin: "", // the GTIN exactly as scanned (14 digits) + productCodes: [...], // every form the GTIN may be stored as + lot: "", // AI 10 (falls back to the serial, AI 21) + serial: "", // AI 21 + expiry: "YYYY-MM-DD", // AI 17, or 15/16 when no 17 is present + useDate: "YYYY-MM-DD", // AI 15 / 16 (best before, sell by) + packDate: "YYYY-MM-DD", // AI 13 + productionDate: "...", // AI 11 + qty: , // AI 30 / 37; null when the label states no count + count: , // AI 30 / 37 (pieces), kept next to the weight + weight: , // AI 31xx–36xx, the measure of the goods + weightUom: {id, name}, // the unit that measure is in, per the rule + measures: [{ai, value, uom}, ...], // every measure, gross weight included + price: , // AI 390n–393n (amount payable) + currency: "", // the numeric code AI 391n / 393n carries + sscc: "", // AI 00 (logistic unit) + location: "", // AI 414 + locationDest: "", // AI 410 / 413 + ais: {"01": "...", "10": "...", ...}, + errors: [...], // what could not be read, e.g. a bad check digit + } + +Both parenthesised barcodes — ``(01)09501101020917(10)LOT123(17)261231`` — and +raw FNC1-separated scans are supported. + +GS1 always carries the GTIN zero-padded to 14 digits, while a product stores the +short code printed on the item. ``value`` therefore holds the padding-free form +Odoo stores (13 digits, as ``sanitize_ean`` produces), which is what the screens +match the product against; ``productCodes`` lists the other lengths a barcode may +have been stored as, longest-standing form first. + +## Variable-length values + +GS1 ends a variable-length value (a lot, a serial…) with FNC1, except when it is +the last element of the barcode, where none is needed. The parser reads it that +way: up to the next separator, or to the end of the barcode (see Configuration +for scanners that cannot send FNC1). + +Only when that reading is impossible — a value longer than its rule allows — +was a separator clearly dropped. The value then ends at the next element that +reads cleanly: a specific numeric identifier (never an alphanumeric one, nor a +catch-all range) with a value, a real date or a right check digit. Anything +short of that is ambiguous — ``21 5830192`` is the serial 5830192, or the serial +58 followed by a count of 192 — and is read as GS1 says, as one value. + +## Misreads are refused + +A GTIN, SSCC or GLN is only accepted when its check digit (GS1 modulo 10) +matches. A misread identifier is left empty and reported in ``errors`` instead +of resolving to the wrong product or pallet. + +## In the warehouse app + +What the warehouse app does with it (with ``barcode_stock`` installed): + +- the quantity picked is the piece count the label states (AI 30/37). A label + without one picks a single unit, or the pack's quantity when its GTIN is a + packaging barcode. A measure such as a net weight is decoded but not taken as + the quantity: that depends on the unit the product is stocked in; +- the lot or serial is looked up for the scanned product and preselected in the + move wizard; on a receipt an unknown lot opens the create-lot flow with the + name and, when ``product_expiry`` is installed, the expiry date prefilled; +- on a delivery or an internal transfer, a lot that is not available is reported + instead of silently picking another one. diff --git a/barcode_gs1/static/description/icon.png b/barcode_gs1/static/description/icon.png new file mode 100644 index 0000000..3a0328b Binary files /dev/null and b/barcode_gs1/static/description/icon.png differ diff --git a/barcode_gs1/static/description/index.html b/barcode_gs1/static/description/index.html new file mode 100644 index 0000000..d506c2b --- /dev/null +++ b/barcode_gs1/static/description/index.html @@ -0,0 +1,575 @@ + + + + + +Barcode GS1 + + + +
+ + + +Odoo Community Association + +
+

Barcode GS1

+ +

Beta License: AGPL-3 OCA/barcode-interface Translate me on Weblate Try me on Runboat

+

This module adds GS1 barcode parsing to the Barcode suite.

+

It registers a GS1 parser into the barcode_scanner base — through +the barcode_parsers registry, without patching the base. Scanned +GS1-128 barcodes, whether written with parenthesised application +identifiers ((01)...(10)...) or as raw FNC1-separated data, are +decoded into structured fields: GTIN (AI 01), batch/lot (10), serial +(21), production/pack/best-before/ expiry dates (11/13/15/16/17), count +(30/37), net weight and other measures (310n–360n), amounts payable +(390n–393n), SSCC (00) and location GLNs (410/413/414).

+

What each application identifier means is read from Odoo’s own GS1 +nomenclature (barcode.nomenclature and its rules, as shipped by +the standard Barcode - GS1 Nomenclature module), so a rule added or +adapted in Settings applies to the scanner too. Identifiers the +nomenclature does not define fall back to the ones built into this +module, so an unknown AI in the middle of a barcode never cuts the rest +of the scan short.

+

Numeric identifiers — GTIN, SSCC, GLN — are only accepted when their +check digit matches, so a misread is reported instead of quietly +resolving to the wrong product.

+

Every screen then receives the parsed data alongside the raw scan, so a +single GS1 scan can identify the product and fill lot, expiry and +quantity at once. Non-GS1 codes fall through to the base EAN13 parser, +so the module is safe to install next to the rest of the suite.

+

Table of contents

+ +
+

Configuration

+

No configuration is needed: once installed, GS1 barcodes are parsed +wherever the app reads a scan. Two things can be adjusted.

+
+

Application identifiers

+

The application identifiers are read from a GS1 +barcode.nomenclature: the one set on the company when it is a GS1 +nomenclature, otherwise the first GS1 nomenclature found (the Default +GS1 Nomenclature Odoo ships). Its GS1-128 rules are fetched once, when +the barcode app opens.

+

To teach the scanner a new application identifier, add a rule under +Inventory → Configuration → Barcode Nomenclatures — no code change. A +rule whose Type is one the app understands (product, lot, quantity, +weighted product, priced product, package, package type, expiration +date, best before date, pack date, location, destination location) lands +on the matching field of the parsed scan (see Usage); the value of any +other rule is still available in ais.

+

Identifiers the nomenclature does not define keep working through the +ones built into the module, and if the nomenclature cannot be read at +all the module falls back to them entirely.

+
+
+

Scanners that cannot send FNC1

+

GS1 ends a variable-length value with FNC1 unless it is the last element +of the barcode, and a keyboard-wedge scanner often sends nothing in its +place. Odoo has a field for exactly that — FNC1 Separator on the +nomenclature — so configure the scanner to send one of those characters +(# out of the box) and the scan is read as printed.

+
+
+
+

Usage

+

Install barcode_gs1 alongside barcode_scanner (and a feature +module such as barcode_stock). Once installed, GS1 barcodes are +parsed automatically wherever the app reads a scan.

+

A scanned GS1 barcode produces a parsed object such as:

+
+{
+    type: "gs1",
+    value: "<product code>",  // GTIN (AI 01), in the form products store
+    gtin: "<GTIN>",           // the GTIN exactly as scanned (14 digits)
+    productCodes: [...],      // every form the GTIN may be stored as
+    lot: "<batch/lot>",       // AI 10 (falls back to the serial, AI 21)
+    serial: "<serial>",       // AI 21
+    expiry: "YYYY-MM-DD",     // AI 17, or 15/16 when no 17 is present
+    useDate: "YYYY-MM-DD",    // AI 15 / 16 (best before, sell by)
+    packDate: "YYYY-MM-DD",   // AI 13
+    productionDate: "...",    // AI 11
+    qty: <number>,            // AI 30 / 37; null when the label states no count
+    count: <number>,          // AI 30 / 37 (pieces), kept next to the weight
+    weight: <number>,         // AI 31xx–36xx, the measure of the goods
+    weightUom: {id, name},    // the unit that measure is in, per the rule
+    measures: [{ai, value, uom}, ...], // every measure, gross weight included
+    price: <number>,          // AI 390n–393n (amount payable)
+    currency: "<ISO 4217>",   // the numeric code AI 391n / 393n carries
+    sscc: "<SSCC>",           // AI 00 (logistic unit)
+    location: "<GLN>",        // AI 414
+    locationDest: "<GLN>",    // AI 410 / 413
+    ais: {"01": "...", "10": "...", ...},
+    errors: [...],            // what could not be read, e.g. a bad check digit
+}
+
+

Both parenthesised barcodes — (01)09501101020917(10)LOT123(17)261231 +— and raw FNC1-separated scans are supported.

+

GS1 always carries the GTIN zero-padded to 14 digits, while a product +stores the short code printed on the item. value therefore holds the +padding-free form Odoo stores (13 digits, as sanitize_ean produces), +which is what the screens match the product against; productCodes +lists the other lengths a barcode may have been stored as, +longest-standing form first.

+
+

Variable-length values

+

GS1 ends a variable-length value (a lot, a serial…) with FNC1, except +when it is the last element of the barcode, where none is needed. The +parser reads it that way: up to the next separator, or to the end of the +barcode (see Configuration for scanners that cannot send FNC1).

+

Only when that reading is impossible — a value longer than its rule +allows — was a separator clearly dropped. The value then ends at the +next element that reads cleanly: a specific numeric identifier (never an +alphanumeric one, nor a catch-all range) with a value, a real date or a +right check digit. Anything short of that is ambiguous — 21 5830192 +is the serial 5830192, or the serial 58 followed by a count of 192 — and +is read as GS1 says, as one value.

+
+
+

Misreads are refused

+

A GTIN, SSCC or GLN is only accepted when its check digit (GS1 modulo +10) matches. A misread identifier is left empty and reported in +errors instead of resolving to the wrong product or pallet.

+
+
+

In the warehouse app

+

What the warehouse app does with it (with barcode_stock installed):

+
    +
  • the quantity picked is the piece count the label states (AI 30/37). A +label without one picks a single unit, or the pack’s quantity when its +GTIN is a packaging barcode. A measure such as a net weight is decoded +but not taken as the quantity: that depends on the unit the product is +stocked in;
  • +
  • the lot or serial is looked up for the scanned product and preselected +in the move wizard; on a receipt an unknown lot opens the create-lot +flow with the name and, when product_expiry is installed, the +expiry date prefilled;
  • +
  • on a delivery or an internal transfer, a lot that is not available is +reported instead of silently picking another one.
  • +
+
+
+
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • Binhex
  • +
+
+ +
+

Maintainers

+

This module is maintained by the OCA.

+ +Odoo Community Association + +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

Current maintainer:

+

szalatyzuzanna

+

This module is part of the OCA/barcode-interface project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+
+ + diff --git a/barcode_gs1/static/src/js/gs1_nomenclature.esm.js b/barcode_gs1/static/src/js/gs1_nomenclature.esm.js new file mode 100644 index 0000000..43fffff --- /dev/null +++ b/barcode_gs1/static/src/js/gs1_nomenclature.esm.js @@ -0,0 +1,181 @@ +import {BarcodeParser} from "@barcodes/js/barcode_parser"; + +/** + * The GS1 rules the parser works with come from Odoo's own nomenclature + * (`barcode.nomenclature` / `barcode.rule`, as shipped and extended by the + * standard `barcodes_gs1_nomenclature` module), so an administrator can add or + * adapt an application identifier from Settings instead of us hard-coding it. + * + * The scan path is synchronous, so the rules are fetched once when the app + * starts and cached here. Until they are loaded — or if no GS1 nomenclature is + * configured — the parser falls back to its built-in application identifiers. + */ + +const NOMENCLATURE_FIELDS = ["name", "is_gs1_nomenclature", "gs1_separator_fnc1"]; +const RULE_FIELDS = [ + "name", + "sequence", + "type", + "pattern", + "gs1_content_type", + "gs1_decimal_usage", + "associated_uom_id", +]; + +// Every rule pattern starts with the application identifier group, e.g. +// "(310[0-5])(\d{6})" -> AI "310[0-5]", value "\d{6}". +const AI_GROUP = /^\(([^()]*)\)/; +// A value group is variable-length as soon as it carries an open quantifier. +const VARIABLE_QUANTIFIER = /[*+?]|\{\d*,\d*\}/; +const FIXED_QUANTIFIER = /\{(\d+)\}\)?$/; +const OPEN_QUANTIFIER = /\{\d*,(\d+)\}\)?$/; + +// Only used for `get_barcode_check_digit`, which is plain arithmetic on a +// string: no nomenclature needed. +const checkDigitParser = new BarcodeParser({}); + +let cachedNomenclature = null; + +/** + * The GS1 check digit (modulo 10) of a numeric identifier, computed the way + * Odoo does — the value is zero-padded to 18 digits first, so the same + * algorithm covers a GLN (13), a GTIN (14) and an SSCC (18). + */ +export function gs1CheckDigit(value) { + return checkDigitParser.get_barcode_check_digit(String(value).padStart(18, "0")); +} + +/** True if the last digit of a numeric identifier matches its check digit. */ +export function hasValidCheckDigit(value) { + const digits = String(value || ""); + if (!/^\d{2,18}$/.test(digits)) { + return false; + } + return gs1CheckDigit(digits) === parseInt(digits.slice(-1), 10); +} + +/** + * Turn a `barcode.rule` record into what the parser needs: how to recognise the + * application identifier, how long its value is, and how to read that value. + * + * Returns null for a pattern we cannot make sense of, so one broken custom rule + * cannot take the whole parser down with it. + */ +export function compileGs1Rule(rule) { + const pattern = rule.pattern || ""; + const aiMatch = AI_GROUP.exec(pattern); + if (!aiMatch) { + return null; + } + const valuePattern = pattern.slice(aiMatch[0].length); + const fixed = FIXED_QUANTIFIER.exec(valuePattern); + const open = OPEN_QUANTIFIER.exec(valuePattern); + const variable = VARIABLE_QUANTIFIER.test(valuePattern); + try { + return { + name: rule.name, + type: rule.type, + contentType: rule.gs1_content_type, + decimalUsage: Boolean(rule.gs1_decimal_usage), + // Catch-all built-ins (a whole AI range in one pattern) match too + // eagerly to be trusted as the boundary of a variable-length value. + generic: Boolean(rule.generic), + // The unit a measure is expressed in (AI 310n is kilograms, 320n + // pounds, ...), which is what tells a measure apart from a count. + uom: rule.associated_uom_id + ? {id: rule.associated_uom_id[0], name: rule.associated_uom_id[1]} + : null, + aiRegex: new RegExp(`^(?:${aiMatch[1]})`), + fullRegex: new RegExp(`^${pattern}$`), + fixedLength: variable ? null : (fixed && parseInt(fixed[1], 10)) || null, + maxLength: variable ? (open && parseInt(open[1], 10)) || 20 : null, + }; + } catch { + // An invalid regex in a user-edited rule: skip it. + return null; + } +} + +/** The cached GS1 nomenclature, or null while none is loaded. */ +export function getGs1Nomenclature() { + return cachedNomenclature; +} + +/** Set the cached nomenclature. Used by the loader and by the tests. */ +export function setGs1Nomenclature(nomenclature) { + cachedNomenclature = nomenclature; +} + +/** Compile a nomenclature record and its rules into what the parser reads. */ +export function compileGs1Nomenclature(nomenclature, rules) { + return { + id: nomenclature.id, + name: nomenclature.name, + separator: nomenclature.gs1_separator_fnc1 || null, + rules: rules + .slice() + .sort((left, right) => (left.sequence || 0) - (right.sequence || 0)) + .map(compileGs1Rule) + .filter(Boolean), + }; +} + +async function findGs1Nomenclature(orm, companyId) { + // The company's own nomenclature comes first: it is the one the rest of + // Odoo parses with. Any other GS1 nomenclature is a fallback, so the module + // still works when the company is left on the default (non-GS1) one. + if (companyId) { + const [company] = await orm.read( + "res.company", + [companyId], + ["nomenclature_id"] + ); + const nomenclatureId = company?.nomenclature_id && company.nomenclature_id[0]; + if (nomenclatureId) { + const [nomenclature] = await orm.read( + "barcode.nomenclature", + [nomenclatureId], + NOMENCLATURE_FIELDS + ); + if (nomenclature && nomenclature.is_gs1_nomenclature) { + return nomenclature; + } + } + } + const [nomenclature] = await orm.searchRead( + "barcode.nomenclature", + [["is_gs1_nomenclature", "=", true]], + NOMENCLATURE_FIELDS, + {limit: 1} + ); + return nomenclature || null; +} + +/** + * Fetch the GS1 nomenclature and its GS1-128 rules, and cache them for the + * parser. Returns the cached nomenclature, or null when there is none to use — + * including when it cannot be read, so the parser falls back to its built-in + * identifiers instead of a half-read nomenclature. + */ +export async function loadGs1Nomenclature(orm, companyId) { + try { + const nomenclature = await findGs1Nomenclature(orm, companyId); + if (!nomenclature) { + setGs1Nomenclature(null); + return null; + } + const rules = await orm.searchRead( + "barcode.rule", + [ + ["barcode_nomenclature_id", "=", nomenclature.id], + ["encoding", "=", "gs1-128"], + ], + RULE_FIELDS, + {order: "sequence"} + ); + setGs1Nomenclature(compileGs1Nomenclature(nomenclature, rules)); + } catch { + setGs1Nomenclature(null); + } + return getGs1Nomenclature(); +} diff --git a/barcode_gs1/static/src/js/gs1_parser.esm.js b/barcode_gs1/static/src/js/gs1_parser.esm.js new file mode 100644 index 0000000..d55fed6 --- /dev/null +++ b/barcode_gs1/static/src/js/gs1_parser.esm.js @@ -0,0 +1,694 @@ +import {barcodeParsers} from "@barcode_scanner/js/registries.esm"; +import { + compileGs1Rule, + getGs1Nomenclature, + hasValidCheckDigit, +} from "@barcode_gs1/js/gs1_nomenclature.esm"; + +const GS1_SEPARATOR = String.fromCharCode(29); // FNC1 (, 0x1D) + +// The symbology identifiers the GS1 carriers prefix their data with: GS1-128, +// DataBar, GS1 DataMatrix, GS1 QR and GS1 DotCode. Their presence is itself +// proof that what follows is GS1 data ("]E0", a plain EAN-13, is not one of +// them). +const GS1_SYMBOLOGIES = ["]C1", "]e0", "]d2", "]Q3", "]J1"]; + +// An application identifier written in parentheses, as on the human-readable +// line of a label: "(01)", "(3103)". +const PARENTHESISED_AI = /\(\d{2,4}\)/; + +// Logistic measures (AI 330n-349n: the gross weight, dimensions and volume of +// the logistic unit) describe the pack, not the goods it holds. +const LOGISTIC_MEASURE_AI = /^3[34]/; + +// The characters GS1 allows in an alphanumeric value, as Odoo's own rules +// spell them out. +const ALPHA = '[!"%-/0-9:-?A-Z_a-z]'; + +/** + * Built-in application identifiers, written as `barcode.rule` patterns so they + * compile exactly like the ones read from the nomenclature. + * + * They are the fallback: the parser prefers the configured GS1 nomenclature and + * only reaches for these while it is still loading, when no GS1 nomenclature is + * configured, or for an identifier the nomenclature does not define (Odoo ships + * no rule for a production date, for instance) — otherwise an unknown AI in the + * middle of a barcode would cut the rest of the scan short. + */ +const BUILTIN_RULE_DEFS = [ + { + name: "SSCC", + pattern: "(00)(\\d{18})", + type: "package", + gs1_content_type: "identifier", + }, + { + name: "GTIN", + pattern: "(01)(\\d{14})", + type: "product", + gs1_content_type: "identifier", + }, + { + name: "GTIN of contained trade items", + pattern: "(02)(\\d{14})", + type: "product", + gs1_content_type: "identifier", + }, + { + name: "Batch or lot number", + pattern: `(10)(${ALPHA}{0,20})`, + type: "lot", + gs1_content_type: "alpha", + }, + { + name: "Production date", + pattern: "(11)(\\d{6})", + type: "production_date", + gs1_content_type: "date", + }, + { + name: "Pack date", + pattern: "(13)(\\d{6})", + type: "pack_date", + gs1_content_type: "date", + }, + { + name: "Best before date", + pattern: "(15)(\\d{6})", + type: "use_date", + gs1_content_type: "date", + }, + { + name: "Sell by date", + pattern: "(16)(\\d{6})", + type: "use_date", + gs1_content_type: "date", + }, + { + name: "Expiration date", + pattern: "(17)(\\d{6})", + type: "expiration_date", + gs1_content_type: "date", + }, + { + name: "Product variant", + pattern: "(20)(\\d{2})", + type: null, + gs1_content_type: "alpha", + }, + { + name: "Serial number", + pattern: `(21)(${ALPHA}{0,20})`, + type: "lot", + gs1_content_type: "alpha", + }, + { + name: "Consumer product variant", + pattern: `(22)(${ALPHA}{0,20})`, + type: null, + gs1_content_type: "alpha", + }, + { + name: "Variable count of items", + pattern: "(30)(\\d{0,8})", + type: "quantity", + gs1_content_type: "measure", + gs1_decimal_usage: false, + }, + { + name: "Measure (weight, length, volume, ...)", + pattern: "(3[1-6]\\d[0-5])(\\d{6})", + type: "quantity", + gs1_content_type: "measure", + gs1_decimal_usage: true, + generic: true, + }, + { + name: "Count of trade items", + pattern: "(37)(\\d{0,8})", + type: "quantity", + gs1_content_type: "measure", + gs1_decimal_usage: false, + }, + { + name: "Amount payable, single monetary area", + pattern: "(39[02][0-9])(\\d{0,15})", + type: "price", + gs1_content_type: "measure", + gs1_decimal_usage: true, + }, + { + // The value opens with the 3-digit ISO 4217 code of its currency. + name: "Amount payable with ISO currency code", + pattern: "(39[13][0-9])(\\d{3,18})", + type: "price", + gs1_content_type: "measure", + gs1_decimal_usage: true, + }, + { + name: "Ship to / Deliver to GLN", + pattern: "(410)(\\d{13})", + type: "location_dest", + gs1_content_type: "identifier", + }, + { + name: "Ship for / Deliver for GLN", + pattern: "(413)(\\d{13})", + type: "location_dest", + gs1_content_type: "identifier", + }, + { + name: "Physical location GLN", + pattern: "(414)(\\d{13})", + type: "location", + gs1_content_type: "identifier", + }, + { + name: "Package type", + pattern: `(91)(${ALPHA}{0,90})`, + type: "package_type", + gs1_content_type: "alpha", + }, + { + name: "Company internal information", + pattern: `(9[0-3])(${ALPHA}{0,30})`, + type: null, + gs1_content_type: "alpha", + generic: true, + }, +]; + +const BUILTIN_RULES = BUILTIN_RULE_DEFS.map(compileGs1Rule).filter(Boolean); + +/** + * The rules to parse with: the configured GS1 nomenclature first — so an + * administrator's rule always wins — then the built-in identifiers. + */ +function activeRules() { + const nomenclature = getGs1Nomenclature(); + return nomenclature ? [...nomenclature.rules, ...BUILTIN_RULES] : BUILTIN_RULES; +} + +/** + * The year a 2-digit GS1 year refers to, per section 7.12 of the GS1 General + * Specifications: the closest year within -49/+50 of the current one. + */ +function gs1Year(twoDigitYear) { + const now = new Date(); + const difference = twoDigitYear - (now.getFullYear() % 100); + let century = Math.floor(now.getFullYear() / 100); + if (difference >= 51 && difference <= 99) { + century -= 1; + } else if (difference >= -99 && difference <= -50) { + century += 1; + } + return century * 100 + twoDigitYear; +} + +function toISODate(value) { + if (!/^\d{6}$/.test(value)) { + return null; + } + const year = gs1Year(parseInt(value.slice(0, 2), 10)); + const month = parseInt(value.slice(2, 4), 10); + let day = parseInt(value.slice(4, 6), 10); + if (month < 1 || month > 12) { + return null; + } + if (day === 0) { + // GS1 allows DD = 00, meaning the last day of the month. + day = new Date(Date.UTC(year, month, 0)).getUTCDate(); + } + const candidate = new Date(Date.UTC(year, month - 1, day)); + if ( + candidate.getUTCFullYear() !== year || + candidate.getUTCMonth() !== month - 1 || + candidate.getUTCDate() !== day + ) { + return null; + } + return `${year.toString().padStart(4, "0")}-${month + .toString() + .padStart(2, "0")}-${day.toString().padStart(2, "0")}`; +} + +/** + * Every form of a GTIN that a product barcode may hold, in priority order. + * + * GS1 always carries the GTIN zero-padded to 14 digits, while products store + * the short code printed on the item (EAN13, UPC-A, EAN8). Stripping the + * padding is therefore part of reading a GS1 scan, not of matching a product. + */ +export function gtinVariants(gtin) { + const digits = String(gtin || "").replace(/\D/g, ""); + if (!digits) { + return []; + } + const significant = digits.replace(/^0+/, "") || "0"; + const variants = []; + // 13 first: Odoo's `sanitize_ean` stores barcodes as EAN13, so a UPC-A is + // held as a 13-digit code too. The other lengths cover codes stored raw. + for (const length of [13, 14, 12, 8]) { + if (significant.length <= length) { + variants.push(significant.padStart(length, "0")); + } + } + variants.push(digits, significant); + return [...new Set(variants)]; +} + +/** + * The GTIN form to match a product against: the EAN13-length code when the GTIN + * fits in one, otherwise the 14-digit code as scanned (a genuine ITF-14). + */ +export function gtinToProductCode(gtin) { + return gtinVariants(gtin)[0] || null; +} + +function normalizeBarcode(barcode) { + let value = String(barcode || "").trim(); + // Strip a leading symbology identifier such as "]C1" / "]d2". + if (/^\][A-Za-z0-9]{2}/.test(value)) { + value = value.slice(3); + } + if (value.startsWith(GS1_SEPARATOR)) { + value = value.slice(1); + } + return value; +} + +/** + * The nomenclature may declare its own separator characters, since a scanner + * that cannot emit FNC1 often sends "#" instead. This runs once the barcode is + * known to be GS1, never before: a product code that happens to contain such a + * character must not start looking like GS1 data because of it. + */ +function applyAlternativeSeparators(barcode) { + const separator = getGs1Nomenclature()?.separator; + if (!separator) { + return barcode; + } + try { + return barcode.replace(new RegExp(separator, "g"), GS1_SEPARATOR); + } catch { + // An invalid separator regex in the nomenclature: leave the scan as is. + return barcode; + } +} + +/** The rule that defines `ai`, or null. */ +function ruleForAi(ai, rules) { + for (const rule of rules) { + const match = rule.aiRegex.exec(ai); + if (match && match[0].length === ai.length) { + return rule; + } + } + return null; +} + +/** + * Read a token's value the way its rule says to: a numeric identifier is only + * accepted when its check digit is right, a date becomes an ISO date, and a + * measure gets its decimal point from the last digit of the AI. + */ +function readValue(token) { + const {rule, ai, value} = token; + switch (rule && rule.contentType) { + case "identifier": + if (!hasValidCheckDigit(value)) { + return {error: `Invalid GS1 check digit for AI ${ai}`}; + } + return {value}; + case "date": { + const date = toISODate(value); + return date ? {value: date} : {error: `Invalid GS1 date for AI ${ai}`}; + } + case "measure": { + const decimals = rule.decimalUsage ? parseInt(ai.slice(-1), 10) : 0; + let amount = value; + let currency = null; + // AI 391n and 393n put the ISO 4217 currency code before the amount. + if (rule.type === "price" && /^39[13]/.test(ai) && amount.length > 3) { + currency = amount.slice(0, 3); + amount = amount.slice(3); + } + const digits = parseInt(amount, 10); + if (!Number.isFinite(digits)) { + return {error: `Invalid GS1 measure for AI ${ai}`}; + } + return { + value: decimals > 0 ? digits / Math.pow(10, decimals) : digits, + currency, + }; + } + default: + return {value}; + } +} + +/** + * Whether the element found at a position may be taken as the end of the + * variable-length value that precedes it, when a separator was dropped. + * + * Only a specific, non-alphanumeric identifier qualifies. A digit sequence in a + * lot number happens to look like plenty of identifiers -- an alphanumeric lot + * such as "L0892611" contains "92", and a catch-all measure range matches + * almost any four digits -- and breaking there silently invents a quantity or + * truncates the lot. The element must also read cleanly: a value, a real date, + * a right check digit. + */ +function canEndValue(match) { + return ( + Boolean(match) && + !match.rule.generic && + match.rule.contentType !== "alpha" && + match.value !== "" && + !readValue(match).error + ); +} + +/** + * Where a variable-length value ends. + * + * GS1 ends it at the FNC1 separator, or at the end of the barcode when it is + * the last element -- where no separator is needed, and where GS1 recommends + * putting it. That reading comes first. Only when it is impossible -- the value + * would be longer than its rule allows, or not match it -- was a separator + * dropped, and the value is then ended at the next element that may end it. + * `matchAt(index)` returns the rule match at a position, as `matchRule` does. + */ +function findVariableEnd(barcode, start, ai, rule, matchAt) { + const separatorIndex = barcode.indexOf(GS1_SEPARATOR, start); + const end = separatorIndex === -1 ? barcode.length : separatorIndex; + const maxLength = rule.maxLength || 20; + if ( + end - start <= maxLength && + rule.fullRegex.test(ai + barcode.slice(start, end)) + ) { + return end; + } + const maxIndex = Math.min(end, start + maxLength); + for (let index = start + 1; index < maxIndex; index++) { + if (canEndValue(matchAt(index))) { + return index; + } + } + return maxIndex; +} + +/** + * The first rule that matches at `index`, with the value it captures. + * + * Finding where a variable-length value ends looks ahead with this same + * function, so the answer for each position is kept in `cache` for the whole + * barcode: without it an alphanumeric run such as "10A10A…" is read again at + * every level of the look-ahead, and the time grows exponentially. + */ +function matchRule(barcode, index, rules, cache = new Map()) { + if (cache.has(index)) { + return cache.get(index); + } + const matchAt = (position) => matchRule(barcode, position, rules, cache); + let result = null; + const rest = barcode.slice(index); + for (const rule of rules) { + const aiMatch = rule.aiRegex.exec(rest); + if (!aiMatch) { + continue; + } + const ai = aiMatch[0]; + const valueStart = index + ai.length; + let valueEnd = null; + if (rule.fixedLength) { + valueEnd = valueStart + rule.fixedLength; + if (valueEnd > barcode.length) { + continue; + } + } else { + valueEnd = findVariableEnd(barcode, valueStart, ai, rule, matchAt); + } + const value = barcode.slice(valueStart, valueEnd); + if (!rule.fullRegex.test(ai + value)) { + continue; + } + result = {rule, ai, value, end: valueEnd}; + break; + } + cache.set(index, result); + return result; +} + +function parseParenthesizedGS1(barcode, rules) { + const tokenRegex = /\((\d{2,4})\)([^()]*)/g; + const tokens = []; + let match = null; + while ((match = tokenRegex.exec(barcode)) !== null) { + const ai = match[1]; + tokens.push({rule: ruleForAi(ai, rules), ai, value: match[2].trim()}); + } + return {tokens, rest: ""}; +} + +function parseRawGS1(barcode, rules) { + const tokens = []; + const cache = new Map(); + let index = 0; + while (index < barcode.length) { + if (barcode[index] === GS1_SEPARATOR) { + index += 1; + continue; + } + const match = matchRule(barcode, index, rules, cache); + if (!match) { + break; + } + tokens.push({rule: match.rule, ai: match.ai, value: match.value}); + index = match.end; + } + return {tokens, rest: barcode.slice(index).replaceAll(GS1_SEPARATOR, "")}; +} + +/** + * The measure that stands for the goods themselves: the first trade measure + * whose unit is known, otherwise the first trade measure. A logistic measure + * (the gross weight of the pack, say) never does. + */ +function goodsMeasure(measures) { + const trade = measures.filter((measure) => !LOGISTIC_MEASURE_AI.test(measure.ai)); + return trade.find((measure) => measure.uom) || trade[0] || null; +} + +/** + * Decode a GS1 barcode into structured fields. + * + * The result follows the conventions the app already reads: `value`/`product` + * hold the product code (screens and scan handlers look the product up with + * it), `qty`/`quantity` the piece count the barcode states — null when it + * states none, so the screen applies its own default: a single unit, or the + * pack's quantity for a packaging barcode — and `lot`/`serial`/`expiration` the + * tracking data. A GS1 scan therefore flows through the existing screens + * without them knowing anything about GS1. + * + * Every measure the barcode carries is listed in `measures`, and the one that + * stands for the goods (a net weight, say, never the gross weight of the pack) + * is kept in `weight`/`weightUom`. None of them becomes the quantity here: + * whether one is depends on the unit the product is stocked in, which only the + * warehouse knows. + * + * What each application identifier means comes from Odoo's GS1 nomenclature + * when one is configured, so a rule added in Settings is honoured here too. + */ +export function parseGS1Barcode(barcode) { + const normalized = applyAlternativeSeparators(normalizeBarcode(barcode)); + const rules = activeRules(); + const {tokens, rest} = PARENTHESISED_AI.test(normalized) + ? parseParenthesizedGS1(normalized, rules) + : parseRawGS1(normalized, rules); + + const parsed = { + type: "gs1", + barcode: normalized, + value: null, + ais: {}, + gtin: null, + product: null, + productCodes: [], + sscc: null, + packageType: null, + lot: null, + serial: null, + expiration: null, + expiry: null, + useDate: null, + packDate: null, + productionDate: null, + location: null, + locationDest: null, + weight: null, + weightUom: null, + measures: [], + count: null, + price: null, + currency: null, + qty: null, + quantity: null, + errors: [], + }; + let hasExpiration = false; + let rejectedGtin = false; + + for (const token of tokens) { + parsed.ais[token.ai] = token.value; + if (!token.rule) { + parsed.errors.push(`Unknown GS1 application identifier ${token.ai}`); + continue; + } + if (!token.rule.fullRegex.test(token.ai + token.value)) { + // Only a parenthesised value can get here: the raw reading never + // cuts a value its rule would not accept. + parsed.errors.push(`Invalid GS1 value for AI ${token.ai}`); + rejectedGtin = rejectedGtin || token.rule.type === "product"; + continue; + } + const read = readValue(token); + if (read.error) { + parsed.errors.push(read.error); + rejectedGtin = rejectedGtin || token.rule.type === "product"; + continue; + } + const value = read.value; + + switch (token.rule.type) { + case "product": + // The trade item (AI 01) wins over the items it contains (02). + parsed.gtin = parsed.gtin || value; + break; + case "package": + parsed.sscc = value; + break; + case "package_type": + parsed.packageType = value; + break; + case "lot": + if (token.ai === "21") { + parsed.serial = value; + parsed.lot = parsed.lot || value; + } else { + parsed.lot = value; + } + break; + case "quantity": + if (token.rule.decimalUsage) { + parsed.measures.push({ai: token.ai, value, uom: token.rule.uom}); + } else { + parsed.count = value; + parsed.qty = value; + parsed.quantity = value; + } + break; + case "weight": + // A rule configured as a weighted product: a measure, exactly + // like a variable-weight one. + parsed.measures.push({ai: token.ai, value, uom: token.rule.uom}); + break; + case "price": + parsed.price = value; + parsed.currency = read.currency || parsed.currency; + break; + case "expiration_date": + parsed.expiration = value; + parsed.expiry = value; + hasExpiration = true; + break; + case "use_date": + parsed.useDate = value; + if (!hasExpiration) { + parsed.expiration = value; + parsed.expiry = value; + } + break; + case "pack_date": + parsed.packDate = value; + break; + case "production_date": + parsed.productionDate = value; + break; + case "location": + parsed.location = value; + break; + case "location_dest": + parsed.locationDest = value; + break; + } + } + + const measure = goodsMeasure(parsed.measures); + if (measure) { + parsed.weight = measure.value; + parsed.weightUom = measure.uom; + } + if (rest) { + parsed.errors.push(`Unparsed GS1 data "${rest}"`); + } + if (parsed.gtin) { + parsed.productCodes = gtinVariants(parsed.gtin); + [parsed.value] = parsed.productCodes; + parsed.product = parsed.value; + } else if (!rejectedGtin) { + parsed.errors.push("Missing GTIN (AI 01)"); + } + + return parsed; +} + +/** + * How a barcode shows itself to be GS1 data. A symbology identifier, an FNC1 + * separator or a parenthesised application identifier is proof. A raw string + * starting with the GTIN AI (01) and longer than an EAN13 is only a hint, which + * the parse has to confirm. Anything else is not GS1 data. + */ +function gs1Evidence(barcode) { + const raw = String(barcode || "").trim(); + if (GS1_SYMBOLOGIES.some((identifier) => raw.startsWith(identifier))) { + return "proof"; + } + const normalized = normalizeBarcode(barcode); + if (PARENTHESISED_AI.test(normalized) || normalized.includes(GS1_SEPARATOR)) { + return "proof"; + } + if (normalized.startsWith("01") && normalized.length > 13) { + return "hint"; + } + return null; +} + +/** + * True if the barcode may be GS1 data: proof of it, or the hint of a raw string + * starting with the GTIN AI (01) that is longer than a plain EAN13 (so genuine + * EAN13 codes fall through to the base parser). + */ +export function isGS1Barcode(barcode) { + return gs1Evidence(barcode) !== null; +} + +/** + * Registered barcode parser. Only claims GS1 data; returns null otherwise so + * the base EAN13 fallback (and any other parser) can handle the scan. A code + * that only hinted at GS1 and yields no application identifier at all — an + * ITF-14 with indicator digit 0, an internal reference starting with "01" — is + * not GS1 data either. + */ +export function parseGs1(barcode) { + const evidence = gs1Evidence(barcode); + if (!evidence) { + return null; + } + const parsed = parseGS1Barcode(barcode); + if (evidence === "hint" && !Object.keys(parsed.ais).length) { + return null; + } + return parsed; +} + +barcodeParsers.add("gs1", parseGs1, {sequence: 10}); diff --git a/barcode_gs1/static/src/js/gs1_startup.esm.js b/barcode_gs1/static/src/js/gs1_startup.esm.js new file mode 100644 index 0000000..827885a --- /dev/null +++ b/barcode_gs1/static/src/js/gs1_startup.esm.js @@ -0,0 +1,11 @@ +import {barcodeStartupTasks} from "@barcode_scanner/js/registries.esm"; +import {loadGs1Nomenclature} from "@barcode_gs1/js/gs1_nomenclature.esm"; + +/** + * Read the GS1 nomenclature once, when the app starts, so the parser — which + * runs synchronously on every scan — has the rules ready. The parser falls back + * to its built-in identifiers if this never completes. + */ +barcodeStartupTasks.add("gs1_nomenclature", (env) => + loadGs1Nomenclature(env.services.orm, env.services.company?.currentCompany?.id) +); diff --git a/barcode_gs1/static/tests/gs1_parser.test.js b/barcode_gs1/static/tests/gs1_parser.test.js new file mode 100644 index 0000000..980231b --- /dev/null +++ b/barcode_gs1/static/tests/gs1_parser.test.js @@ -0,0 +1,605 @@ +/** @odoo-module **/ + +import {afterEach, describe, expect, test} from "@odoo/hoot"; +import {gtinVariants, isGS1Barcode, parseGs1} from "@barcode_gs1/js/gs1_parser.esm"; +import { + compileGs1Nomenclature, + getGs1Nomenclature, + hasValidCheckDigit, + loadGs1Nomenclature, + setGs1Nomenclature, +} from "@barcode_gs1/js/gs1_nomenclature.esm"; +import {parseBarcode} from "@barcode_scanner/js/barcode_parser.esm"; + +// FNC1 (, 0x1D), the separator a scanner sends between variable-length AIs. +const GS = String.fromCharCode(29); +// The characters GS1 allows in an alphanumeric value. +const ALPHA = '[!"%-/0-9:-?A-Z_a-z]'; + +// The GS1 rules Odoo ships in `barcodes_gs1_nomenclature`, trimmed to what +// these tests exercise. +const ODOO_RULES = [ + { + name: "SSCC", + sequence: 1, + pattern: "(00)(\\d{18})", + type: "package", + gs1_content_type: "identifier", + }, + { + name: "GTIN", + sequence: 2, + pattern: "(01)(\\d{14})", + type: "product", + gs1_content_type: "identifier", + }, + { + name: "Physical location GLN", + sequence: 6, + pattern: "(414)(\\d{13})", + type: "location", + gs1_content_type: "identifier", + }, + { + name: "Batch or lot number", + sequence: 10, + pattern: `(10)(${ALPHA}{0,20})`, + type: "lot", + gs1_content_type: "alpha", + }, + { + name: "Serial number", + sequence: 11, + pattern: `(21)(${ALPHA}{0,20})`, + type: "lot", + gs1_content_type: "alpha", + }, + { + name: "Expiration date", + sequence: 15, + pattern: "(17)(\\d{6})", + type: "expiration_date", + gs1_content_type: "date", + }, + { + name: "Variable count of items", + sequence: 20, + pattern: "(30)(\\d{0,8})", + type: "quantity", + gs1_content_type: "measure", + gs1_decimal_usage: false, + }, + { + name: "Net weight, kilograms", + sequence: 21, + pattern: "(310[0-5])(\\d{6})", + type: "quantity", + gs1_content_type: "measure", + gs1_decimal_usage: true, + }, +]; + +const KG = [13, "kg"]; + +function loadNomenclature(rules, separator = "(Alt029|#|\\x1D)") { + setGs1Nomenclature( + compileGs1Nomenclature( + {id: 1, name: "Default GS1 Nomenclature", gs1_separator_fnc1: separator}, + rules + ) + ); +} + +describe("BarcodeGs1", () => { + // The nomenclature is cached for the whole session; each test starts from + // the built-in identifiers unless it loads its own rules. + afterEach(() => setGs1Nomenclature(null)); + + test("a parenthesised barcode decodes the GTIN, the lot and the expiry", () => { + expect(parseGs1("(01)09501101020917(10)LOT123(17)261231")).toMatchObject({ + type: "gs1", + value: "9501101020917", + gtin: "09501101020917", + lot: "LOT123", + expiration: "2026-12-31", + expiry: "2026-12-31", + qty: null, + errors: [], + }); + }); + + test("a raw FNC1-separated barcode decodes the same fields", () => { + expect(parseGs1(`0109501101020917${GS}10LOT123${GS}17261231`)).toMatchObject({ + value: "9501101020917", + lot: "LOT123", + expiry: "2026-12-31", + errors: [], + }); + }); + + test("a variable-length value runs to the end when it is the last element", () => { + // GS1 needs no separator after the last element, and recommends putting + // the variable-length ones there: digits inside the value that look + // like an identifier must not cut it short. + expect(parseGs1("0109501101020917215830192")).toMatchObject({ + serial: "5830192", + lot: "5830192", + count: null, + qty: null, + errors: [], + }); + expect(parseGs1("0109501101020917214711000123")).toMatchObject({ + serial: "4711000123", + productionDate: null, + errors: [], + }); + expect(parseGs1("010950110102091710A3712")).toMatchObject({ + lot: "A3712", + count: null, + qty: null, + errors: [], + }); + expect(parseGs1("01095011010209171020241130")).toMatchObject({ + lot: "20241130", + errors: [], + }); + expect(parseGs1("01095011010209171726123110LOT123")).toMatchObject({ + lot: "LOT123", + expiry: "2026-12-31", + errors: [], + }); + }); + + test("a value too long to be one ends at the next element that reads cleanly", () => { + // Longer than a lot may be, so a separator was dropped: the lot ends + // where a real date starts, and the count after it is read as well. + expect(parseGs1("010950110102091710LOT12345678172612313005")).toMatchObject({ + lot: "LOT12345678", + expiry: "2026-12-31", + count: 5, + qty: 5, + errors: [], + }); + // "17991399" looks like an expiry date but is not one (month 13): the + // lot is not cut there. + expect(parseGs1("010950110102091710AB17991399CD172612313005")).toMatchObject({ + lot: "AB17991399CD", + expiry: "2026-12-31", + count: 5, + errors: [], + }); + }); + + test("a long alphanumeric run without separators is read in linear time", () => { + // Every "10" in the run could open another lot, so finding where each + // value ends looks ahead again and again: without remembering what + // each position matched, this 80-character scan takes about 25 s. + const parsed = parseGs1("]C110" + "A10".repeat(25)); + expect(parsed.lot).toBe("A10A10A10A10A10A10A1"); + expect(parsed.errors).toInclude("Missing GTIN (AI 01)"); + }); + + test("a count (AI 30) is the quantity and a serial (AI 21) doubles as the lot", () => { + expect(parseGs1("(01)09501101020917(21)SN9(30)12")).toMatchObject({ + serial: "SN9", + lot: "SN9", + qty: 12, + quantity: 12, + }); + }); + + test("a net weight (AI 310n) is decoded with its decimals, not as the quantity", () => { + // Whether a weight is the quantity depends on the unit the product is + // stocked in, which the parser does not know: 1.25 kg is not 1.25 units. + expect(parseGs1("(01)09501101020917(3103)001250")).toMatchObject({ + weight: 1.25, + count: null, + qty: null, + quantity: null, + }); + }); + + test("a count next to the weight is the quantity", () => { + expect(parseGs1("(01)09501101020917(3103)001250(30)4")).toMatchObject({ + weight: 1.25, + qty: 4, + }); + }); + + test("the gross weight of the pack never stands for the goods", () => { + // Odoo ships the net weight (310n) with its unit, and no rule for the + // gross weight (330n): the built-in identifier reads it, unitless. + loadNomenclature([ODOO_RULES[1], {...ODOO_RULES[7], associated_uom_id: KG}]); + const net = {ai: "3103", value: 2.497, uom: {id: 13, name: "kg"}}; + const gross = {ai: "3303", value: 2.7, uom: null}; + // Net and gross, in either order: the net weight is the goods'. + for (const label of [ + "(01)09501101020917(3103)002497(3303)002700", + "(01)09501101020917(3303)002700(3103)002497", + ]) { + expect(parseGs1(label)).toMatchObject({ + weight: 2.497, + weightUom: {id: 13, name: "kg"}, + }); + } + expect(parseGs1("(01)09501101020917(3103)002497(3303)002700").measures).toEqual( + [net, gross] + ); + // A gross weight alone is listed, but is no measure of the goods. + expect(parseGs1("(01)09501101020917(3303)002700")).toMatchObject({ + weight: null, + weightUom: null, + measures: [gross], + }); + }); + + test("every measure is listed, the first one with a unit stands for the goods", () => { + loadNomenclature([ + ODOO_RULES[1], + {...ODOO_RULES[7], associated_uom_id: KG}, + { + name: "Net volume, litres", + sequence: 25, + pattern: "(315[0-5])(\\d{6})", + type: "quantity", + gs1_content_type: "measure", + gs1_decimal_usage: true, + associated_uom_id: [11, "L"], + }, + ]); + // A width with no rule (so no unit), a net weight and a net volume. + const parsed = parseGs1( + "(01)09501101020917(3122)000300(3103)002497(3152)000250" + ); + expect(parsed.measures).toEqual([ + {ai: "3122", value: 3, uom: null}, + {ai: "3103", value: 2.497, uom: {id: 13, name: "kg"}}, + {ai: "3152", value: 2.5, uom: {id: 11, name: "L"}}, + ]); + expect(parsed).toMatchObject({weight: 2.497, weightUom: {id: 13, name: "kg"}}); + }); + + test("DD=00 in a date means the last day of the month", () => { + expect(parseGs1("(01)09501101020917(15)261200")).toMatchObject({ + expiry: "2026-12-31", + useDate: "2026-12-31", + errors: [], + }); + }); + + test("an expiration date (17) wins over a best-before date (15)", () => { + expect(parseGs1("(01)09501101020917(15)261200(17)270101")).toMatchObject({ + expiry: "2027-01-01", + useDate: "2026-12-31", + errors: [], + }); + }); + + test("production (11) and pack (13) dates are decoded on their own fields", () => { + expect(parseGs1("(01)09501101020917(11)260115(13)260116")).toMatchObject({ + productionDate: "2026-01-15", + packDate: "2026-01-16", + expiry: null, + errors: [], + }); + }); + + test("an impossible date is reported instead of silently accepted", () => { + const parsed = parseGs1("(01)09501101020917(17)260230"); + expect(parsed.expiry).toBe(null); + expect(parsed.errors).toEqual(["Invalid GS1 date for AI 17"]); + }); + + test("a symbology identifier is stripped before parsing", () => { + expect(parseGs1("]C10109501101020917")).toMatchObject({ + value: "9501101020917", + errors: [], + }); + }); + + test("an SSCC-only label is decoded but reports the missing GTIN", () => { + expect(parseGs1("(00)123456789012345675")).toMatchObject({ + sscc: "123456789012345675", + value: null, + errors: ["Missing GTIN (AI 01)"], + }); + }); + + test("a GLN identifies the physical location it was scanned for", () => { + expect(parseGs1("(414)9501101020917")).toMatchObject({ + location: "9501101020917", + errors: ["Missing GTIN (AI 01)"], + }); + }); + + test("a misread GTIN is refused by its check digit", () => { + // Same barcode as above with the last digit off by one. + expect(parseGs1("(01)09501101020916(10)LOT123")).toMatchObject({ + gtin: null, + value: null, + lot: "LOT123", + errors: ["Invalid GS1 check digit for AI 01"], + }); + }); + + test("a misread SSCC or GLN is refused too", () => { + expect(parseGs1("(00)123456789012345678")).toMatchObject({ + sscc: null, + errors: ["Invalid GS1 check digit for AI 00", "Missing GTIN (AI 01)"], + }); + expect(parseGs1("(414)9501101020916")).toMatchObject({ + location: null, + errors: ["Invalid GS1 check digit for AI 414", "Missing GTIN (AI 01)"], + }); + }); + + test("the check digit is the GS1 modulo 10 of the zero-padded identifier", () => { + expect(hasValidCheckDigit("09501101020917")).toBe(true); + expect(hasValidCheckDigit("09501101020916")).toBe(false); + expect(hasValidCheckDigit("123456789012345675")).toBe(true); + expect(hasValidCheckDigit("123456789012345678")).toBe(false); + }); + + test("the GTIN resolves to the shortest form a product stores", () => { + // GS1 pads the GTIN to 14 digits; products hold the code printed on the + // item, which Odoo stores as an EAN13 (`sanitize_ean`). + expect(gtinVariants("09501101020917")).toEqual([ + "9501101020917", + "09501101020917", + ]); + // A UPC-A: 13 digits first, the shorter forms still offered. + expect(gtinVariants("00012345678905")).toEqual([ + "0012345678905", + "00012345678905", + "012345678905", + "12345678905", + ]); + // A genuine ITF-14 has no padding to strip. + expect(gtinVariants("10012345678902")).toEqual(["10012345678902"]); + }); + + test("only GS1 data is claimed, so other codes reach the base parser", () => { + expect(isGS1Barcode("9501101020917")).toBe(false); + expect(parseGs1("9501101020917")).toBe(null); + // 01... but too short to be anything but an EAN13. + expect(parseGs1("0123456789012")).toBe(null); + expect(isGS1Barcode("(01)09501101020917")).toBe(true); + // An ITF-14 with indicator digit 0 starts with "01" too, but no + // application identifier reads out of it: it is a plain code. + expect(parseGs1("01234567890128")).toBe(null); + // A parenthesis is not an application identifier. + expect(isGS1Barcode("PAL(3)-A")).toBe(false); + expect(parseGs1("PAL(3)-A")).toBe(null); + }); + + test("a parenthesised value its rule does not accept is reported, not read", () => { + expect(parseGs1("(01)09501101020917(30)12abc")).toMatchObject({ + count: null, + qty: null, + errors: ["Invalid GS1 value for AI 30"], + }); + expect( + parseGs1("(01)09501101020917(10)ABCDEFGHIJKLMNOPQRSTUVWXYZ") + ).toMatchObject({lot: null, errors: ["Invalid GS1 value for AI 10"]}); + // A GTIN is always 14 digits. + expect(parseGs1("(01)9501101020917")).toMatchObject({ + gtin: null, + errors: ["Invalid GS1 value for AI 01"], + }); + }); + + test("what cannot be parsed is reported whole", () => { + expect(parseGs1(`0109501101020917${GS}ZZ${GS}YY${GS}XX`).errors).toEqual([ + 'Unparsed GS1 data "ZZYYXX"', + ]); + }); + + test("a nomenclature that cannot be read leaves the built-in identifiers", async () => { + loadNomenclature(ODOO_RULES); + const offline = () => Promise.reject(new Error("offline")); + const orm = {read: offline, searchRead: offline}; + expect(await loadGs1Nomenclature(orm, 1)).toBe(null); + expect(getGs1Nomenclature()).toBe(null); + expect(parseGs1("(01)09501101020917(11)260115")).toMatchObject({ + productionDate: "2026-01-15", + errors: [], + }); + }); + + test("the parser is registered ahead of the built-in EAN13 fallback", () => { + expect(parseBarcode("(01)09501101020917(10)LOT123").type).toBe("gs1"); + expect(parseBarcode("9501101020917").type).toBe("ean13"); + }); + + test("Odoo's own GS1 rules decode the same fields", () => { + loadNomenclature(ODOO_RULES); + expect(parseGs1("(01)09501101020917(10)LOT123(17)261231")).toMatchObject({ + value: "9501101020917", + lot: "LOT123", + expiry: "2026-12-31", + qty: null, + errors: [], + }); + expect(parseGs1(`0109501101020917${GS}10LOT123${GS}17261231`)).toMatchObject({ + value: "9501101020917", + lot: "LOT123", + expiry: "2026-12-31", + errors: [], + }); + expect(parseGs1("01095011010209171726123110LOT123")).toMatchObject({ + value: "9501101020917", + lot: "LOT123", + expiry: "2026-12-31", + errors: [], + }); + expect(parseGs1("(01)09501101020917(3103)001250")).toMatchObject({ + weight: 1.25, + qty: null, + errors: [], + }); + expect(parseGs1("(01)09501101020916")).toMatchObject({ + gtin: null, + errors: ["Invalid GS1 check digit for AI 01"], + }); + }); + + test("the nomenclature's own separator characters are accepted", () => { + // A scanner that cannot emit FNC1 is configured to send "#" instead. + loadNomenclature(ODOO_RULES); + expect(parseGs1("0109501101020917#10LOT123#17261231")).toMatchObject({ + value: "9501101020917", + lot: "LOT123", + expiry: "2026-12-31", + errors: [], + }); + // A code that merely contains one of those characters is not GS1 data. + expect(isGS1Barcode("ABC#123")).toBe(false); + expect(parseGs1("ABC#123")).toBe(null); + }); + + test("an AI the nomenclature does not define still parses", () => { + // Odoo ships no rule for a production date (AI 11): without the + // built-in fallback it would cut the rest of the barcode short. + loadNomenclature(ODOO_RULES); + expect(parseGs1("(01)09501101020917(11)260115(10)LOT9")).toMatchObject({ + productionDate: "2026-01-15", + lot: "LOT9", + errors: [], + }); + expect(parseGs1(`0109501101020917${GS}2012${GS}10LOT9`)).toMatchObject({ + lot: "LOT9", + errors: [], + }); + }); + + test("labels off real pallets decode the same in every form", () => { + // Cured guanciale, 2 pieces of 2.497 kg: (01)(3103)(10)(30)(15). + const guanciale = { + value: "98003948002568", + lot: "534343", + weight: 2.497, + count: 2, + qty: 2, + expiry: "2026-10-06", + errors: [], + }; + expect( + parseGs1("(01)98003948002568(3103)002497(10)534343(30)02(15)261006") + ).toMatchObject(guanciale); + expect( + parseGs1(`0198003948002568310300249710534343${GS}3002${GS}15261006`) + ).toMatchObject(guanciale); + // With the separators dropped there is no telling where the lot ends: + // GS1 reads it to the end. A scanner that cannot send FNC1 is set to + // send the nomenclature's separator instead. + expect( + parseGs1("0198003948002568310300249710534343300215261006") + ).toMatchObject({lot: "534343300215261006", count: null, expiry: null}); + + // Hard cheese, 4.324 kg, no count: the lot closes the barcode. + const cheese = { + value: "98436038190867", + lot: "L0892611", + weight: 4.324, + qty: null, + expiry: "2026-09-26", + errors: [], + }; + expect( + parseGs1("(01)98436038190867(15)260926(3103)004324(10)L0892611") + ).toMatchObject(cheese); + // "L0892611" contains "92", a company-internal identifier: breaking + // there would truncate the lot to "L08". + expect(parseGs1("019843603819086715260926310300432410L0892611")).toMatchObject( + cheese + ); + + // Gorgonzola, weight only on the upper barcode. + expect(parseGs1("(01)98017024009181(3102)000309")).toMatchObject({ + value: "98017024009181", + weight: 3.09, + qty: null, + errors: [], + }); + // ... and the tracking data on a second one, which carries no GTIN. A + // GS1-128 scan announces itself with the "]C1" symbology identifier, + // which is what makes this half a GS1 barcode rather than a plain code. + expect(parseGs1("]C115260613" + "1026104005" + GS + "37002")).toMatchObject({ + lot: "26104005", + count: 2, + expiry: "2026-06-13", + errors: ["Missing GTIN (AI 01)"], + }); + expect(isGS1Barcode("]C1152606131026104005")).toBe(true); + }); + + test("an amount payable (AI 39xn) is decoded, with its currency", () => { + expect(parseGs1("(01)09501101020917(3922)000150")).toMatchObject({ + price: 1.5, + currency: null, + errors: [], + }); + // AI 391n and 393n open with the ISO 4217 numeric code (978 = EUR). + expect(parseGs1("(01)09501101020917(3932)978000150")).toMatchObject({ + price: 1.5, + currency: "978", + errors: [], + }); + expect(parseGs1("01095011010209173922000150")).toMatchObject({ + price: 1.5, + errors: [], + }); + }); + + test("a rule configured as a weighted product is a measure, not the quantity", () => { + loadNomenclature( + [ + ODOO_RULES[1], + { + name: "Net weight", + sequence: 2, + pattern: "(310[0-5])(\\d{6})", + type: "weight", + gs1_content_type: "measure", + gs1_decimal_usage: true, + }, + ODOO_RULES[6], + ], + false + ); + expect(parseGs1("(01)09501101020917(3103)001250")).toMatchObject({ + weight: 1.25, + qty: null, + quantity: null, + errors: [], + }); + // A counted quantity is the quantity. + expect(parseGs1("(01)09501101020917(3103)001250(30)4")).toMatchObject({ + weight: 1.25, + qty: 4, + errors: [], + }); + }); + + test("a rule configured in Odoo wins over the built-in identifier", () => { + // AI 91 is company-internal: here it is configured to carry the lot. + loadNomenclature( + [ + ODOO_RULES[1], + { + name: "Internal lot", + sequence: 2, + pattern: "(91)([A-Z0-9]{0,10})", + type: "lot", + gs1_content_type: "alpha", + }, + ], + false + ); + expect(parseGs1("(01)09501101020917(91)ABC123")).toMatchObject({ + value: "9501101020917", + lot: "ABC123", + errors: [], + }); + }); +}); diff --git a/barcode_gs1/tests/__init__.py b/barcode_gs1/tests/__init__.py new file mode 100644 index 0000000..273fbf4 --- /dev/null +++ b/barcode_gs1/tests/__init__.py @@ -0,0 +1 @@ +from . import test_gs1 diff --git a/barcode_gs1/tests/test_gs1.py b/barcode_gs1/tests/test_gs1.py new file mode 100644 index 0000000..b25758e --- /dev/null +++ b/barcode_gs1/tests/test_gs1.py @@ -0,0 +1,70 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.tests.common import HttpCase, TransactionCase, new_test_user, tagged + + +class TestBarcodeGs1UserAccess(TransactionCase): + """The app reads the GS1 rules as whoever opens it. + + The Scanner menu is open to every internal user, so a plain employee must be + able to read everything ``gs1_nomenclature.esm.js`` loads, with the same + fields it asks for. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.employee = new_test_user( + cls.env, login="barcode_gs1_employee", groups="base.group_user" + ) + + def test_employee_reads_the_gs1_nomenclature_and_rules(self): + env = self.env(user=self.employee) + company = env.company.read(["nomenclature_id"]) + self.assertIn("nomenclature_id", company[0]) + nomenclatures = env["barcode.nomenclature"].search_read( + [("is_gs1_nomenclature", "=", True)], + ["name", "is_gs1_nomenclature", "gs1_separator_fnc1"], + limit=1, + ) + self.assertTrue(nomenclatures) + rules = env["barcode.rule"].search_read( + [ + ("barcode_nomenclature_id", "=", nomenclatures[0]["id"]), + ("encoding", "=", "gs1-128"), + ], + [ + "name", + "sequence", + "type", + "pattern", + "gs1_content_type", + "gs1_decimal_usage", + "associated_uom_id", + ], + order="sequence", + ) + self.assertTrue(rules) + # The unit a measure rule is expressed in is read through the rule. + self.assertTrue(any(rule["associated_uom_id"] for rule in rules)) + + +@tagged("post_install", "-at_install") +class TestBarcodeGs1Hoot(HttpCase): + """Run the GS1 parser unit tests (``static/tests``) in the browser. + + The parsing itself is JS, so that suite is where it is actually covered. A + Chrome/Chromium binary is required: without one the run is skipped, not + passed. + """ + + def test_js(self): + self.browser_js( + "/web/tests?headless&loglevel=2&preset=desktop&filter=BarcodeGs1", + "", + "", + login="admin", + success_signal="[HOOT] Test suite succeeded", + error_checker=lambda message: "[HOOT]" not in message, + )