From 06792a4a383fc38105befe9b290454815330c3cc Mon Sep 17 00:00:00 2001 From: Antonio David Ruban Date: Fri, 6 Nov 2026 00:33:35 -0400 Subject: [PATCH] [ADD] barcode_stock_unexpected_product --- barcode_stock_unexpected_product/README.rst | 123 +++++ barcode_stock_unexpected_product/__init__.py | 1 + .../__manifest__.py | 27 + .../models/__init__.py | 4 + .../models/stock_move.py | 13 + .../models/stock_move_line.py | 35 ++ .../models/stock_picking.py | 174 +++++++ .../models/stock_picking_type.py | 16 + .../pyproject.toml | 3 + .../readme/CONTRIBUTORS.md | 1 + .../readme/DESCRIPTION.md | 16 + .../readme/USAGE.md | 16 + .../static/description/index.html | 462 ++++++++++++++++++ .../components/picking_move_list_patch.esm.js | 24 + .../js/screens/picking_screen_patch.esm.js | 117 +++++ .../product_selector_screen_patch.esm.js | 150 ++++++ .../barcode_scanner_state_patch.esm.js | 52 ++ .../barcode_stock_unexpected_product.scss | 5 + ...ode_stock_unexpected_product_templates.xml | 112 +++++ .../static/tests/manual_line.test.js | 202 ++++++++ .../tests/__init__.py | 9 + .../tests/test_js.py | 23 + .../tests/test_manual_line_authorization.py | 97 ++++ .../tests/test_manual_line_availability.py | 66 +++ .../tests/test_manual_line_guards.py | 229 +++++++++ .../tests/test_manual_line_pending.py | 72 +++ .../tests/test_manual_line_regression.py | 14 + .../tests/test_manual_line_tracking.py | 191 ++++++++ .../tests/test_stock_picking_type.py | 66 +++ .../tests/test_stock_picking_type_view.py | 38 ++ .../views/stock_picking_type_views.xml | 17 + 31 files changed, 2375 insertions(+) create mode 100644 barcode_stock_unexpected_product/README.rst create mode 100644 barcode_stock_unexpected_product/__init__.py create mode 100644 barcode_stock_unexpected_product/__manifest__.py create mode 100644 barcode_stock_unexpected_product/models/__init__.py create mode 100644 barcode_stock_unexpected_product/models/stock_move.py create mode 100644 barcode_stock_unexpected_product/models/stock_move_line.py create mode 100644 barcode_stock_unexpected_product/models/stock_picking.py create mode 100644 barcode_stock_unexpected_product/models/stock_picking_type.py create mode 100644 barcode_stock_unexpected_product/pyproject.toml create mode 100644 barcode_stock_unexpected_product/readme/CONTRIBUTORS.md create mode 100644 barcode_stock_unexpected_product/readme/DESCRIPTION.md create mode 100644 barcode_stock_unexpected_product/readme/USAGE.md create mode 100644 barcode_stock_unexpected_product/static/description/index.html create mode 100644 barcode_stock_unexpected_product/static/src/js/components/picking_move_list_patch.esm.js create mode 100644 barcode_stock_unexpected_product/static/src/js/screens/picking_screen_patch.esm.js create mode 100644 barcode_stock_unexpected_product/static/src/js/screens/product_selector_screen_patch.esm.js create mode 100644 barcode_stock_unexpected_product/static/src/js/services/barcode_scanner_state_patch.esm.js create mode 100644 barcode_stock_unexpected_product/static/src/scss/barcode_stock_unexpected_product.scss create mode 100644 barcode_stock_unexpected_product/static/src/xml/barcode_stock_unexpected_product_templates.xml create mode 100644 barcode_stock_unexpected_product/static/tests/manual_line.test.js create mode 100644 barcode_stock_unexpected_product/tests/__init__.py create mode 100644 barcode_stock_unexpected_product/tests/test_js.py create mode 100644 barcode_stock_unexpected_product/tests/test_manual_line_authorization.py create mode 100644 barcode_stock_unexpected_product/tests/test_manual_line_availability.py create mode 100644 barcode_stock_unexpected_product/tests/test_manual_line_guards.py create mode 100644 barcode_stock_unexpected_product/tests/test_manual_line_pending.py create mode 100644 barcode_stock_unexpected_product/tests/test_manual_line_regression.py create mode 100644 barcode_stock_unexpected_product/tests/test_manual_line_tracking.py create mode 100644 barcode_stock_unexpected_product/tests/test_stock_picking_type.py create mode 100644 barcode_stock_unexpected_product/tests/test_stock_picking_type_view.py create mode 100644 barcode_stock_unexpected_product/views/stock_picking_type_views.xml diff --git a/barcode_stock_unexpected_product/README.rst b/barcode_stock_unexpected_product/README.rst new file mode 100644 index 0000000..21e6ae5 --- /dev/null +++ b/barcode_stock_unexpected_product/README.rst @@ -0,0 +1,123 @@ +.. image:: https://odoo-community.org/readme-banner-image + :target: https://odoo-community.org/get-involved?utm_source=readme + :alt: Odoo Community Association + +================================ +Barcode Stock Unexpected Product +================================ + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:6b894cd33153bc988046a1ec6bcea502d79953332a015b109155e94f7657b5df + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |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/18.0/barcode_stock_unexpected_product + :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-18-0/barcode-interface-18-0-barcode_stock_unexpected_product + :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=18.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +Let the warehouse app add a product to a transfer by scanning it, even +when that product is not one of the transfer's planned move lines. + +By default the scanner only accepts products already expected on the +operation. This module lifts that limit — per operation type — so an +operator scanning an unlisted product adds a new line for it on the +spot, instead of being told the barcode is not part of the operation. + +This is a feature module on top of ``barcode_stock``: it patches the +warehouse scan screens to allow the extra line and gates the behaviour +behind a setting on the operation type, so you enable it only where you +want it. + +The setting only applies to transfers that already have planned lines. +Creating an internal transfer from scratch with the scanner is +unchanged: in that screen every line is new by design. + +**Table of contents** + +.. contents:: + :local: + +Usage +===== + +Enable it per operation type: + +1. Go to **Inventory ▸ Configuration ▸ Operations Types** and open the + type you want (receipts, internal transfers, …). +2. On the **Barcode** tab, tick **Allow Adding New Product Lines from + the Scanner**. + +From then on, scanning a product that is not among the operation's +planned lines adds a new line for it, instead of rejecting the scan. +Where the setting is left off, the scanner keeps refusing products that +are not part of the operation, exactly as before. + +The setting only gates adding unexpected products to a transfer that +already has planned lines. Creating an internal transfer from scratch +with the scanner keeps working exactly as before, whichever value the +setting has. + +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 `__ + +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-antoniodavid| image:: https://github.com/antoniodavid.png?size=40px + :target: https://github.com/antoniodavid + :alt: antoniodavid + +Current `maintainer `__: + +|maintainer-antoniodavid| + +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_stock_unexpected_product/__init__.py b/barcode_stock_unexpected_product/__init__.py new file mode 100644 index 0000000..0650744 --- /dev/null +++ b/barcode_stock_unexpected_product/__init__.py @@ -0,0 +1 @@ +from . import models diff --git a/barcode_stock_unexpected_product/__manifest__.py b/barcode_stock_unexpected_product/__manifest__.py new file mode 100644 index 0000000..a847c7a --- /dev/null +++ b/barcode_stock_unexpected_product/__manifest__.py @@ -0,0 +1,27 @@ +{ + "name": "Barcode Stock Unexpected Product", + "version": "18.0.1.1.0", + "category": "Inventory/Logistics", + "summary": "Allow adding unexpected products to transfers via scanner", + "author": "Binhex, Odoo Community Association (OCA)", + "website": "https://github.com/OCA/barcode-interface", + "maintainers": ["antoniodavid"], + "license": "AGPL-3", + "depends": ["barcode_stock"], + "data": ["views/stock_picking_type_views.xml"], + "assets": { + "web.assets_backend": [ + "barcode_stock_unexpected_product/static/src/scss/barcode_stock_unexpected_product.scss", + "barcode_stock_unexpected_product/static/src/js/services/barcode_scanner_state_patch.esm.js", + "barcode_stock_unexpected_product/static/src/js/components/picking_move_list_patch.esm.js", + "barcode_stock_unexpected_product/static/src/js/screens/picking_screen_patch.esm.js", + "barcode_stock_unexpected_product/static/src/js/screens/product_selector_screen_patch.esm.js", + "barcode_stock_unexpected_product/static/src/xml/barcode_stock_unexpected_product_templates.xml", + ], + "web.assets_unit_tests": [ + "barcode_stock_unexpected_product/static/tests/manual_line.test.js", + ], + }, + "installable": True, + "auto_install": False, +} diff --git a/barcode_stock_unexpected_product/models/__init__.py b/barcode_stock_unexpected_product/models/__init__.py new file mode 100644 index 0000000..ab9230a --- /dev/null +++ b/barcode_stock_unexpected_product/models/__init__.py @@ -0,0 +1,4 @@ +from . import stock_picking_type +from . import stock_move +from . import stock_move_line +from . import stock_picking diff --git a/barcode_stock_unexpected_product/models/stock_move.py b/barcode_stock_unexpected_product/models/stock_move.py new file mode 100644 index 0000000..5bc6fe3 --- /dev/null +++ b/barcode_stock_unexpected_product/models/stock_move.py @@ -0,0 +1,13 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import fields, models + + +class StockMove(models.Model): + _inherit = "stock.move" + + is_manually = fields.Boolean( + string="Manually Added", + help="Technical flag for moves added via scanner.", + ) diff --git a/barcode_stock_unexpected_product/models/stock_move_line.py b/barcode_stock_unexpected_product/models/stock_move_line.py new file mode 100644 index 0000000..887cfd5 --- /dev/null +++ b/barcode_stock_unexpected_product/models/stock_move_line.py @@ -0,0 +1,35 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import api, fields, models + + +class StockMoveLine(models.Model): + _inherit = "stock.move.line" + + is_manually = fields.Boolean( + related="move_id.is_manually", store=False, readonly=True + ) + + @api.model_create_multi + def create(self, vals_list): + lines = super().create(vals_list) + lines._barcode_scanner_sync_manual_move_quantity() + return lines + + def write(self, vals): + res = super().write(vals) + if "quantity" in vals or "qty_picked" in vals: + self._barcode_scanner_sync_manual_move_quantity() + return res + + def _barcode_scanner_sync_manual_move_quantity(self): + for line in self: + move = line.move_id + if not move.is_manually: + continue + total = sum(move.move_line_ids.mapped("quantity")) or sum( + move.move_line_ids.mapped("qty_picked") + ) + if total and move.product_uom_qty != total: + move.product_uom_qty = total diff --git a/barcode_stock_unexpected_product/models/stock_picking.py b/barcode_stock_unexpected_product/models/stock_picking.py new file mode 100644 index 0000000..b06752f --- /dev/null +++ b/barcode_stock_unexpected_product/models/stock_picking.py @@ -0,0 +1,174 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import api, models +from odoo.exceptions import UserError + + +class StockPicking(models.Model): + _inherit = "stock.picking" + + @api.model + def _barcode_scanner_resolve_manual_line_lot(self, lot_id): + if not lot_id: + return False + try: + lot_id = int(lot_id) + except (TypeError, ValueError): + raise UserError(self.env._("The selected lot is not valid.")) from None + lot = self.env["stock.lot"].browse(lot_id).exists() + if not lot: + raise UserError(self.env._("The selected lot is not valid.")) + return lot + + @api.model + def barcode_scanner_add_manual_line_to_picking( + self, picking_id, product_id, quantity, lot_id=False, auto_pick=False + ): + """Create or reserve pending demand from the PickingScreen.""" + picking = self.browse(picking_id).exists() + if not picking: + raise UserError(self.env._("The picking no longer exists.")) + if picking.state in ("done", "cancel"): + raise UserError(self.env._("This picking can no longer be changed.")) + picking_type = picking.picking_type_id + if picking_type.code != "internal" or not picking_type.allow_insert_new_line: + raise UserError( + self.env._( + "Adding a new product line from the scanner is not allowed " + "for this operation type." + ) + ) + + product = self.env["product.product"].browse(product_id).exists() + if not product: + raise UserError( + self.env._("One of the selected products no longer exists.") + ) + qty = float(quantity or 0) + if qty <= 0: + raise UserError( + self.env._( + "Quantity must be greater than zero for product %(name)s.", + name=product.display_name, + ) + ) + + source = picking.location_id or picking.move_ids[:1].location_id + destination = picking.location_dest_id or picking.move_ids[:1].location_dest_id + source = source or picking_type.default_location_src_id + destination = destination or picking_type.default_location_dest_id + + # Serialize additions to this picking so the manual-move lookup and + # subsequent create-or-merge of a move cannot race. + self.env.cr.execute( + "SELECT id FROM stock_picking WHERE id = %s FOR UPDATE", (picking.id,) + ) + + lot = self._barcode_scanner_resolve_manual_line_lot(lot_id) + if product.tracking != "none" and not lot: + raise UserError( + self.env._("A valid lot or serial number is required for this product.") + ) + if lot and lot.product_id != product: + raise UserError( + self.env._("The selected lot is not valid for this product.") + ) + if lot and lot.company_id and lot.company_id != picking.company_id: + raise UserError( + self.env._("The selected lot is not valid for this company.") + ) + if product.tracking == "serial" and qty != 1: + raise UserError( + self.env._("A serial-tracked product must be added one unit per line.") + ) + if product.tracking == "none": + lot = False + + available = self.env["stock.quant"]._get_available_quantity( + product, source, lot_id=lot or None, strict=False + ) + if available < qty: + raise UserError( + self.env._( + "There is not enough available stock for product %(name)s.", + name=product.display_name, + ) + ) + + Move = self.env["stock.move"] + move = Move.search( + [ + ("picking_id", "=", picking.id), + ("product_id", "=", product.id), + ("is_manually", "=", True), + ("picked", "=", False), + ], + limit=1, + ) + if move: + move.product_uom_qty += qty + else: + move = Move.create( + { + "name": product.display_name, + "product_id": product.id, + "product_uom_qty": qty, + "product_uom": product.uom_id.id, + "state": "confirmed", + "picking_id": picking.id, + "location_id": source.id, + "location_dest_id": destination.id, + "company_id": picking.company_id.id, + "is_manually": True, + } + ) + + taken = move._update_reserved_quantity( + qty, source, lot_id=lot or None, strict=False + ) + if taken < qty: + raise UserError( + self.env._( + "There is not enough available stock for product %(name)s.", + name=product.display_name, + ) + ) + if auto_pick: + self._barcode_scanner_auto_pick_manual_line(move, product, lot) + return { + "move_id": move.id, + "product_id": product.id, + "quantity": qty, + "name": product.name, + "picked": bool(auto_pick), + } + + def _barcode_scanner_auto_pick_manual_line(self, move, product, lot): + lines = move.move_line_ids.filtered( + lambda line: line.product_id == product and (not lot or line.lot_id == lot) + ) + for line in lines: + line.qty_picked = line.quantity + + @api.model + def barcode_scanner_delete_manual_line(self, move_id): + """Delete a manually added line (is_manually) from the PickingScreen.""" + move = self.env["stock.move"].browse(move_id).exists() + if not move: + raise UserError(self.env._("The move no longer exists.")) + if not move.is_manually: + raise UserError(self.env._("Only manually added lines can be deleted.")) + picking = move.picking_id + if picking.state in ("done", "cancel"): + raise UserError(self.env._("This picking can no longer be changed.")) + if move.state == "done": + raise UserError(self.env._("A completed move cannot be deleted.")) + if move.quantity: + move._do_unreserve() + # Barcode operators have stock.group_stock_user: they may create and + # write moves but cannot unlink them. The checks above already ensured + # this is a manual line on a changeable picking, so elevate only the + # deletion itself. + move.sudo().unlink() + return {"deleted": True, "move_id": move_id} diff --git a/barcode_stock_unexpected_product/models/stock_picking_type.py b/barcode_stock_unexpected_product/models/stock_picking_type.py new file mode 100644 index 0000000..0310d2b --- /dev/null +++ b/barcode_stock_unexpected_product/models/stock_picking_type.py @@ -0,0 +1,16 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import fields, models + + +class StockPickingType(models.Model): + _inherit = "stock.picking.type" + + allow_insert_new_line = fields.Boolean( + string="Allow Adding New Product Lines from the Scanner", + default=False, + help="Allow the Barcode scanner to add a new/unlisted product line to " + "this internal transfer. Incoming and outgoing operation types never " + "allow new lines.", + ) diff --git a/barcode_stock_unexpected_product/pyproject.toml b/barcode_stock_unexpected_product/pyproject.toml new file mode 100644 index 0000000..4231d0c --- /dev/null +++ b/barcode_stock_unexpected_product/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/barcode_stock_unexpected_product/readme/CONTRIBUTORS.md b/barcode_stock_unexpected_product/readme/CONTRIBUTORS.md new file mode 100644 index 0000000..6c13ebb --- /dev/null +++ b/barcode_stock_unexpected_product/readme/CONTRIBUTORS.md @@ -0,0 +1 @@ +* [Antonio David](https://github.com/antoniodavid) diff --git a/barcode_stock_unexpected_product/readme/DESCRIPTION.md b/barcode_stock_unexpected_product/readme/DESCRIPTION.md new file mode 100644 index 0000000..46b874a --- /dev/null +++ b/barcode_stock_unexpected_product/readme/DESCRIPTION.md @@ -0,0 +1,16 @@ +Let the warehouse app add a product to a transfer by scanning it, even +when that product is not one of the transfer's planned move lines. + +By default the scanner only accepts products already expected on the +operation. This module lifts that limit — per operation type — so an +operator scanning an unlisted product adds a new line for it on the spot, +instead of being told the barcode is not part of the operation. + +This is a feature module on top of `barcode_stock`: it patches the +warehouse scan screens to allow the extra line and gates the behaviour +behind a setting on the operation type, so you enable it only where you +want it. + +The setting only applies to transfers that already have planned lines. +Creating an internal transfer from scratch with the scanner is unchanged: +in that screen every line is new by design. diff --git a/barcode_stock_unexpected_product/readme/USAGE.md b/barcode_stock_unexpected_product/readme/USAGE.md new file mode 100644 index 0000000..a3fd3f8 --- /dev/null +++ b/barcode_stock_unexpected_product/readme/USAGE.md @@ -0,0 +1,16 @@ +Enable it per operation type: + +1. Go to **Inventory ▸ Configuration ▸ Operations Types** and open the + type you want (receipts, internal transfers, …). +2. On the **Barcode** tab, tick **Allow Adding New Product Lines from the + Scanner**. + +From then on, scanning a product that is not among the operation's +planned lines adds a new line for it, instead of rejecting the scan. +Where the setting is left off, the scanner keeps refusing products that +are not part of the operation, exactly as before. + +The setting only gates adding unexpected products to a transfer that +already has planned lines. Creating an internal transfer from scratch +with the scanner keeps working exactly as before, whichever value the +setting has. diff --git a/barcode_stock_unexpected_product/static/description/index.html b/barcode_stock_unexpected_product/static/description/index.html new file mode 100644 index 0000000..955896c --- /dev/null +++ b/barcode_stock_unexpected_product/static/description/index.html @@ -0,0 +1,462 @@ + + + + + +Barcode Stock Unexpected Product + + + +
+ + + +Odoo Community Association + +
+

Barcode Stock Unexpected Product

+ +

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

+

Let the warehouse app add a product to a transfer by scanning it, even +when that product is not one of the transfer’s planned move lines.

+

By default the scanner only accepts products already expected on the +operation. This module lifts that limit — per operation type — so an +operator scanning an unlisted product adds a new line for it on the +spot, instead of being told the barcode is not part of the operation.

+

This is a feature module on top of barcode_stock: it patches the +warehouse scan screens to allow the extra line and gates the behaviour +behind a setting on the operation type, so you enable it only where you +want it.

+

The setting only applies to transfers that already have planned lines. +Creating an internal transfer from scratch with the scanner is +unchanged: in that screen every line is new by design.

+

Table of contents

+ +
+

Usage

+

Enable it per operation type:

+
    +
  1. Go to Inventory ▸ Configuration ▸ Operations Types and open the +type you want (receipts, internal transfers, …).
  2. +
  3. On the Barcode tab, tick Allow Adding New Product Lines from +the Scanner.
  4. +
+

From then on, scanning a product that is not among the operation’s +planned lines adds a new line for it, instead of rejecting the scan. +Where the setting is left off, the scanner keeps refusing products that +are not part of the operation, exactly as before.

+

The setting only gates adding unexpected products to a transfer that +already has planned lines. Creating an internal transfer from scratch +with the scanner keeps working exactly as before, whichever value the +setting has.

+
+
+

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:

+

antoniodavid

+

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_stock_unexpected_product/static/src/js/components/picking_move_list_patch.esm.js b/barcode_stock_unexpected_product/static/src/js/components/picking_move_list_patch.esm.js new file mode 100644 index 0000000..4ced95d --- /dev/null +++ b/barcode_stock_unexpected_product/static/src/js/components/picking_move_list_patch.esm.js @@ -0,0 +1,24 @@ +import {PickingDoneCard} from "@barcode_stock/js/components/picking_done_card.esm"; +import {PickingDoneList} from "@barcode_stock/js/components/picking_done_list.esm"; +import {PickingMoveCard} from "@barcode_stock/js/components/picking_move_card.esm"; +import {PickingMoveList} from "@barcode_stock/js/components/picking_move_list.esm"; + +PickingMoveList.props = { + ...PickingMoveList.props, + onDeleteManual: {type: Function, optional: true}, +}; + +PickingMoveCard.props = { + ...PickingMoveCard.props, + onDeleteManual: {type: Function, optional: true}, +}; + +PickingDoneList.props = { + ...PickingDoneList.props, + onDeleteManual: {type: Function, optional: true}, +}; + +PickingDoneCard.props = { + ...PickingDoneCard.props, + onDeleteManual: {type: Function, optional: true}, +}; diff --git a/barcode_stock_unexpected_product/static/src/js/screens/picking_screen_patch.esm.js b/barcode_stock_unexpected_product/static/src/js/screens/picking_screen_patch.esm.js new file mode 100644 index 0000000..356c2f2 --- /dev/null +++ b/barcode_stock_unexpected_product/static/src/js/screens/picking_screen_patch.esm.js @@ -0,0 +1,117 @@ +import {ConfirmationDialog} from "@web/core/confirmation_dialog/confirmation_dialog"; +import {PickingScreen} from "@barcode_stock/js/screens/picking_screen.esm"; +import {_t} from "@web/core/l10n/translation"; +import {barcodeMatchDomain} from "@barcode_scanner/js/utils/scan_match.esm"; +import {patch} from "@web/core/utils/patch"; + +export function isManualLineEligible(pickingTypeCode, allowInsertNewLine) { + return pickingTypeCode === "internal" && Boolean(allowInsertNewLine); +} + +patch(PickingScreen.prototype, { + get canAddManualLine() { + return isManualLineEligible( + this.state.pickingTypeCode, + this.state.pickingTypeAllowInsertNewLine + ); + }, + + async loadData() { + await super.loadData(...arguments); + const snapshot = this.barcodeScannerState.getSnapshot(); + this.state.pickingTypeAllowInsertNewLine = + snapshot.pickingTypeAllowInsertNewLine || false; + }, + + openManualLineSelector() { + this.store.navigate("product_selector", { + mode: "manual_line", + pickingId: this.pickingId, + pickingTypeCode: this.state.pickingTypeCode, + listParams: this.listParams, + reloadToken: Date.now(), + }); + }, + + deleteManualMove(moveId) { + this.dialog.add(ConfirmationDialog, { + title: _t("Confirm deletion"), + body: _t("Are you sure you want to delete this manually added line?"), + confirm: async () => { + try { + await this.inventory.call( + "stock.picking", + "barcode_scanner_delete_manual_line", + [moveId] + ); + this.inventory.notify(_t("Manual line deleted."), { + type: "success", + }); + await this._reloadMoves(); + } catch { + // Shared api service already showed the failure to the operator. + } + }, + }); + }, + + async handleBarcode(barcode, parsedData = null, payload = {}) { + const normalized = this.barcodeScannerState.applyScanResult({ + barcode, + ...(parsedData || {}), + }); + const source = payload?.source || "hardware"; + if (!normalized.candidates.length) { + // Ponytail: also match default_code (user scans internal reference) + const productDomain = barcodeMatchDomain(normalized.product); + let products = productDomain + ? await this.inventory.searchRead("product.product", productDomain, [ + "display_name", + "tracking", + ]) + : []; + if (!products.length) { + const altDomain = barcodeMatchDomain( + normalized.product, + "default_code" + ); + products = altDomain + ? await this.inventory.searchRead("product.product", altDomain, [ + "display_name", + "tracking", + ]) + : []; + } + if (!products.length || !this.state.picking?.id || !this.canAddManualLine) { + this.setLastScanContext({ + barcode, + source, + tone: "warning", + message: _t("Scanned barcode is not part of the current picking."), + }); + this.feedback.warning({ + notify: true, + message: _t("Scanned barcode is not part of the current picking."), + }); + return; + } + const product = products[0]; + // UX: open the selector pre-searched with the scanned product + // so the operator sets the demand quantity (picked auto-fills). + this.store.navigate("product_selector", { + mode: "manual_line", + pickingId: this.pickingId, + pickingTypeCode: this.state.pickingTypeCode, + listParams: this.listParams, + reloadToken: Date.now(), + preselectProduct: product.id, + preselectBarcode: barcode, + scannedQuantity: normalized.quantity, + scannedLotName: normalized.lotName, + autoPick: true, + }); + return; + } + return super.handleBarcode(...arguments); + }, +}); diff --git a/barcode_stock_unexpected_product/static/src/js/screens/product_selector_screen_patch.esm.js b/barcode_stock_unexpected_product/static/src/js/screens/product_selector_screen_patch.esm.js new file mode 100644 index 0000000..b8e59e4 --- /dev/null +++ b/barcode_stock_unexpected_product/static/src/js/screens/product_selector_screen_patch.esm.js @@ -0,0 +1,150 @@ +import {ProductSelectorScreen} from "@barcode_stock/js/screens/product_selector_screen.esm"; +import {_t} from "@web/core/l10n/translation"; +import {patch} from "@web/core/utils/patch"; +import {recordImageUrl} from "@barcode_stock/js/utils/avatar.esm"; + +export function matchesProductSearch(product, search) { + const value = String(search || "").toLowerCase(); + return [product.name, product.default_code, product.barcode].some((field) => + String(field || "") + .toLowerCase() + .includes(value) + ); +} + +export function getManualLineInitialQuantity(params) { + const quantity = Number.parseFloat(params?.scannedQuantity); + return Number.isFinite(quantity) && quantity > 0 ? quantity : 1; +} + +export function lotIdForName(lots, lotName) { + const name = String(lotName || "").trim(); + if (!name) { + return false; + } + const lot = (lots || []).find( + (candidate) => String(candidate.name || "").trim() === name + ); + return lot ? String(lot.id) : false; +} + +patch(ProductSelectorScreen.prototype, { + setup() { + super.setup(...arguments); + this.state.lots = []; + this.state.lotId = false; + if (this.props.params?.mode === "manual_line") { + this.state.qty = getManualLineInitialQuantity(this.props.params); + } + }, + + async loadProducts() { + if (this.props.params?.mode !== "manual_line") { + return super.loadProducts(...arguments); + } + let products = await this.inventory.searchRead( + "product.product", + [["is_storable", "=", true]], + [ + "name", + "image_128", + "standard_price", + "tracking", + "default_code", + "barcode", + "type", + "write_date", + ], + {context: {bin_size: true}} + ); + products = products.map((product) => { + product.image_url = recordImageUrl("product.product", product); + return product; + }); + this.state.products = products; + this.state.loading = false; + const preselectId = this.props.params?.preselectProduct; + if (preselectId) { + const product = this.state.products.find((p) => p.id === preselectId); + if (product) { + this.state.selectedProduct = product; + this.state.search = product.name || ""; + this.state.lotId = false; + this.state.lots = []; + if (product.tracking !== "none") { + this.state.lots = await this.inventory.searchRead( + "stock.lot", + [["product_id", "=", product.id]], + ["id", "name"] + ); + } + this.state.lotId = lotIdForName( + this.state.lots, + this.props.params?.scannedLotName + ); + } + } + }, + + get filteredProducts() { + if (this.props.params?.mode !== "manual_line") { + return super.filteredProducts; + } + if (!this.state.search) { + return this.state.products; + } + return this.state.products.filter((product) => + matchesProductSearch(product, this.state.search) + ); + }, + + async selectProduct(product) { + super.selectProduct(product); + this.state.lotId = false; + this.state.lots = []; + if (this.props.params?.mode === "manual_line" && product.tracking !== "none") { + this.state.lots = await this.inventory.searchRead( + "stock.lot", + [["product_id", "=", product.id]], + ["id", "name"] + ); + } + }, + + async confirmSelection() { + if (this.props.params?.mode !== "manual_line") { + return super.confirmSelection(...arguments); + } + const product = this.state.selectedProduct; + if (!product) { + return; + } + const qty = Number.parseFloat(this.state.qty) || 1; + const lotId = Number.parseInt(this.state.lotId, 10) || false; + try { + const result = await this.inventory.call( + "stock.picking", + "barcode_scanner_add_manual_line_to_picking", + [ + this.props.params.pickingId, + product.id, + qty, + lotId, + this.props.params.autoPick || false, + ] + ); + this.inventory.notify(_t("Product added as pending demand."), { + type: "success", + }); + // Hand the move back so the picking screen reloads and opens on + // the tab that now holds it (same pattern as move_wizard_screen). + this.store.goBack({ + ...this.props.params, + reloadToken: Date.now(), + focusMoveId: result.move_id, + }); + } catch { + // The shared api service already showed the failure to the operator. + } + }, +}); diff --git a/barcode_stock_unexpected_product/static/src/js/services/barcode_scanner_state_patch.esm.js b/barcode_stock_unexpected_product/static/src/js/services/barcode_scanner_state_patch.esm.js new file mode 100644 index 0000000..64292e8 --- /dev/null +++ b/barcode_stock_unexpected_product/static/src/js/services/barcode_scanner_state_patch.esm.js @@ -0,0 +1,52 @@ +import {BarcodeScannerState} from "@barcode_stock/js/services/barcode_scanner_state.esm"; +import {patch} from "@web/core/utils/patch"; + +patch(BarcodeScannerState.prototype, { + async _loadIsManually(records, model) { + if (!records.length || records[0].is_manually !== undefined) { + return; + } + try { + const ids = records.map((record) => record.id); + const extra = await this.orm.searchRead( + model, + [["id", "in", ids]], + ["is_manually"] + ); + const map = Object.fromEntries( + extra.map((record) => [record.id, record.is_manually]) + ); + for (const record of records) { + record.is_manually = map[record.id] || false; + } + } catch { + // Ignore - fallback to main barcodes + } + }, + + async preloadPicking() { + const result = await super.preloadPicking(...arguments); + await this._loadIsManually(this.moves, "stock.move"); + await this._loadIsManually(this.moveLines, "stock.move.line"); + const pickingTypeId = this.picking?.picking_type_id?.[0]; + if (pickingTypeId) { + const [pickingType] = await this.orm.read( + "stock.picking.type", + [pickingTypeId], + ["allow_insert_new_line"] + ); + this.pickingTypeAllowInsertNewLine = + pickingType?.allow_insert_new_line || false; + } else { + this.pickingTypeAllowInsertNewLine = false; + } + return result; + }, + + getSnapshot() { + return { + ...super.getSnapshot(...arguments), + pickingTypeAllowInsertNewLine: this.pickingTypeAllowInsertNewLine || false, + }; + }, +}); diff --git a/barcode_stock_unexpected_product/static/src/scss/barcode_stock_unexpected_product.scss b/barcode_stock_unexpected_product/static/src/scss/barcode_stock_unexpected_product.scss new file mode 100644 index 0000000..a109f83 --- /dev/null +++ b/barcode_stock_unexpected_product/static/src/scss/barcode_stock_unexpected_product.scss @@ -0,0 +1,5 @@ +.ilx-manual-delete-btn { + cursor: pointer; + color: #d32f2f; + font-size: 1rem; +} diff --git a/barcode_stock_unexpected_product/static/src/xml/barcode_stock_unexpected_product_templates.xml b/barcode_stock_unexpected_product/static/src/xml/barcode_stock_unexpected_product_templates.xml new file mode 100644 index 0000000..e5429fc --- /dev/null +++ b/barcode_stock_unexpected_product/static/src/xml/barcode_stock_unexpected_product_templates.xml @@ -0,0 +1,112 @@ + + + + + + + + + +
+ + +
+
+
+ + + + (moveId) => this.deleteManualMove(moveId) + + + (moveId) => this.deleteManualMove(moveId) + + + + + props.onDeleteManual + + + + + props.onDeleteManual + + + + + + + + + + + + + () => props.line.is_manually + ? props.onDeleteManual?.(props.line.move_id[0]) + : props.onDelete(props.line.id) + + + props.line.is_manually + ? (props.onDeleteManual ? 'Delete manually added line' : 'Manually added line') + : false + + + + + + Tap to delete this manual line + Manually added line + + Tap to remove this confirmation + + + + + + + + +
diff --git a/barcode_stock_unexpected_product/static/tests/manual_line.test.js b/barcode_stock_unexpected_product/static/tests/manual_line.test.js new file mode 100644 index 0000000..cb49101 --- /dev/null +++ b/barcode_stock_unexpected_product/static/tests/manual_line.test.js @@ -0,0 +1,202 @@ +import {describe, expect, test} from "@odoo/hoot"; +import { + getManualLineInitialQuantity, + lotIdForName, + matchesProductSearch, +} from "@barcode_stock_unexpected_product/js/screens/product_selector_screen_patch.esm"; +import {PickingScreen} from "@barcode_stock/js/screens/picking_screen.esm"; +import {ProductSelectorScreen} from "@barcode_stock/js/screens/product_selector_screen.esm"; +import {isManualLineEligible} from "@barcode_stock_unexpected_product/js/screens/picking_screen_patch.esm"; + +describe("BarcodeStockUnexpectedProduct", () => { + test("manual line search matches name, internal reference, and barcode", () => { + const product = {name: "Widget", default_code: "W-01", barcode: "12345"}; + expect(matchesProductSearch(product, "widget")).toBe(true); + expect(matchesProductSearch(product, "w-01")).toBe(true); + expect(matchesProductSearch(product, "12345")).toBe(true); + expect(matchesProductSearch(product, "missing")).toBe(false); + }); + + test("manual line eligibility is restricted to permitted internal transfers", () => { + expect(isManualLineEligible("internal", true)).toBe(true); + expect(isManualLineEligible("incoming", true)).toBe(false); + expect(isManualLineEligible("outgoing", true)).toBe(false); + expect(isManualLineEligible("internal", false)).toBe(false); + }); + + test("manual selection calls the pending-demand RPC and reloads the picking", async () => { + const calls = []; + const backs = []; + const mock = { + props: {params: {mode: "manual_line", pickingId: 7, reloadToken: 9}}, + state: {selectedProduct: {id: 11}, qty: 2.5, lotId: "13"}, + inventory: { + call: async (...args) => { + calls.push(args); + return {move_id: 42}; + }, + notify: () => undefined, + }, + store: {goBack: (params) => backs.push(params)}, + }; + await ProductSelectorScreen.prototype.confirmSelection.call(mock); + expect(calls).toEqual([ + [ + "stock.picking", + "barcode_scanner_add_manual_line_to_picking", + [7, 11, 2.5, 13, false], + ], + ]); + expect(backs[0].focusMoveId).toBe(42); + expect(backs[0].added).toBe(undefined); + }); + + test("unlisted GS1 product passes normalized quantity and lot to the selector", async () => { + const navigations = []; + const searches = []; + const screen = Object.assign(Object.create(PickingScreen.prototype), { + props: {pickingId: 7, listParams: {activeTab: "todo"}}, + state: { + picking: {id: 7}, + pickingTypeCode: "internal", + pickingTypeAllowInsertNewLine: true, + }, + barcodeScannerState: { + applyScanResult: (scan) => { + expect(scan.quantity).toBe(2.5); + expect(scan.lot).toBe("LOT-GS1"); + return { + candidates: [], + product: "01123456789012", + quantity: 2.5, + lotName: "LOT-GS1", + }; + }, + }, + inventory: { + searchRead: async (model, domain) => { + searches.push([model, domain]); + return [{id: 11, display_name: "Widget"}]; + }, + }, + store: {navigate: (...args) => navigations.push(args)}, + }); + + await PickingScreen.prototype.handleBarcode.call(screen, "GS1-CODE", { + quantity: 2.5, + lot: "LOT-GS1", + }); + + expect(searches[0]).toEqual([ + "product.product", + [["barcode", "=ilike", "01123456789012"]], + ]); + expect(navigations[0][0]).toBe("product_selector"); + expect(navigations[0][1].scannedQuantity).toBe(2.5); + expect(navigations[0][1].scannedLotName).toBe("LOT-GS1"); + expect(navigations[0][1].autoPick).toBe(true); + }); + + test("flag-off unlisted scan keeps the original not-part-of-picking message", async () => { + const messages = []; + let navigations = 0; + const screen = Object.assign(Object.create(PickingScreen.prototype), { + props: {pickingId: 7, listParams: {}}, + state: { + picking: {id: 7}, + pickingTypeCode: "internal", + pickingTypeAllowInsertNewLine: false, + }, + barcodeScannerState: { + applyScanResult: () => ({ + candidates: [], + product: "12345", + quantity: 1, + }), + }, + inventory: { + searchRead: async () => [{id: 11, display_name: "Widget"}], + }, + store: {navigate: () => navigations++}, + setLastScanContext: (context) => + // The translation catalog is not loaded in unit tests, so + // LazyTranslatedString throws when coerced. Compare the source + // term instead. + messages.push(String.prototype.valueOf.call(context.message)), + feedback: {warning: () => undefined}, + }); + + await PickingScreen.prototype.handleBarcode.call(screen, "12345", {}); + + expect(navigations).toBe(0); + expect(messages).toEqual([ + "Scanned barcode is not part of the current picking.", + ]); + }); + + test("manual selector defaults to the GS1 quantity and selects its lot by name", async () => { + expect(getManualLineInitialQuantity({scannedQuantity: 2.5})).toBe(2.5); + expect(getManualLineInitialQuantity({})).toBe(1); + const mock = { + props: { + params: { + mode: "manual_line", + preselectProduct: 11, + scannedLotName: "LOT-GS1", + }, + }, + state: { + products: [], + search: "", + loading: true, + selectedProduct: null, + qty: getManualLineInitialQuantity({scannedQuantity: 2.5}), + lotId: false, + lots: [], + }, + inventory: { + searchRead: async (model) => + model === "product.product" + ? [{id: 11, name: "Widget", tracking: "lot"}] + : [{id: 13, name: "LOT-GS1"}], + }, + }; + + await ProductSelectorScreen.prototype.loadProducts.call(mock); + + expect(mock.state.qty).toBe(2.5); + expect(mock.state.lotId).toBe("13"); + expect(lotIdForName([{id: 13, name: "LOT-GS1"}], "LOT-GS1")).toBe("13"); + }); + + test("only manual-line mode uses the barcode-aware product filter", () => { + const product = {name: "Widget", default_code: "", barcode: "GS1-CODE"}; + const selector = Object.assign(Object.create(ProductSelectorScreen.prototype), { + props: {params: {mode: "manual_line"}}, + state: {search: "GS1-CODE", products: [product]}, + }); + expect(selector.filteredProducts).toEqual([product]); + + selector.props.params.mode = "quick_info_product"; + expect(selector.filteredProducts).toEqual([]); + }); + + test("manual selection keeps the screen open when the RPC fails", async () => { + let backCount = 0; + let notifyCount = 0; + const mock = { + props: {params: {mode: "manual_line", pickingId: 7}}, + state: {selectedProduct: {id: 11}, qty: 1, lotId: false}, + inventory: { + call: async () => { + throw new Error("not available"); + }, + notify: () => notifyCount++, + }, + store: {goBack: () => backCount++}, + }; + await ProductSelectorScreen.prototype.confirmSelection.call(mock); + expect(backCount).toBe(0); + expect(notifyCount).toBe(0); + }); +}); diff --git a/barcode_stock_unexpected_product/tests/__init__.py b/barcode_stock_unexpected_product/tests/__init__.py new file mode 100644 index 0000000..be488dd --- /dev/null +++ b/barcode_stock_unexpected_product/tests/__init__.py @@ -0,0 +1,9 @@ +from . import test_stock_picking_type +from . import test_stock_picking_type_view +from . import test_manual_line_authorization +from . import test_manual_line_guards +from . import test_manual_line_pending +from . import test_manual_line_availability +from . import test_manual_line_tracking +from . import test_manual_line_regression +from . import test_js diff --git a/barcode_stock_unexpected_product/tests/test_js.py b/barcode_stock_unexpected_product/tests/test_js.py new file mode 100644 index 0000000..eb4de2e --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_js.py @@ -0,0 +1,23 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.tests.common import HttpCase, tagged + + +@tagged("post_install", "-at_install") +class TestBarcodeStockUnexpectedProductJs(HttpCase): + """Run the module's JS unit tests (``static/tests``) in the browser. + + 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=BarcodeStockUnexpectedProduct", + "", + "", + login="admin", + success_signal="[HOOT] Test suite succeeded", + error_checker=lambda message: "[HOOT]" not in message, + ) diff --git a/barcode_stock_unexpected_product/tests/test_manual_line_authorization.py b/barcode_stock_unexpected_product/tests/test_manual_line_authorization.py new file mode 100644 index 0000000..fcb39e9 --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_manual_line_authorization.py @@ -0,0 +1,97 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.exceptions import UserError +from odoo.tests.common import TransactionCase + + +class TestManualLineAuthorization(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) + cls.company = cls.env.company + cls.origin = cls.env.ref("stock.stock_location_stock") + cls.destination = cls.env["stock.location"].create( + { + "name": "Manual line destination", + "usage": "internal", + "location_id": cls.origin.location_id.id, + "company_id": cls.company.id, + } + ) + cls.product = cls.env["product.product"].create( + {"name": "Manual authorization product", "is_storable": True} + ) + cls.env["stock.quant"]._update_available_quantity(cls.product, cls.origin, 10) + + def _picking(self, picking_type): + return self.env["stock.picking"].create( + { + "picking_type_id": picking_type.id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + } + ) + + def test_permitted_internal_transfer_is_authorized(self): + picking_type = self.env.ref("stock.picking_type_internal") + previous = picking_type.allow_insert_new_line + picking_type.allow_insert_new_line = True + try: + picking = self._picking(picking_type) + result = self.env[ + "stock.picking" + ].barcode_scanner_add_manual_line_to_picking(picking.id, self.product.id, 2) + self.assertEqual(result["product_id"], self.product.id) + self.assertEqual( + self.env["stock.move"].browse(result["move_id"]), picking.move_ids + ) + finally: + picking_type.write({"allow_insert_new_line": previous}) + + def test_internal_type_with_flag_disabled_is_rejected(self): + picking_type = self.env.ref("stock.picking_type_internal") + previous = picking_type.allow_insert_new_line + picking_type.allow_insert_new_line = False + try: + picking = self._picking(picking_type) + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, self.product.id, 1 + ) + self.assertFalse(picking.move_ids) + finally: + picking_type.write({"allow_insert_new_line": previous}) + + def test_receipt_and_delivery_are_rejected(self): + for xmlid in ("stock.picking_type_in", "stock.picking_type_out"): + with self.subTest(xmlid=xmlid): + picking_type = self.env.ref(xmlid) + previous = picking_type.allow_insert_new_line + picking_type.allow_insert_new_line = True + try: + picking = self._picking(picking_type) + with self.assertRaises(UserError): + self.env[ + "stock.picking" + ].barcode_scanner_add_manual_line_to_picking( + picking.id, self.product.id, 1 + ) + self.assertFalse(picking.move_ids) + finally: + picking_type.write({"allow_insert_new_line": previous}) + + def test_done_picking_is_rejected(self): + picking_type = self.env.ref("stock.picking_type_internal") + previous = picking_type.allow_insert_new_line + picking_type.allow_insert_new_line = True + try: + picking = self._picking(picking_type) + picking.state = "done" + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, self.product.id, 1 + ) + finally: + picking_type.write({"allow_insert_new_line": previous}) diff --git a/barcode_stock_unexpected_product/tests/test_manual_line_availability.py b/barcode_stock_unexpected_product/tests/test_manual_line_availability.py new file mode 100644 index 0000000..8733434 --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_manual_line_availability.py @@ -0,0 +1,66 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.exceptions import UserError +from odoo.tests.common import TransactionCase + + +class TestManualLineAvailability(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.origin = cls.env.ref("stock.stock_location_stock") + cls.destination = cls.env["stock.location"].create( + { + "name": "Manual availability destination", + "usage": "internal", + "location_id": cls.origin.location_id.id, + "company_id": cls.env.company.id, + } + ) + cls.picking_type = cls.env.ref("stock.picking_type_internal") + cls._picking_type_allow_insert_new_line = cls.picking_type.allow_insert_new_line + cls.picking_type.allow_insert_new_line = True + + @classmethod + def tearDownClass(cls): + cls.picking_type.write( + { + "allow_insert_new_line": cls._picking_type_allow_insert_new_line, + } + ) + super().tearDownClass() + + def test_insufficient_stock_does_not_create_move(self): + product = self.env["product.product"].create( + {"name": "Unavailable manual product", "is_storable": True} + ) + picking = self.env["stock.picking"].create( + { + "picking_type_id": self.picking_type.id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + } + ) + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1 + ) + self.assertFalse(picking.move_ids) + + def test_invalid_quantity_does_not_create_move(self): + product = self.env["product.product"].create( + {"name": "Invalid quantity product", "is_storable": True} + ) + picking = self.env["stock.picking"].create( + { + "picking_type_id": self.picking_type.id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + } + ) + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 0 + ) + self.assertFalse(picking.move_ids) diff --git a/barcode_stock_unexpected_product/tests/test_manual_line_guards.py b/barcode_stock_unexpected_product/tests/test_manual_line_guards.py new file mode 100644 index 0000000..b76feaa --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_manual_line_guards.py @@ -0,0 +1,229 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from unittest.mock import patch + +from odoo.exceptions import UserError +from odoo.tests.common import TransactionCase, new_test_user + + +class TestManualLineGuards(TransactionCase): + """Defensive paths of the manual-line RPC and quantity synchronisation.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.company = cls.env.company + cls.origin = cls.env.ref("stock.stock_location_stock") + cls.destination = cls.env["stock.location"].create( + { + "name": "Manual guards destination", + "usage": "internal", + "location_id": cls.origin.location_id.id, + "company_id": cls.company.id, + } + ) + cls.picking_type = cls.env.ref("stock.picking_type_internal") + cls._allow_insert_new_line = cls.picking_type.allow_insert_new_line + cls.picking_type.allow_insert_new_line = True + + @classmethod + def tearDownClass(cls): + cls.picking_type.write({"allow_insert_new_line": cls._allow_insert_new_line}) + super().tearDownClass() + + def _product(self, tracking="none"): + return self.env["product.product"].create( + { + "name": f"Manual guard {tracking} product", + "is_storable": True, + "tracking": tracking, + } + ) + + def _picking(self): + return self.env["stock.picking"].create( + { + "picking_type_id": self.picking_type.id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + } + ) + + def _manual_move(self, product, quantity=1): + return self.env["stock.move"].create( + { + "name": product.display_name, + "product_id": product.id, + "product_uom_qty": quantity, + "product_uom": product.uom_id.id, + "picking_id": self._picking().id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + "company_id": self.company.id, + "is_manually": True, + } + ) + + def test_invalid_lot_id_is_rejected(self): + product = self._product(tracking="lot") + picking = self._picking() + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, "not-a-number" + ) + + def test_missing_lot_is_rejected(self): + product = self._product(tracking="lot") + picking = self._picking() + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, 999999999 + ) + + def test_missing_picking_is_rejected(self): + product = self._product() + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + 999999999, product.id, 1 + ) + + def test_missing_product_is_rejected(self): + picking = self._picking() + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, 999999999, 1 + ) + + def test_lot_from_other_company_is_rejected(self): + other_company = self.env["res.company"].create( + {"name": "Manual guards other company"} + ) + product = self._product(tracking="lot") + lot = self.env["stock.lot"].create( + {"name": "MANUAL-GUARD-OTHER-COMPANY", "product_id": product.id} + ) + lot.company_id = other_company + picking = self._picking() + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, lot.id + ) + + def test_reservation_shortfall_is_rejected(self): + product = self._product() + self.env["stock.quant"]._update_available_quantity(product, self.origin, 5) + picking = self._picking() + move_model = type(self.env["stock.move"]) + with patch.object(move_model, "_update_reserved_quantity", return_value=0): + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1 + ) + + def test_delete_missing_move_is_rejected(self): + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_delete_manual_line(999999999) + + def test_delete_completed_move_is_rejected(self): + product = self._product() + other_product = self._product(tracking="none") + self.env["stock.quant"]._update_available_quantity(product, self.origin, 1) + self.env["stock.quant"]._update_available_quantity( + other_product, self.origin, 1 + ) + picking = self._picking() + model = self.env["stock.picking"] + result = model.barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, auto_pick=True + ) + model.barcode_scanner_add_manual_line_to_picking( + picking.id, other_product.id, 1, auto_pick=True + ) + move = self.env["stock.move"].browse(result["move_id"]) + self.env.flush_all() + self.env.cr.execute( + "UPDATE stock_move SET state = 'done' WHERE id = %s", [move.id] + ) + move.invalidate_recordset(["state"]) + self.assertEqual(move.state, "done") + self.assertNotIn(picking.state, ("done", "cancel")) + with self.assertRaises(UserError): + model.barcode_scanner_delete_manual_line(move.id) + + def test_delete_move_without_quantity_skips_unreserve(self): + product = self._product() + move = self._manual_move(product, quantity=0) + result = self.env["stock.picking"].barcode_scanner_delete_manual_line(move.id) + self.assertTrue(result["deleted"]) + self.assertEqual(result["move_id"], move.id) + + def test_delete_manual_line_as_stock_user(self): + product = self._product() + self.env["stock.quant"]._update_available_quantity(product, self.origin, 1) + picking = self._picking() + result = self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, auto_pick=True + ) + move = self.env["stock.move"].browse(result["move_id"]) + user = new_test_user( + self.env, + login="manual_line_stock_user", + groups="stock.group_stock_user", + ) + + self.env["stock.picking"].with_user(user).barcode_scanner_delete_manual_line( + move.id + ) + + self.assertFalse(move.exists()) + self.assertEqual( + self.env["stock.quant"]._get_available_quantity( + product, self.origin, strict=True + ), + 1, + ) + + def test_create_line_syncs_manual_move_quantity(self): + product = self._product() + move = self._manual_move(product) + regular_move = self._manual_move(product) + regular_move.is_manually = False + lines = ( + self.env["stock.move.line"] + .with_context(move_line_pick_qty=True) + .create( + [ + { + "move_id": move.id, + "product_id": product.id, + "product_uom_id": product.uom_id.id, + "quantity": 1, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + }, + { + "move_id": move.id, + "product_id": product.id, + "product_uom_id": product.uom_id.id, + "quantity": 2, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + }, + { + "move_id": regular_move.id, + "product_id": product.id, + "product_uom_id": product.uom_id.id, + "quantity": 2, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + }, + ] + ) + ) + self.assertEqual(move.product_uom_qty, 3) + self.assertEqual(regular_move.product_uom_qty, 1) + + lines.write({"quantity": 4}) + self.assertEqual(move.product_uom_qty, 8) + self.assertEqual(regular_move.product_uom_qty, 1) diff --git a/barcode_stock_unexpected_product/tests/test_manual_line_pending.py b/barcode_stock_unexpected_product/tests/test_manual_line_pending.py new file mode 100644 index 0000000..f686dc6 --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_manual_line_pending.py @@ -0,0 +1,72 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.tests.common import TransactionCase + + +class TestManualLinePending(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.origin = cls.env.ref("stock.stock_location_stock") + cls.destination = cls.env["stock.location"].create( + { + "name": "Manual pending destination", + "usage": "internal", + "location_id": cls.origin.location_id.id, + "company_id": cls.env.company.id, + } + ) + cls.picking_type = cls.env.ref("stock.picking_type_internal") + cls._picking_type_allow_insert_new_line = cls.picking_type.allow_insert_new_line + cls.picking_type.allow_insert_new_line = True + cls.product = cls.env["product.product"].create( + {"name": "Manual pending product", "is_storable": True} + ) + cls.env["stock.quant"]._update_available_quantity(cls.product, cls.origin, 5000) + + @classmethod + def tearDownClass(cls): + cls.picking_type.write( + {"allow_insert_new_line": cls._picking_type_allow_insert_new_line} + ) + super().tearDownClass() + + def test_bulk_add_creates_pending_demand(self): + picking = self.env["stock.picking"].create( + { + "picking_type_id": self.picking_type.id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + } + ) + result = self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, self.product.id, 2000 + ) + move = self.env["stock.move"].browse(result["move_id"]) + self.assertEqual(move.product_uom_qty, 2000) + self.assertFalse(move.picked) + self.assertTrue(move.move_line_ids) + self.assertEqual(sum(move.move_line_ids.mapped("quantity")), 2000) + self.assertEqual(sum(move.move_line_ids.mapped("qty_picked")), 0) + self.assertFalse(any(move.move_line_ids.mapped("picked"))) + + def test_repeated_add_merges_pending_move(self): + picking = self.env["stock.picking"].create( + { + "picking_type_id": self.picking_type.id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + } + ) + model = self.env["stock.picking"] + first = model.barcode_scanner_add_manual_line_to_picking( + picking.id, self.product.id, 2 + ) + second = model.barcode_scanner_add_manual_line_to_picking( + picking.id, self.product.id, 3 + ) + self.assertEqual(first["move_id"], second["move_id"]) + move = self.env["stock.move"].browse(first["move_id"]) + self.assertEqual(move.product_uom_qty, 5) + self.assertEqual(sum(move.move_line_ids.mapped("quantity")), 5) diff --git a/barcode_stock_unexpected_product/tests/test_manual_line_regression.py b/barcode_stock_unexpected_product/tests/test_manual_line_regression.py new file mode 100644 index 0000000..f397e94 --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_manual_line_regression.py @@ -0,0 +1,14 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.tests.common import TransactionCase + + +class TestManualLineRegression(TransactionCase): + def test_manual_line_rpc_remains_available(self): + self.assertTrue( + hasattr( + self.env["stock.picking"], + "barcode_scanner_add_manual_line_to_picking", + ) + ) diff --git a/barcode_stock_unexpected_product/tests/test_manual_line_tracking.py b/barcode_stock_unexpected_product/tests/test_manual_line_tracking.py new file mode 100644 index 0000000..d8458be --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_manual_line_tracking.py @@ -0,0 +1,191 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.exceptions import UserError +from odoo.tests.common import TransactionCase + + +class TestManualLineTracking(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.origin = cls.env.ref("stock.stock_location_stock") + cls.destination = cls.env["stock.location"].create( + { + "name": "Manual tracking destination", + "usage": "internal", + "location_id": cls.origin.location_id.id, + "company_id": cls.env.company.id, + } + ) + cls.picking_type = cls.env.ref("stock.picking_type_internal") + cls._picking_type_allow_insert_new_line = cls.picking_type.allow_insert_new_line + cls.picking_type.allow_insert_new_line = True + + @classmethod + def tearDownClass(cls): + cls.picking_type.write( + { + "allow_insert_new_line": cls._picking_type_allow_insert_new_line, + } + ) + super().tearDownClass() + + def _picking(self): + return self.env["stock.picking"].create( + { + "picking_type_id": self.picking_type.id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + } + ) + + def test_lot_is_required_and_serial_quantity_is_one(self): + product = self.env["product.product"].create( + { + "name": "Tracked manual product", + "is_storable": True, + "tracking": "serial", + } + ) + lot = self.env["stock.lot"].create( + {"name": "MANUAL-SERIAL-1", "product_id": product.id} + ) + self.env["stock.quant"]._update_available_quantity( + product, self.origin, 1, lot_id=lot + ) + picking = self._picking() + model = self.env["stock.picking"] + with self.assertRaises(UserError): + model.barcode_scanner_add_manual_line_to_picking(picking.id, product.id, 1) + with self.assertRaises(UserError): + model.barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 2, lot.id + ) + result = model.barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, lot.id + ) + line = self.env["stock.move"].browse(result["move_id"]).move_line_ids + self.assertEqual(line.lot_id, lot) + self.assertEqual(line.quantity, 1) + self.assertEqual(line.qty_picked, 0) + + def test_lot_must_match_product(self): + product = self.env["product.product"].create( + {"name": "Lot manual product", "is_storable": True, "tracking": "lot"} + ) + other = self.env["product.product"].create( + {"name": "Other lot product", "is_storable": True} + ) + lot = self.env["stock.lot"].create( + {"name": "WRONG-PRODUCT", "product_id": other.id} + ) + self.env["stock.quant"]._update_available_quantity(product, self.origin, 1) + picking = self._picking() + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, lot.id + ) + + def test_string_lot_id_with_multiple_digits_is_resolved(self): + product = self.env["product.product"].create( + { + "name": "String lot manual product", + "is_storable": True, + "tracking": "lot", + } + ) + Lot = self.env["stock.lot"] + lots = Lot.create( + [ + {"name": f"STRING-LOT-{index}", "product_id": product.id} + for index in range(10) + ] + ) + lot = lots[-1] + self.assertGreater(lot.id, 9) + self.env["stock.quant"]._update_available_quantity( + product, self.origin, 1, lot_id=lot + ) + picking = self._picking() + + result = self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, str(lot.id) + ) + + line = self.env["stock.move"].browse(result["move_id"]).move_line_ids + self.assertEqual(line.lot_id, lot) + + def test_auto_pick_sets_qty_picked_and_delete_unreserves(self): + product = self.env["product.product"].create( + {"name": "Auto-picked manual product", "is_storable": True} + ) + quant_model = self.env["stock.quant"] + quant_model._update_available_quantity(product, self.origin, 5) + available_before = quant_model._get_available_quantity( + product, self.origin, strict=True + ) + picking = self._picking() + + result = self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 2, auto_pick=True + ) + move = self.env["stock.move"].browse(result["move_id"]) + self.assertTrue(result["picked"]) + self.assertEqual(sum(move.move_line_ids.mapped("quantity")), 2) + self.assertEqual(sum(move.move_line_ids.mapped("qty_picked")), 2) + self.assertEqual( + quant_model._get_available_quantity(product, self.origin, strict=True), + available_before - 2, + ) + + deleted = self.env["stock.picking"].barcode_scanner_delete_manual_line(move.id) + + self.assertEqual(deleted, {"deleted": True, "move_id": move.id}) + self.assertFalse(move.exists()) + self.assertEqual( + quant_model._get_available_quantity(product, self.origin, strict=True), + available_before, + ) + + def test_delete_rejects_non_manual_move(self): + product = self.env["product.product"].create( + {"name": "Regular move product", "is_storable": True} + ) + picking = self._picking() + move = self.env["stock.move"].create( + { + "name": product.display_name, + "product_id": product.id, + "product_uom_qty": 1, + "product_uom": product.uom_id.id, + "picking_id": picking.id, + "location_id": self.origin.id, + "location_dest_id": self.destination.id, + "company_id": self.env.company.id, + "is_manually": False, + } + ) + + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_delete_manual_line(move.id) + + self.assertTrue(move.exists()) + + def test_delete_rejects_completed_picking(self): + product = self.env["product.product"].create( + {"name": "Completed manual product", "is_storable": True} + ) + self.env["stock.quant"]._update_available_quantity(product, self.origin, 1) + picking = self._picking() + result = self.env["stock.picking"].barcode_scanner_add_manual_line_to_picking( + picking.id, product.id, 1, auto_pick=True + ) + move = self.env["stock.move"].browse(result["move_id"]) + picking.with_context(skip_backorder=True).button_validate() + self.assertEqual(picking.state, "done") + + with self.assertRaises(UserError): + self.env["stock.picking"].barcode_scanner_delete_manual_line(move.id) + + self.assertTrue(move.exists()) diff --git a/barcode_stock_unexpected_product/tests/test_stock_picking_type.py b/barcode_stock_unexpected_product/tests/test_stock_picking_type.py new file mode 100644 index 0000000..ec222ef --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_stock_picking_type.py @@ -0,0 +1,66 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo.tests.common import TransactionCase + + +class TestStockPickingTypeAllowInsertNewLine(TransactionCase): + """EXP-01 and EXP-07: field definition, persistence and upgrade safety.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.picking_type_model = cls.env["stock.picking.type"] + + def test_field_exists_boolean_stored_default_false(self): + # QA-01 + field = self.picking_type_model._fields["allow_insert_new_line"] + self.assertEqual(field.type, "boolean") + self.assertTrue(field.store) + picking_type = self.picking_type_model.create( + { + "name": "Internal QA01", + "code": "internal", + "sequence_code": "TEST01", + } + ) + self.assertIs(picking_type.allow_insert_new_line, False) + + def test_field_value_persisted_in_database(self): + # QA-02: the value is stored, not computed on the fly. + picking_type = self.picking_type_model.create( + { + "name": "Internal QA02", + "code": "internal", + "sequence_code": "TEST02", + } + ) + self.env.cr.execute( + "SELECT allow_insert_new_line FROM stock_picking_type WHERE id = %s", + [picking_type.id], + ) + self.assertIs(self.env.cr.fetchone()[0], False) + + def test_existing_internal_types_keep_false(self): + # QA-03 / EXP-07: "Storage" keeps False, "Ship to Jobs" keeps False + # when present, and no module data enables any type retroactively. + storage = self.env.ref("stock.picking_type_internal") + previous_allow_insert_new_line = storage.allow_insert_new_line + try: + # Ensure isolation from previous manual changes (e.g., WH/INT/00001 + # set to True) while checking the module's configured default. + storage.allow_insert_new_line = False + self.assertIs(storage.allow_insert_new_line, False) + ship_to_jobs = self.env.ref( + "stock.picking_type_internal_ship_to_jobs", raise_if_not_found=False + ) + self.assertFalse( + ship_to_jobs and ship_to_jobs.allow_insert_new_line, + "Ship to Jobs must keep allow_insert_new_line disabled", + ) + enabled = self.picking_type_model.search( + [("allow_insert_new_line", "=", True)] + ) + self.assertFalse(enabled) + finally: + storage.allow_insert_new_line = previous_allow_insert_new_line diff --git a/barcode_stock_unexpected_product/tests/test_stock_picking_type_view.py b/barcode_stock_unexpected_product/tests/test_stock_picking_type_view.py new file mode 100644 index 0000000..594c254 --- /dev/null +++ b/barcode_stock_unexpected_product/tests/test_stock_picking_type_view.py @@ -0,0 +1,38 @@ +# Copyright 2026 Binhex +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from lxml import etree + +from odoo.tests.common import TransactionCase + + +class TestStockPickingTypeBarcodeView(TransactionCase): + """EXP-02/EXP-03: the "Barcode" section renders only for internal types.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + view = cls.env.ref( + "barcode_stock_unexpected_product.view_picking_type_form_inherit_barcode" + ) + cls.arch = etree.fromstring( + cls.env["stock.picking.type"].get_view(view_id=view.id, view_type="form")[ + "arch" + ] + ) + + def test_barcode_page_inside_notebook(self): + # T-04 / QA-05: the page exists, is titled "Barcode" and lives inside + # the notebook of the operation type form. + page = self.arch.xpath("//page[@name='barcode']") + self.assertEqual(len(page), 1) + self.assertEqual(page[0].get("string"), "Barcode") + self.assertEqual(page[0].getparent().tag, "notebook") + + def test_barcode_page_invisible_for_non_internal_codes(self): + # T-03 / QA-04: for incoming/outgoing codes the page (and its field) + # is not rendered; visibility is bound to code == 'internal'. + page = self.arch.xpath("//page[@name='barcode']")[0] + self.assertEqual(page.get("invisible"), "code != 'internal'") + fields = page.xpath(".//field[@name='allow_insert_new_line']") + self.assertEqual(len(fields), 1) diff --git a/barcode_stock_unexpected_product/views/stock_picking_type_views.xml b/barcode_stock_unexpected_product/views/stock_picking_type_views.xml new file mode 100644 index 0000000..670e239 --- /dev/null +++ b/barcode_stock_unexpected_product/views/stock_picking_type_views.xml @@ -0,0 +1,17 @@ + + + + stock.picking.type.form.inherit.barcode + stock.picking.type + + + + + + + + + + + +