size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
910
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA - Damien Crier, Alexandre Fayolle # Copyright 2017 Eficent Business and IT Consulting Services S.L. # Copyright 2017 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Stock picking lines with sequence number", "summary": "Manages the order of stock moves by displaying its sequence", "version": "15.0.1.0.2", "category": "Warehouse Management", "author": "Camptocamp, " "Eficent, " "Serpent CS, " "Odoo Community Association (OCA), " "ArcheTI", "website": "https://github.com/OCA/stock-logistics-workflow", "depends": ["stock", "sale", "sale_stock"], "data": [ "views/stock_view.xml", "report/report_deliveryslip.xml", ], "post_init_hook": "post_init_hook", "installable": True, "auto_install": False, "license": "AGPL-3", }
35
910
5,314
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA - Damien Crier, Alexandre Fayolle # Copyright 2017 Eficent Business and IT Consulting Services S.L. # Copyright 2017 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests import common class TestStockMove(common.TransactionCase): def setUp(self): super(TestStockMove, self).setUp() # Useful models self.Picking = self.env["stock.picking"] self.product_id_1 = self.env.ref("product.product_product_8") self.product_id_2 = self.env.ref("product.product_product_11") self.product_id_3 = self.env.ref("product.product_product_6") self.picking_type_in = self.env.ref("stock.picking_type_in") self.supplier_location = self.env.ref("stock.stock_location_suppliers") self.customer_location = self.env.ref("stock.stock_location_customers") def _create_picking(self): """Create a Picking.""" picking = self.Picking.create( { "picking_type_id": self.picking_type_in.id, "location_id": self.supplier_location.id, "location_dest_id": self.customer_location.id, "move_lines": [ ( 0, 0, { "name": "move 1", "product_id": self.product_id_1.id, "product_uom_qty": 5.0, "product_uom": self.product_id_1.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.customer_location.id, }, ), ( 0, 0, { "name": "move 2", "product_id": self.product_id_2.id, "product_uom_qty": 5.0, "product_uom": self.product_id_2.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.customer_location.id, }, ), ( 0, 0, { "name": "move 3", "product_id": self.product_id_3.id, "product_uom_qty": 5.0, "product_uom": self.product_id_3.uom_id.id, "location_id": self.supplier_location.id, "location_dest_id": self.customer_location.id, }, ), ], } ) return picking def test_move_lines_sequence(self): self.picking = self._create_picking() self.picking._compute_max_line_sequence() self.picking.move_lines.write({"product_uom_qty": 10.0}) self.picking2 = self.picking.copy() self.assertEqual( self.picking2[0].move_lines[0].sequence, self.picking.move_lines[0].sequence, "The Sequence is not copied properly", ) self.assertEqual( self.picking2[0].move_lines[1].sequence, self.picking.move_lines[1].sequence, "The Sequence is not copied properly", ) self.assertEqual( self.picking2[0].move_lines[2].sequence, self.picking.move_lines[2].sequence, "The Sequence is not copied properly", ) def test_backorder(self): picking = self._create_picking() picking._compute_max_line_sequence() picking.action_confirm() picking.action_assign() picking.move_line_ids[1].write({"qty_done": 5}) res_dict = picking.button_validate() self.assertEqual(res_dict["res_model"], "stock.backorder.confirmation") backorder_wiz = ( self.env["stock.backorder.confirmation"] .browse(res_dict.get("res_id")) .with_context(**res_dict["context"]) ) backorder_wiz.process() picking_backorder = self.Picking.search([("backorder_id", "=", picking.id)]) self.assertEqual( picking_backorder[0].move_lines[1].sequence, 3, "Backorder wrong sequence" ) self.assertEqual( picking_backorder[0].move_lines[0].sequence, 1, "Backorder wrong sequence" ) def test_move_lines_aggregated(self): picking = self._create_picking() picking._compute_max_line_sequence() picking.action_confirm() agg_mls = picking.move_line_ids[0]._get_aggregated_product_quantities() for key in agg_mls: self.assertNotEqual( agg_mls[key].get("sequence2", "NA"), "NA", "The field sequence2 is not added in dictionary", ) self.assertEqual( picking.move_line_ids[0].move_id.sequence2, agg_mls[key]["sequence2"], "The Sequence is not copied properly in " "the aggregated move lines", )
41.193798
5,314
3,496
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA - Damien Crier, Alexandre Fayolle # Copyright 2017 Eficent Business and IT Consulting Services S.L. # Copyright 2017 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class StockMove(models.Model): _inherit = "stock.move" # re-defines the field to change the default sequence = fields.Integer("HiddenSequence", default=9999) # displays sequence on the stock moves sequence2 = fields.Integer( "Sequence", help="Shows the sequence in the Stock Move.", related="sequence", readonly=True, store=True, ) @api.model def create(self, values): move = super(StockMove, self).create(values) # We do not reset the sequence if we are copying a complete picking # or creating a backorder if not self.env.context.get("keep_line_sequence", False): move.picking_id._reset_sequence() return move class StockMoveLine(models.Model): _inherit = "stock.move.line" def _get_aggregated_product_quantities(self, **kwargs): def get_aggregated_properties(move_line=False, move=False): move = move or move_line.move_id uom = move.product_uom or move_line.product_uom_id name = move.product_id.display_name description = move.description_picking if description == name or description == move.product_id.name: description = False product = move.product_id line_key = ( f"{product.id}_{product.display_name}_" f'{description or ""}_{uom.id}' ) return line_key aggregated_move_lines = super( StockMoveLine, self )._get_aggregated_product_quantities(**kwargs) for move_line in self: line_key = get_aggregated_properties(move_line=move_line) sequence2 = move_line.move_id.sequence2 if line_key in aggregated_move_lines: aggregated_move_lines[line_key]["sequence2"] = sequence2 return aggregated_move_lines class StockPicking(models.Model): _inherit = "stock.picking" @api.depends("move_ids_without_package") def _compute_max_line_sequence(self): """Allow to know the highest sequence entered in move lines. Then we add 1 to this value for the next sequence, this value is passed to the context of the o2m field in the view. So when we create new move line, the sequence is automatically incremented by 1. (max_sequence + 1) """ for picking in self: picking.max_line_sequence = ( max(picking.mapped("move_ids_without_package.sequence") or [0]) + 1 ) max_line_sequence = fields.Integer( string="Max sequence in lines", compute="_compute_max_line_sequence" ) def _reset_sequence(self): for rec in self: current_sequence = 1 for line in rec.move_ids_without_package: line.sequence = current_sequence current_sequence += 1 def copy(self, default=None): return super(StockPicking, self.with_context(keep_line_sequence=True)).copy( default ) def button_validate(self): return super( StockPicking, self.with_context(keep_line_sequence=True) ).button_validate()
35.673469
3,496
534
py
PYTHON
15.0
# © 2017 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Stock Picking Sale Order Link", "summary": "Link between picking and sale order", "version": "15.0.1.0.2", "category": "Inventory", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["sale_stock"], "data": ["views/stock_picking_view.xml"], }
35.533333
533
2,210
py
PYTHON
15.0
# © 2017 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import tagged from odoo.tests.common import TransactionCase @tagged("post_install", "-at_install") class TestStockPickingSaleOrderLink(TransactionCase): def setUp(self): super(TestStockPickingSaleOrderLink, self).setUp() self.Location = self.env["stock.location"] self.PickingType = self.env["stock.picking.type"] self.Picking = self.env["stock.picking"] self.Product = self.env["product.template"] self.warehouse = self.env["stock.warehouse"].create( {"name": "warehouse - test", "code": "WH-TEST"} ) self.product = self.Product.create( { "name": "Product - Test", "type": "product", "list_price": 100.00, "standard_price": 100.00, } ) self.partner = self.env["res.partner"].create({"name": "Customer - test"}) self.picking_type = self.PickingType.search( [("warehouse_id", "=", self.warehouse.id), ("code", "=", "outgoing")] ) sale_order = self.env["sale.order"].create( { "partner_id": self.partner.id, "partner_invoice_id": self.partner.id, "partner_shipping_id": self.partner.id, "order_line": [ ( 0, 0, { "name": self.product.name, "product_id": self.product.product_variant_ids.id, "product_uom_qty": 2, "product_uom": self.product.uom_id.id, "price_unit": 100.00, }, ) ], } ) sale_order.action_confirm() self.picking = self.Picking.search([("sale_id", "=", sale_order.id)]) def test_picking_to_sale_order(self): result = self.picking.action_view_sale_order() self.assertEqual(result["res_id"], self.picking.sale_id.id)
38.754386
2,209
736
py
PYTHON
15.0
# © 2017 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockPicking(models.Model): _inherit = "stock.picking" def action_view_sale_order(self): """This function returns an action that display existing sales order of given picking. """ self.ensure_one() # Remove default_picking_id to avoid defaults get # https://github.com/odoo/odoo/blob/e4d22d390c8aa8edf757e36704a9e04b2b89f115/ # addons/stock/models/stock_move.py#L410 ctx = self.env.context.copy() ctx.pop("default_picking_id", False) return self.with_context(**ctx).sale_id.get_formview_action()
36.75
735
314
py
PYTHON
15.0
# Copyright 2019 Camptocamp - Iryna Vyshnevska # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import SUPERUSER_ID, api def post_init_hook(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) env["res.company"].search([]).write({"use_oca_batch_validation": True})
31.4
314
1,141
py
PYTHON
15.0
# Copyright 2012-2014 Alexandre Fayolle, Camptocamp SA # Copyright 2018-2020 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock batch picking extended", "summary": "Allows manage a lot of pickings in batch", "version": "15.0.2.3.0", "author": "Camptocamp, " "Tecnativa, " "Odoo Community Association (OCA)", "development_status": "Mature", "maintainers": ["gurneyalex", "carlosdauden", "i-vyshnevska"], "category": "Warehouse Management", "depends": ["stock_picking_batch", "delivery"], "website": "https://github.com/OCA/stock-logistics-workflow", "data": [ "security/ir.model.access.csv", "data/batch_picking_actions_server.xml", "views/stock_batch_picking.xml", "views/product_product.xml", "views/report_batch_picking.xml", "views/stock_picking_views.xml", "views/stock_warehouse.xml", "views/res_config_settings_views.xml", "wizard/stock_picking_to_batch_views.xml", ], "installable": True, "post_init_hook": "post_init_hook", "license": "AGPL-3", }
39.344828
1,141
463
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from openupgradelib import openupgrade def _update_assigned_state_to_inprogress(env): query = """ UPDATE stock_picking_batch SET state = 'in_progress' WHERE state='assigned' """ openupgrade.logged_query(env.cr, query) @openupgrade.migrate() def migrate(env, version): _update_assigned_state_to_inprogress(env)
25.722222
463
15,339
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Carlos Dauden from odoo.exceptions import UserError from odoo.tests import Form from odoo.tests.common import TransactionCase, tagged @tagged("post_install", "-at_install") class TestBatchPicking(TransactionCase): def _create_product(self, name, product_type="consu"): return self.env["product.product"].create({"name": name, "type": product_type}) def setUp(self): super(TestBatchPicking, self).setUp() self.stock_loc = self.browse_ref("stock.stock_location_stock") self.customer_loc = self.browse_ref("stock.stock_location_customers") self.uom_unit = self.env.ref("uom.product_uom_unit") self.batch_model = self.env["stock.picking.batch"] # Delete (in transaction) all batches for simplify tests. self.batch_model.search([("state", "=", "draft")]).unlink() self.picking_model = self.env["stock.picking"] self.product6 = self._create_product("product_product_6") self.product7 = self._create_product("product_product_7") self.product8 = self._create_product("product_product_8", "product") self.product9 = self._create_product("product_product_9") self.product10 = self._create_product("product_product_10") self.product11 = self._create_product("product_product_11") self.picking = self.create_simple_picking(self.product6.ids + self.product7.ids) self.picking.action_confirm() self.picking2 = self.create_simple_picking((self.product9 + self.product10).ids) self.picking2.action_confirm() self.batch = self.batch_model.create( { "user_id": self.env.uid, "use_oca_batch_validation": True, "picking_ids": [(4, self.picking.id), (4, self.picking2.id)], } ) def create_simple_picking(self, product_ids, batch_id=False): # The 'planned' context key ensures that the picking # will be created in the 'draft' state (no autoconfirm) return self.picking_model.with_context(planned=True).create( { "picking_type_id": self.ref("stock.picking_type_out"), "location_id": self.stock_loc.id, "location_dest_id": self.customer_loc.id, "batch_id": batch_id, "move_lines": [ ( 0, 0, { "name": "Test move", "product_id": product_id, "product_uom": self.ref("uom.product_uom_unit"), "product_uom_qty": 1, "location_id": self.stock_loc.id, "location_dest_id": self.customer_loc.id, }, ) for product_id in product_ids ], } ) def test_assign__no_picking(self): batch = self.batch_model.create({}) with self.assertRaises(UserError): batch.action_assign() # Even with multiple batches batches = batch | self.batch_model.create({}) with self.assertRaises(UserError): for batch in batches: batch.action_assign() def test_assign(self): self.assertEqual("draft", self.batch.state) self.assertEqual("assigned", self.picking.state) self.assertEqual("assigned", self.picking2.state) self.assertEqual(4, len(self.batch.move_line_ids)) self.assertEqual(4, len(self.batch.move_ids)) def test_assign_with_cancel(self): self.picking2.action_cancel() self.assertEqual("draft", self.batch.state) self.assertEqual("assigned", self.picking.state) self.assertEqual("cancel", self.picking2.state) self.batch.action_assign() self.assertEqual("draft", self.batch.state) self.assertEqual("cancel", self.picking2.state) def test_cancel(self): self.assertEqual("draft", self.batch.state) self.assertEqual("assigned", self.picking.state) self.assertEqual("assigned", self.picking2.state) self.batch.action_cancel() self.assertEqual("cancel", self.batch.state) self.assertEqual("cancel", self.picking.state) self.assertEqual("cancel", self.picking2.state) def test_cancel__no_pickings(self): batch = self.batch_model.create({}) self.assertEqual("draft", batch.state) batch.action_cancel() self.assertEqual("cancel", batch.state) def test_stock_picking_copy(self): picking = self.batch.picking_ids[0] self.assertEqual(self.batch, picking.batch_id) copy = picking.copy() self.assertFalse(copy.batch_id) def test_create_wizard(self): wizard = self.env["stock.picking.to.batch"].create( {"name": "Unittest wizard", "mode": "new"} ) # Pickings already in batch. with self.assertRaises(UserError): wizard.with_context(active_ids=[self.picking.id]).action_create_batch() # Creating and selecting (too) another picking picking3 = self.create_simple_picking(self.product8.ids) picking3.action_confirm() self.assertEqual( 0, self.batch_model.search_count([("name", "=", "Unittest wizard")]) ) wizard.with_context( active_ids=[self.picking.id, picking3.id] ).action_create_batch() batch = self.batch_model.search([("name", "=", "Unittest wizard")]) self.assertEqual(1, len(batch)) # Only picking3 because self.picking is already in another batch. self.assertEqual(picking3, batch.picking_ids) self.assertEqual(batch, picking3.batch_id) def test_wizard_user_id(self): wh_main = self.browse_ref("stock.warehouse0") wizard_model = self.env["stock.picking.to.batch"] wizard = wizard_model.create({"name": "Unittest wizard", "mode": "new"}) self.assertFalse(wizard.user_id) wh_main.default_user_id = self.env.user wizard = wizard_model.create({"name": "Unittest wizard"}) self.assertEqual(self.env.user, wizard.user_id) other_wh = self.env["stock.warehouse"].create( {"name": "Unittest other warehouse", "code": "UWH"} ) wizard = wizard_model.with_context(warehouse_id=other_wh.id).create( {"name": "Unittest wizard"} ) self.assertFalse(wizard.user_id) user2 = self.env["res.users"].create( {"name": "Unittest user", "login": "unittest_user"} ) other_wh.default_user_id = user2 wizard = wizard_model.with_context(warehouse_id=other_wh.id).create( {"name": "Unittest wizard"} ) self.assertEqual(user2, wizard.user_id) def perform_action(self, action): model = action["res_model"] res_id = action["res_id"] res = self.env[model].browse(res_id) res = res.process() return res def test_backorder(self): # Change move lines quantities for product 6 and 7 for move in self.batch.move_ids: if move.product_id == self.product6: move.product_uom_qty = 5 elif move.product_id == self.product7: move.product_uom_qty = 2 self.batch.action_assign() # Mark product 6 as partially processed and 7 and 9 as fully processed. for operation in self.batch.move_line_ids: # stock_move_line.qty_done if operation.product_id == self.product6: operation.qty_done = 3 elif operation.product_id == self.product7: operation.qty_done = 2 elif operation.product_id == self.product9: operation.qty_done = 1 # confirm transfer action creation self.batch.action_assign() context = self.batch.action_done().get("context") # confirm transfer action creation Form( self.env["stock.backorder.confirmation"].with_context(**context) ).save().process() self.assertEqual("done", self.picking.state) self.assertEqual("done", self.picking2.state) # A backorder has been created for product with # 5 - 3 = 2 qty to process. backorder = self.picking_model.search([("backorder_id", "=", self.picking.id)]) self.assertEqual(1, len(backorder)) self.assertEqual("assigned", backorder.state) self.assertEqual(1, len(backorder.move_lines)) self.assertEqual(self.product6, backorder.move_lines[0].product_id) self.assertEqual(2, backorder.move_lines[0].product_uom_qty) self.assertEqual(1, len(backorder.move_line_ids)) self.assertEqual(2, backorder.move_line_ids[0].product_uom_qty) self.assertEqual(0, backorder.move_line_ids[0].qty_done) backorder2 = self.picking_model.search( [("backorder_id", "=", self.picking2.id)] ) self.assertEqual(1, len(backorder2)) self.assertEqual("assigned", backorder2.state) self.assertEqual(1, len(backorder2.move_lines)) self.assertEqual(self.product10, backorder2.move_lines.product_id) self.assertEqual(1, backorder2.move_lines.product_uom_qty) self.assertEqual(1, len(backorder2.move_line_ids)) self.assertEqual(1, backorder2.move_line_ids.product_uom_qty) self.assertEqual(0, backorder2.move_line_ids.qty_done) def test_assign_draft_pick(self): picking3 = self.create_simple_picking( self.product11.ids, batch_id=self.batch.id ) self.assertEqual("draft", picking3.state) self.batch.action_assign() context = self.batch.action_done().get("context") Form( self.env["stock.immediate.transfer"].with_context(**context) ).save().process() self.assertEqual("done", self.batch.state) self.assertEqual("done", self.picking.state) self.assertEqual("done", self.picking2.state) self.assertEqual("done", picking3.state) def test_package(self): warehouse = self.browse_ref("stock.warehouse0") warehouse.delivery_steps = "pick_ship" group = self.env["procurement.group"].create( {"name": "Test", "move_type": "direct"} ) values = { "company_id": warehouse.company_id, "group_id": group, "date_planned": "2018-11-13 12:12:59", "warehouse_id": warehouse, } procurements = [ self.env["procurement.group"].Procurement( self.product11, 1, self.env.ref("uom.product_uom_unit"), self.customer_loc, "test", "TEST", warehouse.company_id, values, ) ] group.run(procurements) pickings = self.picking_model.search([("group_id", "=", group.id)]) self.assertEqual(2, len(pickings)) picking = pickings.filtered(lambda p: p.state == "assigned") picking.move_line_ids[0].qty_done = 1 picking.action_put_in_pack() other_picking = pickings.filtered(lambda p: p.id != picking.id) picking._action_done() self.assertEqual("assigned", other_picking.state) # We add the 'package' picking in batch other_picking.batch_id = self.batch self.batch.action_assign() context = self.batch.action_done().get("context") Form( self.env["stock.immediate.transfer"].with_context(**context) ).save().process() self.assertEqual("done", self.batch.state) self.assertEqual("done", self.picking.state) self.assertEqual("done", self.picking2.state) self.assertEqual("done", other_picking.state) def test_remove_undone(self): self.picking2.action_cancel() self.assertEqual("assigned", self.picking.state) self.assertEqual("cancel", self.picking2.state) self.assertEqual("draft", self.batch.state) self.batch.remove_undone_pickings() self.assertEqual("cancel", self.batch.state) self.assertEqual(1, len(self.batch.picking_ids)) self.assertEqual(self.picking2, self.batch.picking_ids) def test_partial_done(self): # If user filled some quantity_done manually in operations tab, # we want only these qties to be processed. # So picking with no qties processed are release and backorder are # created for picking partially processed. self.batch.action_assign() self.assertEqual("assigned", self.picking.state) self.assertEqual("assigned", self.picking2.state) self.picking.move_line_ids[0].qty_done = 1 self.picking2.move_line_ids[0].qty_done = 1 self.picking2.move_line_ids[1].qty_done = 1 context = self.batch.action_done().get("context") # Create backorder? action Form( self.env["stock.backorder.confirmation"].with_context(**context) ).save().process() self.batch.remove_undone_pickings() self.assertEqual(len(self.batch.picking_ids), 2) self.assertEqual("done", self.picking.state) # Second picking is filled and his state is done too self.assertEqual("done", self.picking2.state) self.assertTrue(self.picking2.batch_id) picking_backorder = self.picking_model.search( [("backorder_id", "=", self.picking.id)] ) self.assertEqual(1, len(picking_backorder.move_lines)) def test_wizard_batch_grouped_by_field(self): Wiz = self.env["stock.picking.to.batch"] self.picking.origin = "A" self.picking2.origin = "B" pickings = self.picking + self.picking2 wiz = Wiz.with_context(active_ids=pickings.ids).create( {"name": "Unittest wizard", "mode": "new"} ) # Read values from config parameters, before first execution there # are no values self.assertFalse(wiz.batch_by_group) self.assertFalse(wiz.group_field_ids) # Add fields no to do one batch picking per grouped picking # create_date field origin_field = self.env.ref("stock.field_stock_picking__origin") wiz.batch_by_group = True wiz.group_field_ids = [(0, 0, {"sequence": 1, "field_id": origin_field.id})] # Raise error if any picking already is in other batch picking with self.assertRaises(UserError): wiz.action_create_batch() # Two picking has distinct origin so two batch pickings must be created pickings.write({"batch_id": False}) res = wiz.action_create_batch() self.assertTrue(res["domain"]) # Two picking has same origin so only one batch picking must be created pickings.write({"batch_id": False}) self.picking2.origin = "A" res = wiz.action_create_batch() self.assertTrue(res["res_id"]) # Test if group field create_date has been stored into config # parameters self.assertEqual(origin_field, wiz.load_store_fields())
41.909836
15,339
6,790
py
PYTHON
15.0
# Copyright 2012-2016 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import json from odoo import _, api, fields, models from odoo.exceptions import UserError class StockPickingToBatch(models.TransientModel): """Create a stock.picking.batch from stock.picking""" _inherit = "stock.picking.to.batch" _group_field_param = "stock_batch_picking.group_field" name = fields.Char( help="Name of the batch picking", ) user_id = fields.Many2one( default=lambda self: self._default_user_id(), ) notes = fields.Text(help="Free form remarks") batch_by_group = fields.Boolean( string="Create batch pickings grouped by fields", ) group_field_ids = fields.One2many( comodel_name="stock.picking.batch.creator.group.field", inverse_name="picking_to_batch_id", string="Group by field", help="If set any, multiple batch picking will be created, one per " "group field", ) @api.onchange("batch_by_group") def onchange_batch_by_group(self): if self.batch_by_group: self.group_field_ids = False for index, field in enumerate(self.load_store_fields()): self.group_field_ids += self.group_field_ids.new( {"sequence": index, "field_id": field.id} ) def load_store_fields(self): group_field_ids = ( self.env["ir.config_parameter"].sudo().get_param(self._group_field_param) ) group_fields = self.env["ir.model.fields"].browse( group_field_ids and json.loads(group_field_ids) ) return group_fields @api.model def default_get(self, fields): """ Set last grouped fields used that are stored in config parameters """ res = super().default_get(fields) group_fields = self.load_store_fields() res["batch_by_group"] = group_fields and True or False return res def _default_user_id(self): """Return default_user_id from the main company warehouse except if a warehouse_id is specified in context. """ warehouse_id = self.env.context.get("warehouse_id") if warehouse_id: warehouse = self.env["stock.warehouse"].browse(warehouse_id) else: warehouse = self.env["stock.warehouse"].search( [("company_id", "=", self.env.user.company_id.id)], limit=1 ) return warehouse.default_user_id def _prepare_stock_batch_picking(self): vals = { "notes": self.notes, "user_id": self.user_id.id, } if self.name: # If not name set in wizard Odoo creates one automatically by sequence vals["name"] = self.name return vals def _raise_message_error(self): return _( "All selected pickings are already in a batch picking " "or are in a wrong state." ) def create_simple_batch(self, domain): """Create one batch picking with all pickings""" pickings = self.env["stock.picking"].search(domain) if not pickings: raise UserError(self._raise_message_error()) batch = self.env["stock.picking.batch"].create( self._prepare_stock_batch_picking() ) pickings.write({"batch_id": batch.id}) return batch def create_multiple_batch(self, domain): """Create n batch pickings by grouped fields selected""" StockPicking = self.env["stock.picking"] groupby = [f.field_id.name for f in self.group_field_ids] pickings_grouped = StockPicking.read_group(domain, groupby, groupby) if not pickings_grouped: raise UserError(self._raise_message_error()) batchs = self.env["stock.picking.batch"].browse() for group in pickings_grouped: batchs += self.env["stock.picking.batch"].create( self._prepare_stock_batch_picking() ) StockPicking.search(group["__domain"]).write({"batch_id": batchs[-1:].id}) return batchs def action_create_batch(self): """ For OCA approach: Create a batch picking with selected pickings after having checked that they are not already in another batch or done/cancel. For non OCA approach or add to existing batch picking: Call to original method """ if not self.env.company.use_oca_batch_validation or self.mode != "new": return self.attach_pickings() domain = [ ("id", "in", self.env.context["active_ids"]), ("batch_id", "=", False), ("state", "not in", ("cancel", "done")), ] if self.batch_by_group and self.group_field_ids: batchs = self.create_multiple_batch(domain) else: batchs = self.create_simple_batch(domain) # Store as system parameter the fields used to be loaded in the next # execution keeping the order. if self.batch_by_group: group_fields = [f.field_id.id for f in self.group_field_ids] self.env["ir.config_parameter"].sudo().set_param( self._group_field_param, group_fields ) # Ensure that the group field is empty upon the next execution elif ( self.env["ir.config_parameter"].sudo().get_param(self._group_field_param) != "[]" ): self.env["ir.config_parameter"].sudo().set_param( self._group_field_param, [] ) return self.action_view_batch_picking(batchs) def action_view_batch_picking(self, batch_pickings): if len(batch_pickings) > 1: action = self.env["ir.actions.act_window"]._for_xml_id( "stock_picking_batch.stock_picking_batch_action" ) action["domain"] = [("id", "in", batch_pickings.ids)] else: action = batch_pickings.get_formview_action() return action class StockBatchPickingCreatorGroupField(models.TransientModel): """Make mass batch pickings from grouped fields""" _name = "stock.picking.batch.creator.group.field" _description = "Batch Picking Creator Group Field" _order = "sequence, id" picking_to_batch_id = fields.Many2one( comodel_name="stock.picking.to.batch", ondelete="cascade", required=True, ) sequence = fields.Integer(help="Group by picking field", default=0) field_id = fields.Many2one( comodel_name="ir.model.fields", string="Field to group", domain=[("model", "=", "stock.picking"), ("store", "=", True)], required=True, )
37.103825
6,790
390
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class StockWarehouse(models.Model): _inherit = "stock.warehouse" default_user_id = fields.Many2one( "res.users", "Default Picker", help="the user to which the batch pickings are assigned by default", index=True, )
26
390
338
py
PYTHON
15.0
# Copyright 2012-2014 Alexandre Fayolle, Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class Product(models.Model): _inherit = "product.product" # TODO: Integrate in existent field description_warehouse = fields.Text("Warehouse Description", translate=True)
33.8
338
540
py
PYTHON
15.0
# Copyright 2019 Camptocamp - Iryna Vyshnevska # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" use_oca_batch_validation = fields.Boolean( string="Use OCA approach to validate Picking Batch", related="company_id.use_oca_batch_validation", readonly=False, ) class Company(models.Model): _inherit = "res.company" use_oca_batch_validation = fields.Boolean()
27
540
4,231
py
PYTHON
15.0
# Copyright 2012-2014 Alexandre Fayolle, Camptocamp SA # Copyright 2018-2020 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError class StockPickingBatch(models.Model): """This object allow to manage multiple stock.picking at the same time.""" # renamed stock.batch.picking -> stock.picking.batch _inherit = "stock.picking.batch" name = fields.Char( index=True, states={"draft": [("readonly", False)]}, ) date = fields.Date( required=True, readonly=True, index=True, states={"draft": [("readonly", False)], "in_progress": [("readonly", False)]}, default=fields.Date.context_today, help="date on which the batch picking is to be processed", ) user_id = fields.Many2one(index=True) use_oca_batch_validation = fields.Boolean( default=lambda self: self.env.company.use_oca_batch_validation, copy=False, ) active_picking_ids = fields.One2many( string="Active Pickings", comodel_name="stock.picking", inverse_name="batch_id", readonly=True, domain=[("state", "not in", ("cancel", "done"))], help="List of active picking managed by this batch.", ) notes = fields.Text(help="free form remarks") entire_package_ids = fields.Many2many( comodel_name="stock.quant.package", compute="_compute_entire_package_ids", help="Those are the entire packages of a picking shown in the view of " "operations", ) entire_package_detail_ids = fields.Many2many( comodel_name="stock.quant.package", compute="_compute_entire_package_ids", help="Those are the entire packages of a picking shown in the view of " "detailed operations", ) picking_count = fields.Integer( string="# Pickings", compute="_compute_picking_count", ) @api.depends("picking_ids") def _compute_entire_package_ids(self): for batch in self: batch.update( { "entire_package_ids": batch.use_oca_batch_validation and batch.picking_ids.mapped("entire_package_ids" or False), "entire_package_detail_ids": batch.use_oca_batch_validation and batch.picking_ids.mapped("entire_package_detail_ids" or False), } ) def _compute_picking_count(self): """Calculate number of pickings.""" groups = self.env["stock.picking"].read_group( domain=[("batch_id", "in", self.ids)], fields=["batch_id"], groupby=["batch_id"], ) counts = {g["batch_id"][0]: g["batch_id_count"] for g in groups} for batch in self: batch.picking_count = counts.get(batch.id, 0) def action_cancel(self): """Call action_cancel for all batches pickings and set batches states to cancel too only if user set OCA batch validation approach. """ if self.env.company.use_oca_batch_validation: self.mapped("picking_ids").action_cancel() self.state = "cancel" else: return super().action_cancel() def action_print_picking(self): pickings = self.mapped("picking_ids") if not pickings: raise UserError(_("Nothing to print.")) return self.env.ref( "stock_picking_batch_extended.action_report_batch_picking" ).report_action(self) def remove_undone_pickings(self): """Remove of this batch all pickings which state is not done / cancel.""" self.mapped("active_picking_ids").write({"batch_id": False}) def action_view_stock_picking(self): """This function returns an action that display existing pickings of given batch picking. """ self.ensure_one() pickings = self.mapped("picking_ids") action = self.env["ir.actions.act_window"]._for_xml_id( "stock.action_picking_tree_all" ) action["domain"] = [("id", "in", pickings.ids)] return action
37.442478
4,231
3,436
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import logging from odoo import api, fields, models from odoo.tools import float_is_zero _logger = logging.getLogger(__name__) class ReportPrintBatchPicking(models.AbstractModel): _name = "report.stock_picking_batch_extended.report_batch_picking" _description = "Report for Batch Picking" @api.model def key_level_0(self, operation): return operation.location_id.id, operation.location_dest_id.id @api.model def key_level_1(self, operation): return operation.product_id.id @api.model def new_level_0(self, operation): level_0_name = "{} \u21E8 {}".format( operation.location_id.name_get()[0][1], operation.location_dest_id.name_get()[0][1], ) return { "name": level_0_name, "location": operation.location_id, "location_dest": operation.location_dest_id, "l1_items": {}, } @api.model def _get_operation_qty(self, operation): return ( float_is_zero( operation.product_qty, precision_rounding=operation.product_uom_id.rounding, ) and operation.qty_done or operation.product_qty ) @api.model def new_level_1(self, operation): return { "product": operation.product_id, "product_qty": self._get_operation_qty(operation), "operations": operation, } @api.model def update_level_1(self, group_dict, operation): group_dict["product_qty"] += self._get_operation_qty(operation) group_dict["operations"] += operation @api.model def sort_level_0(self, rec_list): return sorted( rec_list, key=lambda rec: ( rec["location"].posx, rec["location"].posy, rec["location"].posz, rec["location"].name, ), ) @api.model def sort_level_1(self, rec_list): return sorted( rec_list, key=lambda rec: (rec["product"].default_code or "", rec["product"].id), ) @api.model def _get_grouped_data(self, batch): grouped_data = {} for op in batch.move_line_ids: l0_key = self.key_level_0(op) if l0_key not in grouped_data: grouped_data[l0_key] = self.new_level_0(op) l1_key = self.key_level_1(op) if l1_key in grouped_data[l0_key]["l1_items"]: self.update_level_1(grouped_data[l0_key]["l1_items"][l1_key], op) else: grouped_data[l0_key]["l1_items"][l1_key] = self.new_level_1(op) for l0_key in grouped_data.keys(): grouped_data[l0_key]["l1_items"] = self.sort_level_1( grouped_data[l0_key]["l1_items"].values() ) return self.sort_level_0(grouped_data.values()) @api.model def _get_report_values(self, docids, data=None): model = "stock.picking.batch" docs = self.env[model].browse(docids) return { "doc_ids": docids, "doc_model": model, "data": data, "docs": docs, "get_grouped_data": self._get_grouped_data, "now": fields.Datetime.now, }
31.814815
3,436
488
py
PYTHON
15.0
# Copyright 2020 Camptocamp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock Putaway Hooks", "summary": "Add hooks allowing modules to add more putaway strategies", "version": "15.0.1.0.0", "category": "Hidden", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Camptocamp, Odoo Community Association (OCA)", "license": "AGPL-3", "application": True, "depends": ["stock"], "data": [], }
32.533333
488
1,481
py
PYTHON
15.0
# Copyright 2022 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase from .common import PutawayHookCommon class TestPutawayHook(PutawayHookCommon, TransactionCase): def test_putaway_hook(self): """ The first location has no strategy nor alternative one The _get_putaway_strategy() should return that location """ strategy = self.location_internal_1._get_putaway_strategy(self.product) self.assertEqual( self.location_internal_1, strategy, ) def test_putaway_hook_context(self): """ The second location has no strategy nor alternative one But _putaway_<field> is passed in context. Should return the second location """ strategy = self.location_internal_1.with_context( _putaway_foo=True )._get_putaway_strategy(self.product) self.assertEqual( self.location_internal_1, strategy, ) def test_putaway_hook_alternative(self): """ The third location has no strategy but a foo alternative one Should return the location from the putaway """ strategy = self.location_internal_3.with_context( _putaway_foo=True )._get_putaway_strategy(self.product) self.assertEqual( self.location_internal_shelf_3, strategy, )
32.911111
1,481
437
py
PYTHON
15.0
# Copyright 2022 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class StockPutawayRule(models.Model): _inherit = "stock.putaway.rule" foo = fields.Boolean() class StockLocation(models.Model): _inherit = "stock.location" @property def _putaway_strategies(self): strategies = super()._putaway_strategies return strategies + ["foo"]
21.85
437
2,163
py
PYTHON
15.0
# Copyright 2022 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo_test_helper import FakeModelLoader class PutawayHookCommon: @classmethod def setUpClass(cls): super().setUpClass() cls.loader = FakeModelLoader(cls.env, cls.__module__) cls.loader.backup_registry() from .model import StockLocation, StockPutawayRule cls.loader.update_registry((StockPutawayRule,)) cls.loader.update_registry((StockLocation,)) cls.product = cls.env["product.product"].create( { "name": "Product", } ) cls.location_internal_1 = cls.env["stock.location"].create( { "name": "Internal for putaways", "usage": "internal", } ) cls.location_internal_2 = cls.env["stock.location"].create( { "name": "Internal 2 for putaways", "usage": "internal", } ) cls.location_internal_parent_3 = cls.env["stock.location"].create( { "name": "Parent 3 for putaways", "usage": "internal", } ) cls.location_internal_shelf_3 = cls.env["stock.location"].create( { "name": "Shelf 3 for putaways", "usage": "internal", "location_id": cls.location_internal_parent_3.id, } ) cls.location_internal_3 = cls.env["stock.location"].create( { "name": "Internal 3 for putaways", "usage": "internal", "location_id": cls.location_internal_parent_3.id, } ) cls.env["stock.putaway.rule"].create( { "foo": True, # The field that is passed through context "location_in_id": cls.location_internal_parent_3.id, "location_out_id": cls.location_internal_shelf_3.id, } ) @classmethod def tearDownClass(cls): cls.loader.restore_registry() return super().tearDownClass()
33.276923
2,163
4,166
py
PYTHON
15.0
# Copyright 2020 Camptocamp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from lxml import etree from odoo import models from odoo.osv.expression import AND, OR from odoo.tools.safe_eval import safe_eval from odoo.addons.base.models.ir_ui_view import ( transfer_modifiers_to_node, transfer_node_to_modifiers, ) class StockPutawayRule(models.Model): _inherit = "stock.putaway.rule" def fields_view_get( self, view_id=None, view_type="form", toolbar=False, submenu=False ): result = super().fields_view_get( view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu ) if result["name"] == "stock.putaway.rule.tree": result["arch"] = self._fields_view_get_adapt_attrs(result["arch"]) return result def _fields_view_get_add_exclusive_selection_attrs(self, doc): """Make the readonly and required attrs dynamic for putaway rules By default, product_id and category_id fields have static domains such as they are mutually exclusive: both fields are required, as soon as we select a product, the category becomes readonly and not required, if we select a category, the product becomes readonly and not required. If we add a third field, such as "route_id", the domains for the readonly and required attrs should now include "route_id" as well, and if we add a fourth field, again. We can't extend them this way from XML, so this method dynamically generate these domains and set it on the fields attrs. The only requirement is to have exclusive_selection set in the options of the field: :: <field name="route_id" options="{'no_create': True, 'no_open': True, 'exclusive_selection': True}" readonly="context.get('putaway_route', False)" force_save="1" /> Look in module stock_putaway_by_route (where this is tested as well). """ exclusive_fields = set() nodes = doc.xpath("//field[@options]") for field in nodes: options = safe_eval(field.attrib.get("options", "{}")) if options.get("exclusive_selection"): exclusive_fields.add(field) for field in exclusive_fields: readonly_domain = OR( [ [(other.attrib["name"], "!=", False)] for other in exclusive_fields if other != field ] ) required_domain = AND( [ [(other.attrib["name"], "=", False)] for other in exclusive_fields if other != field ] ) if field.attrib.get("attrs"): attrs = safe_eval(field.attrib["attrs"]) else: attrs = {} attrs["readonly"] = readonly_domain attrs["required"] = required_domain field.set("attrs", str(attrs)) modifiers = {} transfer_node_to_modifiers(field, modifiers, context=self.env.context) transfer_modifiers_to_node(modifiers, field) def _add_exclusive_selection(self, doc, field_name): nodes = doc.xpath("//field[@name='{}']".format(field_name)) for field in nodes: options = safe_eval(field.attrib.get("options", "{}")) options["exclusive_selection"] = True field.set("options", str(options)) def _fields_view_get_adapt_attrs(self, view_arch): doc = etree.XML(view_arch) # Add the "exclusive_selection" option on product_id and category_id # fields from core, so they are treated by # _fields_view_get_add_exclusive_selection_attrs self._add_exclusive_selection(doc, "product_id") self._add_exclusive_selection(doc, "category_id") self._fields_view_get_add_exclusive_selection_attrs(doc) new_view = etree.tostring(doc, encoding="unicode") return new_view
37.531532
4,166
4,072
py
PYTHON
15.0
# Copyright 2020 Camptocamp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models from odoo.fields import first class StockLocation(models.Model): _inherit = "stock.location" @property def _putaway_strategies(self): """List of plugged put-away strategies Each item is the key of the strategy. When applying the putaway, if no strategy is found for the product and the category (default ones), the method ``_alternative_putaway_strategy`` will loop over these keys. The key of a strategy must be the name of the field added on ``stock.putaway.rule``. For instance if the strategies are ["route_id", "foo"], the putaway will: * search a putaway for the product (core module) * if not found, search for the product category (core module) If None is found, the alternatives strategies are looked for: * if not found, search for route_id * if not found, search for foo """ return [] def _get_putaway_strategy( self, product, quantity=0, package=None, packaging=None, additional_qty=None ): """Extend the code method to add hooks * Call the alternative strategies lookups * Call a hook ``_putaway_strategy_finalizer`` after all the strategies * This should always return a result """ putaway_location = super()._get_putaway_strategy( product, quantity, package, packaging, additional_qty ) if putaway_location == self: putaway_location = self._alternative_putaway_strategy() return self._putaway_strategy_finalizer( putaway_location, product, quantity, package, packaging, additional_qty ) def _alternative_putaway_strategy(self): """Find a putaway according to the ``_putaway_strategies`` keys The methods that calls ``StockLocation._get_putaway_strategy have to pass in the context a key with the name ``_putaway_<KEY>``, where KEY is the name of the strategy. The value must be the value to match with the putaway rule. The value can be a unit, a recordset of any length or a list/tuple. In latter cases, the putaway rule is selected if its field match any value in the list/recordset. """ current_location = self putaway_location = self.browse() strategy_values = { field: self.env.context.get("_putaway_{}".format(field)) for field in self._putaway_strategies } # retain only the strategies for which we have a value provided in context available_strategies = [ strategy for strategy in self._putaway_strategies if strategy_values.get(strategy) ] if not available_strategies: return current_location while current_location and not putaway_location: # copy and reverse the strategies, so we pop them in their order strategies = available_strategies[::-1] while not putaway_location and strategies: strategy = strategies.pop() value = strategy_values[strategy] # Looking for a putaway from the strategy putaway_rules = current_location.putaway_rule_ids.filtered( lambda x: x[strategy] in value if isinstance(value, (models.BaseModel, list, tuple)) else x[strategy] == value ) putaway_location = first(putaway_rules).location_out_id current_location = current_location.location_id return putaway_location or self def _putaway_strategy_finalizer( self, putaway_location, product, quantity=0, package=None, packaging=None, additional_qty=None, ): """Hook for putaway called after the strategy lookup""" # by default, do nothing return putaway_location
38.056075
4,072
435
py
PYTHON
15.0
{ "name": "Stock Restrict Lot", "summary": "Base module that add back the concept of restrict lot on stock move", "version": "15.0.0.0.2", "category": "Warehouse Management", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Akretion, Odoo Community Association (OCA)", "maintainers": ["florian-dacosta"], "license": "AGPL-3", "installable": True, "depends": ["stock"], }
36.25
435
9,168
py
PYTHON
15.0
from odoo.tests.common import TransactionCase class TestRestrictLot(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.customer_loc = cls.env.ref("stock.stock_location_customers") cls.output_loc = cls.env.ref("stock.stock_location_output") cls.product = cls.env.ref("product.product_product_16") cls.product.write({"tracking": "lot"}) cls.warehouse = cls.env.ref("stock.warehouse0") cls.warehouse.write({"delivery_steps": "pick_ship"}) cls.lot = cls.env["stock.production.lot"].create( { "name": "lot1", "product_id": cls.product.id, "company_id": cls.warehouse.company_id.id, } ) def test_00_move_restrict_lot_propagation(self): move = self.env["stock.move"].create( { "product_id": self.product.id, "location_id": self.output_loc.id, "location_dest_id": self.customer_loc.id, "product_uom_qty": 1, "product_uom": self.product.uom_id.id, "name": "test", "procure_method": "make_to_order", "warehouse_id": self.warehouse.id, "route_ids": [(6, 0, self.warehouse.delivery_route_id.ids)], "restrict_lot_id": self.lot.id, } ) move._action_confirm() orig_move = move.move_orig_ids self.assertEqual(orig_move.restrict_lot_id.id, self.lot.id) def test_01_move_split_and_copy(self): move = self.env["stock.move"].create( { "product_id": self.product.id, "location_id": self.output_loc.id, "location_dest_id": self.customer_loc.id, "product_uom_qty": 2, "product_uom": self.product.uom_id.id, "name": "test", "procure_method": "make_to_stock", "warehouse_id": self.warehouse.id, "route_ids": [(6, 0, self.warehouse.delivery_route_id.ids)], "restrict_lot_id": self.lot.id, } ) move._action_confirm() vals_list = move._split(1) new_move = self.env["stock.move"].create(vals_list) self.assertEqual(new_move.restrict_lot_id.id, move.restrict_lot_id.id) other_move = move.copy() self.assertFalse(other_move.restrict_lot_id.id) def _update_product_stock(self, qty, lot_id=False, location=None): quant = self.env["stock.quant"].create( { "product_id": self.product.id, "location_id": ( location.id if location else self.warehouse.lot_stock_id.id ), "lot_id": lot_id, "inventory_quantity": qty, } ) quant.action_apply_inventory() def test_02_move_restrict_lot_reservation(self): lot2 = self.env["stock.production.lot"].create( { "name": "lot2", "product_id": self.product.id, "company_id": self.warehouse.company_id.id, } ) self._update_product_stock(1, lot2.id) move = self.env["stock.move"].create( { "product_id": self.product.id, "location_id": self.warehouse.lot_stock_id.id, "location_dest_id": self.customer_loc.id, "product_uom_qty": 1, "product_uom": self.product.uom_id.id, "name": "test", "warehouse_id": self.warehouse.id, "restrict_lot_id": self.lot.id, } ) move._action_confirm() move._action_assign() # move should not reserve wrong free lot self.assertEqual(move.state, "confirmed") self._update_product_stock(1, self.lot.id) move._action_assign() self.assertEqual(move.state, "assigned") self.assertEqual(move.move_line_ids.lot_id.id, self.lot.id) def test_procurement_with_2_steps_output(self): # make warehouse output in two step self.env["res.config.settings"].write( { "group_stock_adv_location": True, "group_stock_multi_locations": True, } ) warehouse = self.env["stock.warehouse"].search( [("company_id", "=", self.env.company.id)], limit=1 ) warehouse.delivery_steps = "pick_ship" self.product.categ_id.route_ids |= self.env["stock.location.route"].search( [("name", "ilike", "deliver in 2")] ) # self.env["stock.warehouse"].write(dict(delivery_steps='pick_ship',)) location_1 = self.env["stock.location"].create( {"name": "loc1", "location_id": warehouse.lot_stock_id.id} ) location_2 = self.env["stock.location"].create( {"name": "loc2", "location_id": warehouse.lot_stock_id.id} ) # create goods in stock lot2 = self.env["stock.production.lot"].create( { "name": "lot 2", "product_id": self.product.id, "company_id": self.warehouse.company_id.id, } ) self._update_product_stock(10, self.lot.id, location=location_1) self._update_product_stock(10, self.lot.id, location=location_2) self._update_product_stock(5, lot2.id, location=location_1) self._update_product_stock(25, lot2.id, location=location_2) # create a procurement with two lines of same product with different lots procurement_group = self.env["procurement.group"].create( {"name": "My procurement", "move_type": "one"} ) self.env["procurement.group"].run( [ self.env["procurement.group"].Procurement( self.product, 15, self.product.uom_id, self.customer_loc, "a name", "an origin restrict on lot 1", self.env.company, { "group_id": procurement_group, "restrict_lot_id": self.lot.id, }, ), self.env["procurement.group"].Procurement( self.product, 30, self.product.uom_id, self.customer_loc, "a name", "an origin restrict on lot 2", self.env.company, { "group_id": procurement_group, "restrict_lot_id": lot2.id, }, ), ] ) # make sure in the two stock picking we get right quantities # for expected lot and locations def assert_move_qty_per_lot(moves, expect_lot, expect_qty): concern_move = moves.filtered(lambda mov: mov.restrict_lot_id == expect_lot) self.assertEqual(len(concern_move), 1) self.assertEqual(concern_move.product_uom_qty, expect_qty) def assert_move_line_per_lot_and_location( moves, expect_lot, expect_from_location, expect_reserved_qty ): concern_move_line = moves.filtered( lambda mov: mov.lot_id == expect_lot and mov.location_id == expect_from_location ) self.assertEqual(len(concern_move_line), 1) self.assertEqual(concern_move_line.product_uom_qty, expect_reserved_qty) pickings = self.env["stock.picking"].search( [("group_id", "=", procurement_group.id)] ) self.assertEqual(len(pickings), 2) delivery = pickings.filtered( lambda pick: pick.picking_type_id.code == "outgoing" ) pick = pickings.filtered(lambda pick: pick.picking_type_id.code == "internal") self.assertEqual(delivery.state, "waiting") self.assertEqual(len(delivery.move_ids_without_package), 2) assert_move_qty_per_lot(delivery.move_ids_without_package, self.lot, 15) assert_move_qty_per_lot(delivery.move_ids_without_package, lot2, 30) pick.action_assign() self.assertEqual(pick.state, "assigned") self.assertEqual(len(pick.move_ids_without_package), 2) assert_move_qty_per_lot(pick.move_ids_without_package, self.lot, 15) assert_move_qty_per_lot(pick.move_ids_without_package, lot2, 30) assert_move_line_per_lot_and_location( pick.move_line_ids_without_package, self.lot, location_1, 10 ) assert_move_line_per_lot_and_location( pick.move_line_ids_without_package, self.lot, location_2, 5 ) assert_move_line_per_lot_and_location( pick.move_line_ids_without_package, lot2, location_1, 5 ) assert_move_line_per_lot_and_location( pick.move_line_ids_without_package, lot2, location_2, 25 )
40.387665
9,168
2,934
py
PYTHON
15.0
from odoo import _, api, exceptions, fields, models class StockMove(models.Model): _inherit = "stock.move" # seems better to not copy this field except when a move is splitted, because a move # can be copied in multiple different occasions and could even be copied with a # different product... restrict_lot_id = fields.Many2one( "stock.production.lot", string="Restrict Lot", copy=False ) def _prepare_procurement_values(self): vals = super()._prepare_procurement_values() vals["restrict_lot_id"] = self.restrict_lot_id.id return vals @api.model def _prepare_merge_moves_distinct_fields(self): distinct_fields = super()._prepare_merge_moves_distinct_fields() distinct_fields.append("restrict_lot_id") return distinct_fields def _prepare_move_line_vals(self, quantity=None, reserved_quant=None): vals = super()._prepare_move_line_vals( quantity=quantity, reserved_quant=reserved_quant ) if self.restrict_lot_id: if ( "lot_id" in vals and vals["lot_id"] is not False and vals["lot_id"] != self.restrict_lot_id.id ): raise exceptions.UserError( _( "Inconsistencies between reserved quant and lot restriction on " "stock move" ) ) vals["lot_id"] = self.restrict_lot_id.id return vals def _get_available_quantity( self, location_id, lot_id=None, package_id=None, owner_id=None, strict=False, allow_negative=False, ): self.ensure_one() if not lot_id and self.restrict_lot_id: lot_id = self.restrict_lot_id return super()._get_available_quantity( location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict, allow_negative=allow_negative, ) def _update_reserved_quantity( self, need, available_quantity, location_id, lot_id=None, package_id=None, owner_id=None, strict=True, ): self.ensure_one() if self.restrict_lot_id: lot_id = self.restrict_lot_id return super()._update_reserved_quantity( need, available_quantity, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict, ) def _split(self, qty, restrict_partner_id=False): vals_list = super()._split(qty, restrict_partner_id=restrict_partner_id) if vals_list and self.restrict_lot_id: vals_list[0]["restrict_lot_id"] = self.restrict_lot_id.id return vals_list
31.891304
2,934
236
py
PYTHON
15.0
from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _get_custom_move_fields(self): fields = super()._get_custom_move_fields() fields += ["restrict_lot_id"] return fields
23.6
236
570
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Carlos Dauden # Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Move Quick Lot", "summary": "Set lot name and end date directly on picking operations", "version": "15.0.1.0.0", "category": "Stock", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["product_expiry"], "data": ["views/stock_view.xml"], }
38
570
2,361
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Carlos Dauden # Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestStockMoveQuickLot(TransactionCase): @classmethod def setUpClass(cls): super(TestStockMoveQuickLot, cls).setUpClass() cls.supplier_location = cls.env.ref("stock.stock_location_suppliers") cls.stock_location = cls.env.ref("stock.stock_location_stock") cls.picking_type_in = cls.env.ref("stock.picking_type_in") cls.picking = cls.env["stock.picking"].create( { "picking_type_id": cls.picking_type_in.id, "location_id": cls.supplier_location.id, "location_dest_id": cls.stock_location.id, } ) cls.product = cls.env["product.product"].create( {"name": "Product for test", "type": "product", "tracking": "lot"} ) cls.env["stock.move"].create( { "name": "a move", "product_id": cls.product.id, "product_uom_qty": 5.0, "product_uom": cls.product.uom_id.id, "picking_id": cls.picking.id, "location_id": cls.supplier_location.id, "location_dest_id": cls.stock_location.id, } ) cls.picking.action_assign() cls.move_line = cls.picking.move_lines[:1] def test_quick_input(self): self.assertTrue(self.move_line) with self.assertRaises(ValidationError): self.move_line.onchange_line_lot_name() self.move_line.line_lot_name = "SN99999999999" self.move_line._compute_line_lot_name() self.move_line.onchange_line_lot_name() # Try again self.move_line.expiration_date = "2030-12-31" lot = self.move_line.move_line_ids[:1].lot_id self.assertTrue(lot) self.move_line.line_lot_name = False self.move_line.line_lot_name = "SN99999999998" lot2 = self.move_line.move_line_ids[:1].lot_id self.assertNotEqual(lot, lot2) self.move_line.expiration_date = False self.move_line.expiration_date = "2030-12-28" self.assertEqual(str(lot2.expiration_date), "2030-12-28 00:00:00")
42.160714
2,361
2,891
py
PYTHON
15.0
# Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class StockMove(models.Model): _inherit = "stock.move" line_lot_name = fields.Char( string="Lot Name", compute="_compute_line_lot_name", inverse="_inverse_line_lot_name", ) expiration_date = fields.Datetime( string="End of Life Date", help="This is the date on which the goods with this Serial Number may " "become dangerous and must not be consumed.", compute="_compute_expiration_date", inverse="_inverse_expiration_date", ) @api.onchange("line_lot_name") def onchange_line_lot_name(self): lot = self.production_lot_from_name(create_lot=False) self.expiration_date = lot.expiration_date def _compute_line_lot_name(self): for line in self: line.line_lot_name = ", ".join( lot.name for lot in line.mapped("move_line_ids.lot_id") ) def _inverse_line_lot_name(self): for line in self: if not line.line_lot_name: continue lot = line.production_lot_from_name() if line.move_line_ids: if line.move_line_ids.lot_id != lot: line.move_line_ids.lot_id = lot def _compute_expiration_date(self): for line in self: line.expiration_date = line.move_line_ids[:1].lot_id.expiration_date def _inverse_expiration_date(self): for line in self: if not line.expiration_date: continue lot = line.production_lot_from_name() if lot and lot.expiration_date != line.expiration_date: lot.expiration_date = line.expiration_date def production_lot_from_name(self, create_lot=True): StockProductionLot = self.env["stock.production.lot"] if not self.line_lot_name: if self.move_line_ids: raise ValidationError(_("Open detail to remove lot")) else: return StockProductionLot.browse() if len(self.move_line_ids) > 1: raise ValidationError(_("Go to lots to change data")) lot = StockProductionLot.search( [ ("product_id", "=", self.product_id.id), ("name", "=", self.line_lot_name), ], limit=1, ) if not lot and create_lot: lot = lot.create( { "name": self.line_lot_name, "product_id": self.product_id.id, "expiration_date": self.expiration_date, "company_id": self.company_id.id, } ) return lot
35.691358
2,891
727
py
PYTHON
15.0
# Copyright 2020 Carlos Dauden - Tecnativa # Copyright 2020 Sergio Teruel - Tecnativa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Owner Restriction", "summary": "Do not reserve quantity with assigned owner", "version": "15.0.1.1.0", "development_status": "Beta", "category": "stock", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "data": ["views/stock_picking_type_views.xml", "views/stock_picking_views.xml"], "depends": ["stock"], "post_init_hook": "set_default_owner_restriction", "uninstall_hook": "uninstall_hook", }
40.388889
727
7,229
py
PYTHON
15.0
# Copyright 2020 Carlos Dauden - Tecnativa # Copyright 2020 Sergio Teruel - Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestStockOwnerRestriction(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) # models cls.picking_model = cls.env["stock.picking"] cls.move_model = cls.env["stock.move"] cls.ResPartner = cls.env["res.partner"] # warehouse and picking types cls.warehouse = cls.env.ref("stock.stock_warehouse_shop0") cls.picking_type_in = cls.env.ref("stock.chi_picking_type_in") cls.picking_type_out = cls.env.ref("stock.chi_picking_type_out") cls.supplier_location = cls.env.ref("stock.stock_location_suppliers") cls.customer_location = cls.env.ref("stock.stock_location_customers") # Allow all companies for OdooBot user and set default user company # to warehouse company companies = cls.env["res.company"].search([]) cls.env.user.company_ids = [(6, 0, companies.ids)] cls.env.user.company_id = cls.warehouse.company_id # customer cls.customer = cls.ResPartner.create({"name": "Customer test"}) # Owner cls.owner = cls.ResPartner.create({"name": "Owner test"}) # products cls.product = cls.env["product.product"].create( {"name": "Test restriction", "type": "product"} ) quant_vals = { "product_id": cls.product.id, "location_id": cls.picking_type_out.default_location_src_id.id, "quantity": 500.00, } # Create quants without owner cls.env["stock.quant"].create(quant_vals) # Create quants with owner cls.env["stock.quant"].create(dict(quant_vals, owner_id=cls.owner.id)) cls.picking_out = cls.picking_model.with_context( default_picking_type_id=cls.picking_type_out.id ).create( { "partner_id": cls.customer.id, "picking_type_id": cls.picking_type_out.id, "location_id": cls.picking_type_out.default_location_src_id.id, "location_dest_id": cls.customer_location.id, } ) def test_product_qty_available(self): # Quants with owner assigned are not available self.assertEqual(self.product.qty_available, 500.00) self.product.invalidate_cache() self.assertEqual( self.product.with_context(skip_restricted_owner=True).qty_available, 1000.00 ) def test_restrict_reserve_qty(self): # Restrict quants from one owner to other customer self.move_model.create( dict( product_id=self.product.id, picking_id=self.picking_out.id, name=self.product.display_name, picking_type_id=self.picking_type_out.id, product_uom_qty=1000.00, location_id=self.picking_type_out.default_location_src_id.id, location_dest_id=self.customer_location.id, product_uom=self.product.uom_id.id, ) ) # Set restriction options on picking type self.picking_type_out.owner_restriction = "standard_behavior" self.picking_out.action_confirm() self.picking_out.action_assign() # For standard_behavior Odoo does not take into account the owner in # quants, so Odoo has been reserved 500 quantities without owner and # 500 quantities with owner self.assertEqual(self.picking_out.move_lines.reserved_availability, 1000.00) self.assertEqual(len(self.picking_out.move_line_ids), 2) self.assertEqual(self.picking_out.move_line_ids.mapped("owner_id"), self.owner) # Set restriction options on picking type to get only quants without # owner assigned self.picking_type_out.owner_restriction = "unassigned_owner" self.picking_out.do_unreserve() self.picking_out.action_assign() self.assertEqual(self.picking_out.move_lines.reserved_availability, 500.00) self.assertEqual(len(self.picking_out.move_line_ids), 1) self.assertFalse(self.picking_out.move_line_ids.mapped("owner_id")) # Set restriction options on picking type to get only quants with an # owner assigned. # The picking partner has not quants assigned so the picking is in # confirm state self.picking_type_out.owner_restriction = "picking_partner" self.picking_out.do_unreserve() self.picking_out.action_assign() self.assertEqual(self.picking_out.move_lines.reserved_availability, 0.0) self.assertEqual(len(self.picking_out.move_line_ids), 0) self.assertEqual(self.picking_out.state, "confirmed") # Set restriction options on picking type to get only quants with an # owner assigned. # The picking partner has quants assigned so the picking is in # assigned state self.picking_type_out.owner_restriction = "picking_partner" self.picking_out.partner_id = self.owner self.picking_out.do_unreserve() self.picking_out.action_assign() self.assertEqual(self.picking_out.move_lines.reserved_availability, 500.00) self.assertEqual(len(self.picking_out.move_line_ids), 1) self.assertTrue(self.picking_out.move_line_ids.mapped("owner_id")) self.assertEqual(self.picking_out.state, "assigned") # Set restriction options on picking type to get only quants with an # owner assigned. # The picking partner has quants assigned and there ara unassigned quants # so the picking is in assigned state and with 1000 reserved units self.picking_type_out.owner_restriction = "partner_or_unassigned" self.picking_out.do_unreserve() self.picking_out.action_assign() self.assertEqual(self.picking_out.move_lines.reserved_availability, 1000.00) self.assertEqual(len(self.picking_out.move_line_ids), 2) self.assertEqual(self.picking_out.move_line_ids.mapped("owner_id"), self.owner) # Set restriction options on picking type to get only quants with an # owner assigned. # The picking partner has not quants assigned but there are unassigned quants # so the picking is in assigned state with 500 reserved units self.picking_out.partner_id = False self.picking_out.do_unreserve() self.picking_out.action_assign() self.assertEqual(self.picking_out.move_lines.reserved_availability, 500.00) self.assertEqual(len(self.picking_out.move_line_ids), 1) def test_search_qty(self): products = self.env["product.product"].search( [("id", "=", self.product.id), ("qty_available", ">", 500.00)] ) self.assertFalse(products) products = self.env["product.product"].search( [("id", "=", self.product.id), ("qty_available", ">", 499.00)] ) self.assertTrue(products)
46.63871
7,229
2,226
py
PYTHON
15.0
# Copyright 2020 Carlos Dauden - Tecnativa # Copyright 2020 Sergio Teruel - Tecnativa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models from odoo.osv import expression class StockQuant(models.Model): _inherit = "stock.quant" def _gather( self, product_id, location_id, lot_id=None, package_id=None, owner_id=None, strict=False, ): records = super()._gather( product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict, ) restricted_owner_id = self.env.context.get("force_restricted_owner_id", None) if owner_id is None or restricted_owner_id is None: return records return records.filtered( lambda q: q.owner_id == (restricted_owner_id or self.env["res.partner"]) ) @api.model def read_group( self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True ): restricted_owner_id = self.env.context.get("force_restricted_owner_id", None) if restricted_owner_id is not None: domain = expression.AND([domain, [("owner_id", "=", restricted_owner_id)]]) return super(StockQuant, self).read_group( domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy, ) @api.model def _get_available_quantity( self, product_id, location_id, lot_id=None, package_id=None, owner_id=None, strict=False, allow_negative=False, ): restricted_owner_id = self.env.context.get("force_restricted_owner_id", None) if not owner_id and restricted_owner_id is not None: owner_id = restricted_owner_id return super()._get_available_quantity( product_id, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict, allow_negative=allow_negative, )
30.081081
2,226
606
py
PYTHON
15.0
# Copyright 2020 Carlos Dauden - Tecnativa # Copyright 2020 Sergio Teruel - Tecnativa # 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" owner_restriction = fields.Selection( [ ("standard_behavior", "Standard behavior"), ("unassigned_owner", "Unassigned owner"), ("picking_partner", "Picking partner"), ("partner_or_unassigned", "Picking partner or unassigned owner"), ], default="standard_behavior", )
33.666667
606
2,335
py
PYTHON
15.0
# Copyright 2020 Carlos Dauden - Tecnativa # Copyright 2020 Sergio Teruel - Tecnativa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from collections import defaultdict from odoo import models class StockMove(models.Model): _inherit = "stock.move" def _action_assign(self): # Split moves by picking type owner behavior restriction to process # moves depending of their owners moves = self.filtered( lambda m: m.picking_type_id.owner_restriction == "standard_behavior" ) res = super(StockMove, moves)._action_assign() dict_key = defaultdict(lambda: self.env["stock.move"]) for move in self - moves: if move.picking_type_id.owner_restriction == "unassigned_owner": dict_key[False] |= move else: dict_key[move.picking_id.owner_id or move.picking_id.partner_id] |= move for owner_id, moves_to_assign in dict_key.items(): super( StockMove, moves_to_assign.with_context(force_restricted_owner_id=owner_id), )._action_assign() if ( owner_id and moves_to_assign.picking_type_id.owner_restriction == "partner_or_unassigned" and sum( move.reserved_availability - move.product_uom_qty for move in moves_to_assign ) < 0 ): super( StockMove, moves_to_assign.with_context(force_restricted_owner_id=False), )._action_assign() return res def _update_reserved_quantity( self, need, available_quantity, location_id, lot_id=None, package_id=None, owner_id=None, strict=True, ): restricted_owner_id = self.env.context.get("force_restricted_owner_id", None) if not owner_id and restricted_owner_id is not None: owner_id = restricted_owner_id return super()._update_reserved_quantity( need, available_quantity, location_id, lot_id=lot_id, package_id=package_id, owner_id=owner_id, strict=strict, )
34.850746
2,335
337
py
PYTHON
15.0
# Copyright 2020 Carlos Dauden - Tecnativa # Copyright 2020 Sergio Teruel - Tecnativa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class StockPicking(models.Model): _inherit = "stock.picking" owner_restriction = fields.Selection(related="picking_type_id.owner_restriction")
33.7
337
1,481
py
PYTHON
15.0
# Copyright 2020 Carlos Dauden - Tecnativa # Copyright 2020 Sergio Teruel - Tecnativa # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class ProductProduct(models.Model): _inherit = "product.product" def _compute_quantities_dict( self, lot_id, owner_id, package_id, from_date=False, to_date=False ): if self.env.context.get("skip_restricted_owner"): return super()._compute_quantities_dict( lot_id, owner_id, package_id, from_date=from_date, to_date=to_date ) restricted_owner_id = self.env.context.get("force_restricted_owner_id", None) if owner_id is None and restricted_owner_id is None: # Force owner to False if is None owner_id = False elif restricted_owner_id: owner_id = restricted_owner_id return super()._compute_quantities_dict( lot_id, owner_id, package_id, from_date=from_date, to_date=to_date ) def _search_qty_available_new( self, operator, value, lot_id=False, owner_id=False, package_id=False ): new_self = self if not owner_id: new_self = self.with_context(force_restricted_owner_id=False) # Pass context variable to add domain in read group return super(ProductProduct, new_self)._search_qty_available_new( operator, value, lot_id=lot_id, owner_id=owner_id, package_id=package_id )
41.138889
1,481
446
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Stock Picking Return Restricted Qty", "summary": "Restrict the return to delivered quantity", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-workflow", "depends": ["stock"], "data": [], }
34.307692
446
3,369
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.exceptions import UserError from odoo.tests import Form, common class StockPickingReturnRestrictedQtyTest(common.TransactionCase): def setUp(self): super().setUp() partner = self.env["res.partner"].create({"name": "Test"}) product = self.env["product.product"].create( {"name": "test_product", "type": "product"} ) picking_type_out = self.env.ref("stock.picking_type_out") stock_location = self.env.ref("stock.stock_location_stock") customer_location = self.env.ref("stock.stock_location_customers") self.picking = self.env["stock.picking"].create( { "partner_id": partner.id, "picking_type_id": picking_type_out.id, "location_id": stock_location.id, "location_dest_id": customer_location.id, "move_lines": [ ( 0, 0, { "name": product.name, "product_id": product.id, "product_uom_qty": 20, "product_uom": product.uom_id.id, "location_id": stock_location.id, "location_dest_id": customer_location.id, }, ) ], } ) self.picking.action_confirm() self.picking.action_assign() self.picking.move_lines[:1].quantity_done = 20 self.picking.button_validate() def get_return_picking_wizard(self, picking): stock_return_picking_form = Form( self.env["stock.return.picking"].with_context( active_ids=picking.ids, active_id=picking.ids[0], active_model="stock.picking", ) ) return stock_return_picking_form.save() def test_return_not_allowed(self): """On this test we create a return picking with more quantity than the quantity that client have on his hand""" return_picking = self.get_return_picking_wizard(self.picking) self.assertEqual(return_picking.product_return_moves.quantity, 20) return_picking.product_return_moves.quantity = 30 with self.assertRaises(UserError): return_picking._create_returns() def test_multiple_return(self): """On this test we are going to follow a sequence that a client can follow if he tries to return a product""" wiz = self.get_return_picking_wizard(self.picking) wiz.product_return_moves.quantity = 10 picking_returned_id = wiz._create_returns()[0] picking_returned = self.env["stock.picking"].browse(picking_returned_id) wiz = self.get_return_picking_wizard(self.picking) self.assertEqual(wiz.product_return_moves.quantity, 10) picking_returned._action_done() wiz = self.get_return_picking_wizard(self.picking) self.assertEqual(wiz.product_return_moves.quantity, 10) wiz.product_return_moves.quantity = 80 with self.assertRaises(UserError): wiz.product_return_moves._onchange_quantity()
41.592593
3,369
2,333
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import UserError from odoo.tools import float_compare class ReturnPicking(models.TransientModel): _inherit = "stock.return.picking" @api.model def _prepare_stock_return_picking_line_vals_from_move(self, stock_move): val = super()._prepare_stock_return_picking_line_vals_from_move(stock_move) return_lines = self.env["stock.return.picking.line"] val["quantity"] = return_lines.get_returned_restricted_quantity(stock_move) return val def _create_returns(self): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) for return_line in self.product_return_moves: quantity = return_line.get_returned_restricted_quantity(return_line.move_id) if ( float_compare( return_line.quantity, quantity, precision_digits=precision ) > 0 ): raise UserError( _("Return more quantities than delivered is not allowed.") ) return super()._create_returns() class ReturnPickingLine(models.TransientModel): _inherit = "stock.return.picking.line" @api.onchange("quantity") def _onchange_quantity(self): qty = self.get_returned_restricted_quantity(self.move_id) if self.quantity > qty: raise UserError(_("Return more quantities than delivered is not allowed.")) def get_returned_restricted_quantity(self, stock_move): """This function is created to know how many products have the person who tries to create a return picking on his hand.""" qty = stock_move.product_qty for line in stock_move.move_dest_ids.mapped("move_line_ids"): if ( line.move_id.origin_returned_move_id and line.move_id.origin_returned_move_id != stock_move ): continue if line.state in {"partially_available", "assigned"}: qty -= line.product_qty elif line.state == "done": qty -= line.qty_done return max(qty, 0.0)
38.245902
2,333
828
py
PYTHON
15.0
# Copyright 2013-2015 Camptocamp SA - Nicolas Bessi # Copyright 2013-2015 Camptocamp SA - Guewen Baconnier # Copyright 2013-2015 Camptocamp SA - Yannick Vaucher # Copyright 2017 Tecnativa - Vicent Cubells # Copyright 2021 ForgeFlow # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Split picking", "summary": "Split a picking in two not transferred pickings", "version": "15.0.1.1.2", "category": "Inventory", "author": "Camptocamp, " "Tecnativa, " "ForgeFlow S.L., " "Odoo Community Association (OCA),", "license": "AGPL-3", "website": "https://github.com/OCA/stock-logistics-workflow", "depends": ["stock"], "data": [ "security/ir.model.access.csv", "wizards/stock_split_picking.xml", "views/stock_partial_picking.xml", ], }
34.5
828
6,840
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Vicent Cubells <vicent.cubells@tecnativa.com> # Copyright 2018 Camptocamp SA - Julien Coux # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.exceptions import UserError from odoo.tests.common import TransactionCase class TestStockSplitPicking(TransactionCase): @classmethod def setUpClass(cls): super(TestStockSplitPicking, cls).setUpClass() cls.src_location = cls.env.ref("stock.stock_location_stock") cls.dest_location = cls.env.ref("stock.stock_location_customers") cls.product = cls.env["product.product"].create({"name": "Test product"}) cls.product_2 = cls.env["product.product"].create({"name": "Test product 2"}) cls.partner = cls.env["res.partner"].create({"name": "Test partner"}) cls.picking = cls.env["stock.picking"].create( { "partner_id": cls.partner.id, "picking_type_id": cls.env.ref("stock.picking_type_out").id, "location_id": cls.src_location.id, "location_dest_id": cls.dest_location.id, } ) def _create_stock_move(product): return cls.env["stock.move"].create( { "name": "/", "picking_id": cls.picking.id, "product_id": product.id, "product_uom_qty": 10, "product_uom": product.uom_id.id, "location_id": cls.src_location.id, "location_dest_id": cls.dest_location.id, } ) cls.move = _create_stock_move(cls.product) cls.move_2 = _create_stock_move(cls.product_2) def test_stock_split_picking(self): # Picking state is draft self.assertEqual(self.picking.state, "draft") # We can't split a draft picking with self.assertRaises(UserError): self.picking.split_process() # Confirm picking self.picking.action_confirm() # We can't split an unassigned picking with self.assertRaises(UserError): self.picking.split_process() # We assign quantities in order to split self.picking.action_assign() move_line = self.env["stock.move.line"].search( [ ("picking_id", "=", self.picking.id), ("product_id", "=", self.product.id), ], limit=1, ) move_line_2 = self.env["stock.move.line"].search( [ ("picking_id", "=", self.picking.id), ("product_id", "=", self.product_2.id), ], limit=1, ) move_line.qty_done = 4.0 # Split picking: 4 and 6 # import pdb; pdb.set_trace() self.picking.split_process() # We have a picking with 4 units in state assigned self.assertAlmostEqual(move_line.qty_done, 4.0) self.assertAlmostEqual(move_line.product_qty, 4.0) self.assertAlmostEqual(move_line.product_uom_qty, 4.0) self.assertAlmostEqual(self.move.quantity_done, 4.0) self.assertAlmostEqual(self.move.product_qty, 4.0) self.assertAlmostEqual(self.move.product_uom_qty, 4.0) self.assertEqual(move_line.picking_id, self.picking) self.assertEqual(self.move.picking_id, self.picking) # move/move_line with no done qty no longer belongs to the original picking. self.assertNotEqual(move_line_2.picking_id, self.picking) self.assertNotEqual(self.move_2.picking_id, self.picking) self.assertEqual(self.picking.state, "assigned") # An another one with 6 units in state assigned new_picking = self.env["stock.picking"].search( [("backorder_id", "=", self.picking.id)], limit=1 ) move_line = self.env["stock.move.line"].search( [("picking_id", "=", new_picking.id), ("product_id", "=", self.product.id)], limit=1, ) move_line_2 = self.env["stock.move.line"].search( [ ("picking_id", "=", new_picking.id), ("product_id", "=", self.product_2.id), ], limit=1, ) self.assertAlmostEqual(move_line.qty_done, 0.0) self.assertAlmostEqual(move_line.product_qty, 6.0) self.assertAlmostEqual(move_line.product_uom_qty, 6.0) self.assertAlmostEqual(move_line_2.qty_done, 0.0) self.assertAlmostEqual(move_line_2.product_qty, 10.0) self.assertAlmostEqual(move_line_2.product_uom_qty, 10.0) move = self.env["stock.move"].search( [("picking_id", "=", new_picking.id), ("product_id", "=", self.product.id)], limit=1, ) move_2 = self.env["stock.move"].search( [ ("picking_id", "=", new_picking.id), ("product_id", "=", self.product_2.id), ], limit=1, ) self.assertAlmostEqual(move.quantity_done, 0.0) self.assertAlmostEqual(move.product_qty, 6.0) self.assertAlmostEqual(move.product_uom_qty, 6.0) self.assertAlmostEqual(move_2.quantity_done, 0.0) self.assertAlmostEqual(move_2.product_qty, 10.0) self.assertAlmostEqual(move_2.product_uom_qty, 10.0) self.assertEqual(new_picking.state, "assigned") def test_stock_split_picking_wizard_move(self): self.move2 = self.move.copy() self.assertEqual(self.move2.picking_id, self.picking) wizard = ( self.env["stock.split.picking"] .with_context(active_ids=self.picking.ids) .create({"mode": "move"}) ) wizard.action_apply() self.assertNotEqual(self.move2.picking_id, self.picking) self.assertEqual(self.move.picking_id, self.picking) def test_stock_split_picking_wizard_selection(self): self.move2 = self.move.copy() self.assertEqual(self.move2.picking_id, self.picking) wizard = ( self.env["stock.split.picking"] .with_context(active_ids=self.picking.ids) .create({"mode": "selection", "move_ids": [(6, False, self.move2.ids)]}) ) wizard.action_apply() self.assertNotEqual(self.move2.picking_id, self.picking) self.assertEqual(self.move.picking_id, self.picking) def test_stock_picking_split_off_moves(self): with self.assertRaises(UserError): # fails because we can't split off all lines self.picking._split_off_moves(self.picking.move_lines) with self.assertRaises(UserError): # fails because we can't split cancelled pickings self.picking.action_cancel() self.picking._split_off_moves(self.picking.move_lines)
40.958084
6,840
4,911
py
PYTHON
15.0
# Copyright 2013-2015 Camptocamp SA - Nicolas Bessi # Copyright 2018 Camptocamp SA - Julien Coux # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import UserError from odoo.tools.float_utils import float_compare class StockPicking(models.Model): """Adds picking split without done state.""" _inherit = "stock.picking" def _check_split_process(self): # Check the picking state and condition before split if self.state == "draft": raise UserError(_("Mark as todo this picking please.")) if all([x.qty_done == 0.0 for x in self.move_line_ids]): raise UserError( _( "You must enter done quantity in order to split your " "picking in several ones." ) ) def split_process(self): """Use to trigger the wizard from button with correct context""" for picking in self: picking._check_split_process() # Split moves considering the qty_done on moves new_moves = self.env["stock.move"] for move in picking.move_lines: rounding = move.product_uom.rounding qty_done = move.quantity_done qty_initial = move.product_uom_qty qty_diff_compare = float_compare( qty_done, qty_initial, precision_rounding=rounding ) if qty_diff_compare < 0: qty_split = qty_initial - qty_done qty_uom_split = move.product_uom._compute_quantity( qty_split, move.product_id.uom_id, rounding_method="HALF-UP" ) # Empty list is returned for moves with zero qty_done. new_move_vals = move._split(qty_uom_split) if new_move_vals: for move_line in move.move_line_ids: if move_line.product_qty and move_line.qty_done: # To avoid an error # when picking is partially available try: move_line.write( {"product_uom_qty": move_line.qty_done} ) except UserError: continue new_move = self.env["stock.move"].create(new_move_vals) # Moves with no qty_done should be moved to the new picking. else: new_move = move new_move._action_confirm(merge=False) new_moves |= new_move # If we have new moves to move, create the backorder picking if new_moves: backorder_picking = picking._create_split_backorder() new_moves.write({"picking_id": backorder_picking.id}) new_moves.mapped("move_line_ids").write( {"picking_id": backorder_picking.id} ) new_moves._action_assign() def _create_split_backorder(self, default=None): """Copy current picking with defaults passed, post message about backorder""" self.ensure_one() backorder_picking = self.copy( dict( { "name": "/", "move_lines": [], "move_line_ids": [], "backorder_id": self.id, }, **(default or {}) ) ) self.message_post( body=_( 'The backorder <a href="#" ' 'data-oe-model="stock.picking" ' 'data-oe-id="%(id)d">%(name)s</a> has been created.' ), id=backorder_picking.id, name=backorder_picking.name, ) return backorder_picking def _split_off_moves(self, moves): """Remove moves from pickings in self and put them into a new one""" new_picking = self.env["stock.picking"] for this in self: if this.state in ("done", "cancel"): raise UserError( _("Cannot split picking {name} in state {state}").format( name=this.name, state=this.state ) ) new_picking = new_picking or this._create_split_backorder() if not this.move_lines - moves: raise UserError( _("Cannot split off all moves from picking %s") % this.name ) moves.write({"picking_id": new_picking.id}) moves.mapped("move_line_ids").write({"picking_id": new_picking.id}) return new_picking
41.618644
4,911
1,872
py
PYTHON
15.0
# Copyright 2020 Hunki Enterprises BV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class StockSplitPicking(models.TransientModel): _name = "stock.split.picking" _description = "Split a picking" mode = fields.Selection( [ ("done", "Done quantities"), ("move", "One picking per move"), ("selection", "Select move lines to split off"), ], required=True, default="done", ) picking_ids = fields.Many2many( "stock.picking", default=lambda self: self._default_picking_ids(), ) move_ids = fields.Many2many("stock.move") def _default_picking_ids(self): return self.env["stock.picking"].browse(self.env.context.get("active_ids", [])) def action_apply(self): return getattr(self, "_apply_%s" % self[:1].mode)() def _apply_done(self): return self.mapped("picking_ids").split_process() def _apply_move(self): """Create new pickings for every move line, keep first move line in original picking """ new_pickings = self.env["stock.picking"] for picking in self.mapped("picking_ids"): for move in picking.move_lines[1:]: new_pickings += picking._split_off_moves(move) return self._picking_action(new_pickings) def _apply_selection(self): """Create one picking for all selected moves""" moves = self.mapped("move_ids") new_picking = moves.mapped("picking_id")._split_off_moves(moves) return self._picking_action(new_picking) def _picking_action(self, pickings): action = self.env["ir.actions.act_window"]._for_xml_id( "stock.action_picking_tree_all", ) action["domain"] = [("id", "in", pickings.ids)] return action
32.842105
1,872
638
py
PYTHON
15.0
# ?? 2015-2016 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Stock Disallow Negative", "version": "15.0.1.0.0", "category": "Inventory, Logistic, Storage", "license": "AGPL-3", "summary": "Disallow negative stock levels by default", "author": "Akretion,Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-workflow", "depends": ["stock"], "data": ["views/product_product_views.xml", "views/stock_location_views.xml"], "installable": True, }
37.529412
638
4,094
py
PYTHON
15.0
# Copyright 2015-2016 Akretion (http://www.akretion.com) - Alexis de Lattre # Copyright 2016 ForgeFlow (http://www.forgeflow.com) # Copyright 2016 Serpent Consulting Services (<http://www.serpentcs.com>) # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestStockNoNegative(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product_model = cls.env["product.product"] cls.product_ctg_model = cls.env["product.category"] cls.picking_type_id = cls.env.ref("stock.picking_type_out") cls.location_id = cls.env.ref("stock.stock_location_stock") cls.location_dest_id = cls.env.ref("stock.stock_location_customers") # Create product category cls.product_ctg = cls._create_product_category(cls) # Create a Product cls.product = cls._create_product(cls, "test_product1") cls._create_picking(cls) def _create_product_category(self): product_ctg = self.product_ctg_model.create( {"name": "test_product_ctg", "allow_negative_stock": False} ) return product_ctg def _create_product(self, name): product = self.product_model.create( { "name": name, "categ_id": self.product_ctg.id, "type": "product", "allow_negative_stock": False, } ) return product def _create_picking(self): self.stock_picking = ( self.env["stock.picking"] .with_context(test_stock_no_negative=True) .create( { "picking_type_id": self.picking_type_id.id, "move_type": "direct", "location_id": self.location_id.id, "location_dest_id": self.location_dest_id.id, } ) ) self.stock_move = self.env["stock.move"].create( { "name": "Test Move", "product_id": self.product.id, "product_uom_qty": 100.0, "product_uom": self.product.uom_id.id, "picking_id": self.stock_picking.id, "state": "draft", "location_id": self.location_id.id, "location_dest_id": self.location_dest_id.id, "quantity_done": 100.0, } ) def test_check_constrains(self): """Assert that constraint is raised when user tries to validate the stock operation which would make the stock level of the product negative""" self.stock_picking.action_confirm() with self.assertRaises(ValidationError): self.stock_picking.button_validate() def test_true_allow_negative_stock_product(self): """Assert that negative stock levels are allowed when the allow_negative_stock is set active in the product""" self.product.allow_negative_stock = True self.stock_picking.action_confirm() self.stock_picking.button_validate() quant = self.env["stock.quant"].search( [ ("product_id", "=", self.product.id), ("location_id", "=", self.location_id.id), ] ) self.assertEqual(quant.quantity, -100) def test_true_allow_negative_stock_location(self): """Assert that negative stock levels are allowed when the allow_negative_stock is set active in the product""" self.product.allow_negative_stock = False self.location_id.allow_negative_stock = True self.stock_picking.action_confirm() self.stock_picking.button_validate() quant = self.env["stock.quant"].search( [ ("product_id", "=", self.product.id), ("location_id", "=", self.location_id.id), ] ) self.assertEqual(quant.quantity, -100)
38.261682
4,094
442
py
PYTHON
15.0
# Copyright 2018 ForgeFlow (https://www.forgeflow.com) # @author Jordi Ballester <jordi.ballester@forgeflow.com.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class StockLocation(models.Model): _inherit = "stock.location" allow_negative_stock = fields.Boolean( help="Allow negative stock levels for the stockable products " "attached to this location.", )
31.571429
442
2,280
py
PYTHON
15.0
# Copyright 2015-2017 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, models from odoo.exceptions import ValidationError from odoo.tools import config, float_compare class StockQuant(models.Model): _inherit = "stock.quant" @api.constrains("product_id", "quantity") def check_negative_qty(self): p = self.env["decimal.precision"].precision_get("Product Unit of Measure") check_negative_qty = ( config["test_enable"] and self.env.context.get("test_stock_no_negative") ) or not config["test_enable"] if not check_negative_qty: return for quant in self: disallowed_by_product = ( not quant.product_id.allow_negative_stock and not quant.product_id.categ_id.allow_negative_stock ) disallowed_by_location = not quant.location_id.allow_negative_stock if ( float_compare(quant.quantity, 0, precision_digits=p) == -1 and quant.product_id.type == "product" and quant.location_id.usage in ["internal", "transit"] and disallowed_by_product and disallowed_by_location ): msg_add = "" if quant.lot_id: msg_add = _(" lot '%s'") % quant.lot_id.name_get()[0][1] raise ValidationError( _( "You cannot validate this stock operation because the " "stock level of the product '%(name)s'%(name_lot)s would " "become negative " "(%(q_quantity)s) on the stock location '%(complete_name)s' " "and negative stock is " "not allowed for this product and/or location." ) % { "name": quant.product_id.display_name, "name_lot": msg_add, "q_quantity": quant.quantity, "complete_name": quant.location_id.complete_name, } )
43.018868
2,280
949
py
PYTHON
15.0
# Copyright 2015-2016 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductCategory(models.Model): _inherit = "product.category" allow_negative_stock = fields.Boolean( help="Allow negative stock levels for the stockable products " "attached to this category. The options doesn't apply to products " "attached to sub-categories of this category.", ) class ProductTemplate(models.Model): _inherit = "product.template" allow_negative_stock = fields.Boolean( help="If this option is not active on this product nor on its " "product category and that this product is a stockable product, " "then the validation of the related stock moves will be blocked if " "the stock level becomes negative with the stock move.", )
36.5
949
558
py
PYTHON
15.0
# Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Purchase Stock Picking Invoice Link", "version": "15.0.1.0.0", "category": "Warehouse Management", "summary": "Adds link between purchases, pickings and invoices", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-workflow", "license": "AGPL-3", "depends": ["stock_picking_invoice_link", "purchase"], "installable": True, }
39.857143
558
8,718
py
PYTHON
15.0
# Copyright 2019 Vicent Cubells <pedro.baeza@tecnativa.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import fields from odoo.tests import Form, common, tagged @tagged("-at_install", "post_install") class TestPurchaseSTockPickingInvoiceLink(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.supplier = cls.env["res.partner"].create({"name": "Supplier for Test"}) cls.product = cls.env["product.product"].create({"name": "Product for Test"}) po_form = Form(cls.env["purchase.order"]) po_form.partner_id = cls.supplier with po_form.order_line.new() as po_line_form: po_line_form.product_id = cls.product po_line_form.price_unit = 15.0 cls.po = po_form.save() def test_puchase_stock_picking_invoice_link(self): # Purchase order confirm self.po.button_confirm() # Validate shipment picking = self.po.picking_ids[0] # Process pickings picking.move_lines.quantity_done = 1.0 picking.button_validate() # Create and post invoice inv_action = self.po.action_create_invoice() invoice = self.env["account.move"].browse([(inv_action["res_id"])]) invoice.invoice_date = self.po.create_date invoice._compute_picking_ids() invoice.action_post() # Only one invoice line has been created self.assertEqual(len(invoice.invoice_line_ids), 1) line = invoice.invoice_line_ids # Move lines are set in invoice lines self.assertEqual(len(line.mapped("move_line_ids")), 1) self.assertEqual(line.mapped("move_line_ids"), picking.move_lines) # Invoices are set in pickings self.assertEqual(picking.invoice_ids, invoice) def test_link_transfer_after_invoice_creation(self): self.product.purchase_method = "purchase" # Purchase order confirm self.po.button_confirm() # create and post invoice inv_action = self.po.action_create_invoice() invoice = self.env["account.move"].browse([(inv_action["res_id"])]) invoice.invoice_date = self.po.create_date invoice.action_post() # Validate shipment picking = self.po.picking_ids[0] # Process pickings picking.move_lines.quantity_done = 1.0 picking.button_validate() # Only one invoice line has been created self.assertEqual(len(invoice.invoice_line_ids), 1) line = invoice.invoice_line_ids # Move lines are set in invoice lines self.assertEqual(len(line.mapped("move_line_ids")), 1) self.assertEqual(line.mapped("move_line_ids"), picking.move_lines) self.assertEqual(len(invoice.picking_ids), 1) # Invoices are set in pickings self.assertEqual(picking.invoice_ids, invoice) def test_invoice_refund_invoice(self): """Check that the invoice created after a refund is linked to the stock picking. """ self.po.button_confirm() # Validate shipment picking = self.po.picking_ids[0] # Process pickings picking.move_lines.quantity_done = 1.0 picking.button_validate() # Create invoice inv_action = self.po.action_create_invoice() invoice = self.env["account.move"].browse([(inv_action["res_id"])]) invoice.invoice_date = self.po.create_date invoice.action_post() # Refund invoice wiz_invoice_refund = ( self.env["account.move.reversal"] .with_context(active_model="account.move", active_ids=invoice.ids) .create( { "refund_method": "cancel", "reason": "test", "journal_id": invoice.journal_id.id, } ) ) wiz_invoice_refund.reverse_moves() # Create invoice again inv_action = self.po.action_create_invoice() new_inv = self.env["account.move"].browse([(inv_action["res_id"])]) # Assert that new invoice has related picking self.assertEqual(new_inv.picking_ids, picking) def test_invoice_refund_modify(self): """Check that the invoice created when the option "Full refund and new draft invoice" is selected, is linked to the picking. """ self.po.button_confirm() # Validate shipment picking = self.po.picking_ids[0] # Process pickings picking.move_lines.quantity_done = 1.0 picking.button_validate() # Create invoice inv_action = self.po.action_create_invoice() invoice = self.env["account.move"].browse([(inv_action["res_id"])]) invoice.invoice_date = self.po.create_date invoice.action_post() # Refund invoice wiz_invoice_refund = ( self.env["account.move.reversal"] .with_context(active_model="account.move", active_ids=invoice.ids) .create( { "refund_method": "modify", "reason": "test", "journal_id": invoice.journal_id.id, } ) ) invoice_id = wiz_invoice_refund.reverse_moves()["res_id"] new_inv = self.env["account.move"].browse(invoice_id) # Maintain order due to a bug in the ORM that does not populate compute before # evaluating the len() function. # Bug reported on: https://github.com/odoo/odoo/issues/98981 self.assertEqual(new_inv.picking_ids, picking) self.assertEqual(len(picking.invoice_ids), 3) def test_purchase_invoice_backorder_no_linked_policy_receive(self): self.product.purchase_method = "receive" self.po.order_line.product_qty = 10 self.po.button_confirm() picking = self.po.picking_ids[0] picking.move_lines.quantity_done = 8.0 picking._action_done() wiz = self.env["stock.backorder.confirmation"].create( {"pick_ids": [(4, picking.id)]} ) wiz.process() inv_action = self.po.action_create_invoice() invoice = self.env["account.move"].browse([(inv_action["res_id"])]) self.assertEqual(invoice.picking_ids, picking) self.assertEqual(len(picking.invoice_ids), 1) backorder_picking = self.po.picking_ids.filtered(lambda p: p.state != "done") backorder_picking.move_lines.quantity_done = 2.0 backorder_picking.button_validate() self.assertFalse(len(backorder_picking.invoice_ids)) self.assertEqual(invoice.picking_ids, picking) def test_purchase_invoice_backorder_linked_policy_purchase(self): self.product.purchase_method = "purchase" self.po.order_line.product_qty = 10 self.po.button_confirm() picking = self.po.picking_ids[0] picking.move_lines.quantity_done = 8.0 picking._action_done() wiz = self.env["stock.backorder.confirmation"].create( {"pick_ids": [(4, picking.id)]} ) wiz.process() inv_action = self.po.action_create_invoice() invoice = self.env["account.move"].browse([(inv_action["res_id"])]) self.assertEqual(invoice.picking_ids, picking) self.assertEqual(len(picking.invoice_ids), 1) backorder_picking = self.po.picking_ids.filtered(lambda p: p.state != "done") backorder_picking.move_lines.quantity_done = 2.0 backorder_picking.button_validate() self.assertEqual(invoice.picking_ids, picking + backorder_picking) def test_partial_invoice_full_link(self): """Check that the partial invoices are linked to the stock picking. """ self.product.purchase_method = "purchase" self.po.order_line.product_qty = 2.0 self.po.button_confirm() picking = self.po.picking_ids[0] picking.move_lines.quantity_done = 2.0 picking._action_done() # Create invoice inv_action = self.po.action_create_invoice() invoice = self.env["account.move"].browse([(inv_action["res_id"])]) inv_form = Form(invoice) inv_form.invoice_date = fields.Date.today() for i in range(len(inv_form.invoice_line_ids)): with inv_form.invoice_line_ids.edit(i) as line_form: line_form.quantity = 1 inv = inv_form.save() inv.action_post() self.assertEqual(inv.picking_ids, picking) inv_action = self.po.action_create_invoice() inv2 = self.env["account.move"].browse([(inv_action["res_id"])]) self.assertEqual(inv2.picking_ids, picking)
43.373134
8,718
2,360
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import models from odoo.tools import float_compare, float_is_zero class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" def get_stock_moves_link_invoice(self): moves_linked = self.env["stock.move"] if self.product_id.purchase_method == "purchase": to_invoice = self.product_qty - self.qty_invoiced else: to_invoice = self.qty_received - self.qty_invoiced for stock_move in self.move_ids.sorted( lambda m: (m.write_date, m.id), reverse=True ): if ( stock_move.state != "done" or stock_move.scrapped or ( stock_move.location_id.usage != "supplier" and ( stock_move.location_dest_id.usage != "supplier" or not stock_move.to_refund ) ) ): continue if not stock_move.invoice_line_ids: to_invoice -= ( stock_move.quantity_done if not stock_move.to_refund else -stock_move.quantity_done ) moves_linked += stock_move continue elif float_is_zero( to_invoice, precision_rounding=self.product_uom.rounding ): break to_invoice -= ( stock_move.quantity_done if not stock_move.to_refund else -stock_move.quantity_done ) moves_linked += stock_move return moves_linked def _prepare_account_move_line(self, move=False): vals = super()._prepare_account_move_line(move=move) stock_moves = self.get_stock_moves_link_invoice() # Invoice returned moves marked as to_refund if ( float_compare( self.product_qty - self.qty_invoiced, 0.0, precision_rounding=self.currency_id.rounding, ) < 0 ): stock_moves = stock_moves.filtered("to_refund") vals["move_line_ids"] = [(4, m.id) for m in stock_moves] return vals
36.307692
2,360
1,547
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class StockMove(models.Model): _inherit = "stock.move" def write(self, vals): """Method used to associate the stock.move with the created account.move.line when the invoicing method of the product is 'purchase' and the invoice is done before receiving the products. """ res = super().write(vals) if vals.get("state", "") == "done": stock_moves = self.get_moves_link_invoice() for stock_move in stock_moves.filtered( lambda sm: sm.purchase_line_id and sm.product_id.purchase_method == "purchase" ): inv_type = stock_move.to_refund and "in_refund" or "in_invoice" inv_line = self.env["account.move.line"].search( [ ("purchase_line_id", "=", stock_move.purchase_line_id.id), ("move_id.move_type", "=", inv_type), ] ) if inv_line: stock_move.invoice_line_ids = [(4, m.id) for m in inv_line] return res def get_moves_link_invoice(self): return self.filtered( lambda x: x.state == "done" and not x.scrapped and ( x.location_id.usage == "supplier" or (x.location_dest_id.usage == "supplier" and x.to_refund) ) )
37.731707
1,547
535
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Stock Picking Product Assortment", "version": "15.0.1.0.0", "category": "Warehouse Management", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "maintainers": ["CarlosRoca13"], "license": "AGPL-3", "installable": True, "depends": ["stock", "product_assortment"], "data": ["views/stock_picking_view.xml"], }
35.666667
535
4,919
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import Form, TransactionCase class TestStockPickingProductAssortment(TransactionCase): def setUp(self): super().setUp() self.filter_obj = self.env["ir.filters"] self.product_obj = self.env["product.template"] self.stock_picking_obj = self.env["stock.picking"] self.pick_type_out = self.env.ref("stock.picking_type_out") self.stock_location = self.env.ref("stock.stock_location_stock") self.customers_location = self.env.ref("stock.stock_location_customers") self.product_category = self.env["product.category"].create( {"name": "Test Product category"} ) self.partner_1 = self.env["res.partner"].create({"name": "Test partner 1"}) self.partner_2 = self.env["res.partner"].create({"name": "Test partner 2"}) self.product_1 = self.product_obj.create( { "name": "Test product 1", "sale_ok": True, "type": "product", "categ_id": self.product_category.id, "description_sale": "Test Description Sale", } ) self.product_2 = self.product_obj.create( { "name": "Test product 2", "sale_ok": True, "type": "product", "categ_id": self.product_category.id, "description_sale": "Test Description Sale", } ) def test_stock_picking_product_assortment(self): assortment_with_whitelist = self.filter_obj.create( { "name": "Test Assortment 1", "model_id": "product.product", "domain": [], "is_assortment": True, "partner_ids": [(4, self.partner_1.id)], "whitelist_product_ids": [(4, self.product_1.product_variant_id.id)], } ) stock_picking_form = Form(self.stock_picking_obj) stock_picking_form.partner_id = self.partner_1 stock_picking_form.picking_type_id = self.pick_type_out stock_picking_form.location_id = self.stock_location stock_picking_form.location_dest_id = self.customers_location with stock_picking_form.move_ids_without_package.new() as move_id: move_id.assortment_product_id = self.product_1.product_variant_id self.assertEqual(move_id.product_id, self.product_1.product_variant_id) stock_picking_1 = stock_picking_form.save() self.assertEqual( stock_picking_1.assortment_product_ids, assortment_with_whitelist.whitelist_product_ids, ) self.assertTrue(stock_picking_1.has_assortment) assortment_with_blacklist = self.filter_obj.create( { "name": "Test Assortment 2", "model_id": "product.product", "domain": [], "is_assortment": True, "partner_ids": [(4, self.partner_1.id), (4, self.partner_2.id)], "blacklist_product_ids": [(4, self.product_2.product_variant_id.id)], } ) stock_picking_form = Form(self.stock_picking_obj) stock_picking_form.partner_id = self.partner_1 stock_picking_form.picking_type_id = self.pick_type_out stock_picking_form.location_id = self.stock_location stock_picking_form.location_dest_id = self.customers_location with stock_picking_form.move_ids_without_package.new() as move_id: move_id.assortment_product_id = self.product_1.product_variant_id self.assertEqual(move_id.product_id, self.product_1.product_variant_id) stock_picking_2 = stock_picking_form.save() self.assertEqual( stock_picking_2.assortment_product_ids, assortment_with_whitelist.whitelist_product_ids - assortment_with_blacklist.blacklist_product_ids, ) self.assertTrue(stock_picking_2.has_assortment) stock_picking_form = Form(self.stock_picking_obj) stock_picking_form.partner_id = self.partner_2 stock_picking_form.picking_type_id = self.pick_type_out stock_picking_form.location_id = self.stock_location stock_picking_form.location_dest_id = self.customers_location with stock_picking_form.move_ids_without_package.new() as move_id: move_id.assortment_product_id = self.product_1.product_variant_id self.assertEqual(move_id.product_id, self.product_1.product_variant_id) stock_picking_3 = stock_picking_form.save() self.assertFalse( stock_picking_3.assortment_product_ids & assortment_with_blacklist.blacklist_product_ids ) self.assertTrue(stock_picking_3.has_assortment)
47.757282
4,919
626
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). from odoo import api, fields, models # We overwrite this class as a trick to repeat the product_id field with different # attributes on the view. class StockMoveLine(models.Model): _inherit = "stock.move.line" assortment_product_id = fields.Many2one( related="product_id", string="Product with blacklist" ) @api.onchange("assortment_product_id") def _onchange_product_secondary_fields(self): if self.assortment_product_id: self.product_id = self.assortment_product_id
34.777778
626
617
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). from odoo import api, fields, models # We overwrite this class as a trick to repeat the product_id field with different # attributes on the view. class StockMove(models.Model): _inherit = "stock.move" assortment_product_id = fields.Many2one( related="product_id", string="Product with blacklist" ) @api.onchange("assortment_product_id") def _onchange_product_secondary_fields(self): if self.assortment_product_id: self.product_id = self.assortment_product_id
34.277778
617
1,531
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). from odoo import api, fields, models from odoo.osv import expression class StockPicking(models.Model): _inherit = "stock.picking" assortment_product_ids = fields.Many2many( comodel_name="product.product", string="Assortment Products", compute="_compute_product_assortment_ids", ) has_assortment = fields.Boolean(compute="_compute_product_assortment_ids") @api.depends("partner_id") def _compute_product_assortment_ids(self): # If we don't initialize the fields we get an error with NewId self.assortment_product_ids = self.env["product.product"] self.has_assortment = False for record in self: if record.partner_id and record.picking_type_id.code == "outgoing": # As all_partner_ids can't be a stored field filters = self.env["ir.filters"].search( [ ( "all_partner_ids", "in", (self.partner_id + self.partner_id.parent_id).ids, ), ] ) domain = [] for fil in filters: domain = expression.AND([domain, fil._get_eval_domain()]) self.has_assortment = True self.assortment_product_ids = self.env["product.product"].search(domain)
40.289474
1,531
679
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Picking Auto Create Lot", "summary": "Auto create lots for incoming pickings", "version": "15.0.1.0.0", "development_status": "Production/Stable", "category": "stock", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "ACSONE SA/NV, Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["stock"], "data": ["views/product_views.xml", "views/stock_picking_type_views.xml"], "maintainers": ["sergio-teruel"], }
39.941176
679
2,409
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). class CommonStockPickingAutoCreateLot(object): def assertUniqueIn(self, element_list): elements = [] for element in element_list: if element in elements: raise Exception("Element %s is not unique in list" % element) elements.append(element) @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.lot_obj = cls.env["stock.production.lot"] cls.warehouse = cls.env.ref("stock.warehouse0") cls.picking_type_in = cls.env.ref("stock.picking_type_in") cls.supplier_location = cls.env.ref("stock.stock_location_suppliers") cls.supplier = cls.env["res.partner"].create({"name": "Supplier - test"}) @classmethod def _create_product(cls, tracking="lot", auto=True): name = "{tracking} - {auto}".format(tracking=tracking, auto=auto) return cls.env["product.product"].create( { "name": name, "type": "product", "tracking": tracking, "auto_create_lot": auto, } ) @classmethod def _create_picking(cls): cls.picking = ( cls.env["stock.picking"] .with_context(default_picking_type_id=cls.picking_type_in.id) .create( { "partner_id": cls.supplier.id, "picking_type_id": cls.picking_type_in.id, "location_id": cls.supplier_location.id, } ) ) @classmethod def _create_move(cls, product=None, qty=1.0): location_dest = cls.picking.picking_type_id.default_location_dest_id cls.move = cls.env["stock.move"].create( { "name": "test-{product}".format(product=product.name), "product_id": product.id, "picking_id": cls.picking.id, "picking_type_id": cls.picking.picking_type_id.id, "product_uom_qty": qty, "product_uom": product.uom_id.id, "location_id": cls.supplier_location.id, "location_dest_id": location_dest.id, } )
37.640625
2,409
5,634
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import UserError from odoo.tests import TransactionCase from .common import CommonStockPickingAutoCreateLot class TestStockPickingAutoCreateLot(CommonStockPickingAutoCreateLot, TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Create 3 products with lot/serial and auto_create True/False cls.product = cls._create_product() cls.product_serial = cls._create_product(tracking="serial") cls.product_serial_not_auto = cls._create_product(tracking="serial", auto=False) cls.picking_type_in.auto_create_lot = True cls._create_picking() cls._create_move(product=cls.product, qty=2.0) cls._create_move(product=cls.product_serial, qty=3.0) cls._create_move(product=cls.product_serial_not_auto, qty=4.0) def test_manual_lot(self): self.picking.action_assign() # Check the display field move = self.picking.move_lines.filtered( lambda m: m.product_id == self.product_serial ) self.assertFalse(move.display_assign_serial) move = self.picking.move_lines.filtered( lambda m: m.product_id == self.product_serial_not_auto ) self.assertTrue(move.display_assign_serial) # Assign manual serials for line in move.move_line_ids: line.lot_id = self.lot_obj.create(line._prepare_auto_lot_values()) self.picking.button_validate() lot = self.env["stock.production.lot"].search( [("product_id", "=", self.product.id)] ) self.assertEqual(len(lot), 1) # Search for serials lot = self.env["stock.production.lot"].search( [("product_id", "=", self.product_serial.id)] ) self.assertEqual(len(lot), 3) def test_auto_create_lot(self): self.picking.action_assign() # Check the display field move = self.picking.move_lines.filtered( lambda m: m.product_id == self.product_serial ) self.assertFalse(move.display_assign_serial) move = self.picking.move_lines.filtered( lambda m: m.product_id == self.product_serial_not_auto ) self.assertTrue(move.display_assign_serial) self.picking._action_done() lot = self.env["stock.production.lot"].search( [("product_id", "=", self.product.id)] ) self.assertEqual(len(lot), 1) # Search for serials lot = self.env["stock.production.lot"].search( [("product_id", "=", self.product_serial.id)] ) self.assertEqual(len(lot), 3) def test_auto_create_transfer_lot(self): self.picking.action_assign() moves = self.picking.move_lines.filtered( lambda m: m.product_id == self.product_serial ) for line in moves.mapped("move_line_ids"): self.assertFalse(line.lot_id) # Test the exception if manual serials are not filled in with self.assertRaises(UserError), self.cr.savepoint(): self.picking.button_validate() # Assign manual serial for product that need it moves = self.picking.move_lines.filtered( lambda m: m.product_id == self.product_serial_not_auto ) # Assign manual serials for line in moves.mapped("move_line_ids"): line.lot_id = self.lot_obj.create(line._prepare_auto_lot_values()) self.picking.button_validate() for line in moves.mapped("move_line_ids"): self.assertTrue(line.lot_id) lot = self.env["stock.production.lot"].search( [("product_id", "=", self.product.id)] ) self.assertEqual(len(lot), 1) # Search for serials lot = self.env["stock.production.lot"].search( [("product_id", "=", self.product_serial.id)] ) self.assertEqual(len(lot), 3) # Check if lots are unique per move and per product if managed # per serial move_lines_serial = self.picking.move_line_ids.filtered( lambda m: m.product_id.tracking == "serial" and m.product_id.auto_create_lot ) serials = [] for move in move_lines_serial: serials.append(move.lot_id.name) self.assertUniqueIn(serials) def test_multi_auto_create_lot(self): """ Create two pickings Try to validate them together Check if lots have been assigned to each move """ self.picking.action_assign() picking_1 = self.picking self._create_picking() picking_2 = self.picking self._create_move(product=self.product_serial, qty=3.0) picking_2.action_assign() pickings = picking_1 | picking_2 moves = pickings.mapped("move_lines").filtered( lambda m: m.product_id == self.product_serial ) for line in moves.mapped("move_line_ids"): self.assertFalse(line.lot_id) pickings._action_done() for line in moves.mapped("move_line_ids"): self.assertTrue(line.lot_id) lot = self.env["stock.production.lot"].search( [("product_id", "=", self.product.id)] ) self.assertEqual(len(lot), 1) # Search for serials lot = self.env["stock.production.lot"].search( [("product_id", "=", self.product_serial.id)] ) self.assertEqual(len(lot), 6)
36.584416
5,634
1,407
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models from odoo.fields import first class StockMoveLine(models.Model): _inherit = "stock.move.line" def _prepare_auto_lot_values(self): """ Prepare multi valued lots per line to use multi creation. """ self.ensure_one() return {"product_id": self.product_id.id, "company_id": self.company_id.id} def set_lot_auto(self): """ Create lots using create_multi to avoid too much queries As move lines were created by product or by tracked 'serial' products, we apply the lot with both different approaches. """ values = [] production_lot_obj = self.env["stock.production.lot"] lots_by_product = dict() for line in self: values.append(line._prepare_auto_lot_values()) lots = production_lot_obj.create(values) for lot in lots: if lot.product_id.id not in lots_by_product: lots_by_product[lot.product_id.id] = lot else: lots_by_product[lot.product_id.id] += lot for line in self: lot = first(lots_by_product[line.product_id.id]) line.lot_id = lot if lot.product_id.tracking == "serial": lots_by_product[line.product_id.id] -= lot
36.076923
1,407
256
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # 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" auto_create_lot = fields.Boolean()
28.444444
256
716
py
PYTHON
15.0
# Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class StockMove(models.Model): _inherit = "stock.move" @api.depends( "has_tracking", "picking_type_id.auto_create_lot", "product_id.auto_create_lot", "picking_type_id.use_existing_lots", "state", ) def _compute_display_assign_serial(self): super()._compute_display_assign_serial() moves_not_display = self.filtered( lambda m: m.picking_type_id.auto_create_lot and m.product_id.auto_create_lot ) for move in moves_not_display: move.display_assign_serial = False return
29.833333
716
921
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # Copyright 2020 ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class StockPicking(models.Model): _inherit = "stock.picking" def _set_auto_lot(self): """ Allows to be called either by button or through code """ pickings = self.filtered(lambda p: p.picking_type_id.auto_create_lot) lines = pickings.mapped("move_line_ids").filtered( lambda x: ( not x.lot_id and not x.lot_name and x.product_id.tracking != "none" and x.product_id.auto_create_lot ) ) lines.set_lot_auto() def _action_done(self): self._set_auto_lot() return super()._action_done() def button_validate(self): self._set_auto_lot() return super().button_validate()
29.709677
921
253
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductTemplate(models.Model): _inherit = "product.template" auto_create_lot = fields.Boolean()
28.111111
253
643
py
PYTHON
15.0
# Copyright 2015 - Sandra Figueroa Varela # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock Picking by Mail", "summary": "Send stock picking by email", "version": "15.0.1.0.1", "author": "Sandra Figueroa Varela, " "Tecnativa, " "Odoo Community Association (OCA), " "Daniel Domínguez (Xtendoo)", "website": "https://github.com/OCA/stock-logistics-workflow", "category": "Warehouse Management", "license": "AGPL-3", "depends": ["stock", "mail"], "data": ["views/stock_picking_view.xml"], "installable": True, }
33.789474
642
1,621
py
PYTHON
15.0
# Copyright 2017 Tecnativa <vicent.cubells@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common class TestStockPickingSendByMail(common.TransactionCase): @classmethod def setUpClass(cls): super(TestStockPickingSendByMail, cls).setUpClass() cls.product = cls.env["product.product"].create({"name": "Test product"}) cls.location_id = cls.env.ref("stock.stock_location_stock") cls.location_destination_id = cls.env.ref("stock.stock_location_customers") cls.picking_type = cls.env.ref("stock.picking_type_out") cls.picking = cls.env["stock.picking"].create( { "picking_type_id": cls.picking_type.id, "location_id": cls.location_id.id, "location_dest_id": cls.location_destination_id.id, "move_lines": [ ( 0, 0, { "name": cls.product.name, "product_id": cls.product.id, "product_uom": cls.product.uom_id.id, "location_id": cls.location_id.id, "location_dest_id": cls.location_destination_id.id, }, ) ], } ) def test_send_mail(self): self.picking.action_confirm() self.picking.action_assign() result = self.picking.action_picking_send() self.assertEqual(result["name"], "Compose Email")
40.525
1,621
1,188
py
PYTHON
15.0
# Copyright 2015 - Sandra Figueroa Varela # Copyright 2017 Tecnativa - Vicent Cubells # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, models class StockPicking(models.Model): _inherit = "stock.picking" def action_picking_send(self): self.ensure_one() template = self.company_id.stock_mail_confirmation_template_id compose_form = self.env.ref( "mail.email_compose_message_wizard_form", False, ) ctx = dict( default_model="stock.picking", default_res_id=self.id, default_use_template=bool(template), default_template_id=template and template.id or False, default_composition_mode="comment", user_id=self.env.user.id, ) return { "name": _("Compose Email"), "type": "ir.actions.act_window", "view_type": "form", "view_mode": "form", "res_model": "mail.compose.message", "views": [(compose_form.id, "form")], "view_id": compose_form.id, "target": "new", "context": ctx, }
33
1,188
456
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Stock Push Delay", "summary": "Manual evaluation of Push rules", "version": "15.0.1.0.0", "category": "Inventory", "author": "ForgeFlow, " "Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/stock-logistics-workflow", "depends": ["stock"], "development_status": "Alpha", }
35.076923
456
1,677
py
PYTHON
15.0
from odoo.tests import Form from odoo.tests.common import TransactionCase class TestPacking(TransactionCase): @classmethod def setUpClass(cls): super(TestPacking, cls).setUpClass() cls.stock_location = cls.env.ref("stock.stock_location_stock") cls.warehouse = cls.env["stock.warehouse"].search( [("lot_stock_id", "=", cls.stock_location.id)], limit=1 ) cls.warehouse.reception_steps = "two_steps" cls.productA = cls.env["product.product"].create( {"name": "Product A", "type": "product"} ) def test_push_delay(self): """Checks that the push picking is delayed""" receipt_form = Form(self.env["stock.picking"]) receipt_form.picking_type_id = self.warehouse.in_type_id with receipt_form.move_ids_without_package.new() as move_line: move_line.product_id = self.productA move_line.product_uom_qty = 1 receipt = receipt_form.save() receipt.action_confirm() # Checks an internal transfer was not created. internal_transfer = self.env["stock.picking"].search( [("picking_type_id", "=", self.warehouse.int_type_id.id)], order="id desc", limit=1, ) self.assertNotEqual(internal_transfer.origin, receipt.name) receipt._action_done() # Checks an internal transfer was created. internal_transfer = self.env["stock.picking"].search( [("picking_type_id", "=", self.warehouse.int_type_id.id)], order="id desc", limit=1, ) self.assertEqual(internal_transfer.origin, receipt.name)
39
1,677
460
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockMove(models.Model): _inherit = "stock.move" def _push_apply(self): """Manual triggering""" if self.env.context.get("manual_push", False): new_move = super(StockMove, self)._push_apply() if new_move: new_move._action_confirm() return new_move return self.env["stock.move"]
27.058824
460
365
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockPicking(models.Model): _inherit = "stock.picking" def _action_done(self): res = super(StockPicking, self)._action_done() for picking in self.with_context(manual_push=True): picking.move_lines._push_apply() return res
26.071429
365
636
py
PYTHON
15.0
# Copyright 2022 Tecnativa - César A. Sánchez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock landed costs security", "version": "15.0.1.0.0", "category": "Inventory", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["stock_landed_costs"], "data": [ "security/stock_landed_costs_security.xml", "security/ir.model.access.csv", "views/stock_landed_costs_view.xml", ], "installable": True, "maintainers": ["cesar-tecnativa"], }
35.222222
634
602
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Picking backordering strategies", "version": "15.0.1.0.0", "development_status": "Production/Stable", "author": """ACSONE SA/NV, Odoo Community Association (OCA)""", "maintainers": ["rousseldenis", "mgosai"], "category": "Warehouse Management", "website": "https://github.com/OCA/stock-logistics-workflow", "depends": ["stock"], "data": ["views/picking_type.xml"], "license": "AGPL-3", "installable": True, "application": False, }
33.444444
602
3,887
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import Form, TransactionCase class TestBackorderStrategy(TransactionCase): @classmethod def setUpClass(cls): """Create the picking.""" super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.picking_obj = cls.env["stock.picking"] move_obj = cls.env["stock.move"] cls.picking_type = cls.env.ref("stock.picking_type_in") product = cls.env.ref("product.product_product_13") loc_supplier_id = cls.env.ref("stock.stock_location_suppliers").id loc_stock_id = cls.env.ref("stock.stock_location_stock").id cls.picking = cls.picking_obj.create( { "picking_type_id": cls.picking_type.id, "location_id": loc_supplier_id, "location_dest_id": loc_stock_id, } ) move_obj.create( { "name": "/", "picking_id": cls.picking.id, "product_uom": product.uom_id.id, "location_id": loc_supplier_id, "location_dest_id": loc_stock_id, "product_id": product.id, "product_uom_qty": 2, } ) cls.picking.action_confirm() def _process_picking(self): """Receive partially the picking""" self.picking.move_line_ids.qty_done = 1.0 res = self.picking.button_validate() return res def test_backorder_strategy_create(self): """Check strategy for stock.picking_type_in is create Receive picking Check backorder is created """ self.picking_type.backorder_strategy = "create" self._process_picking() backorder = self.picking_obj.search([("backorder_id", "=", self.picking.id)]) self.assertTrue(backorder) def test_backorder_strategy_no_create(self): """Set strategy for stock.picking_type_in to no_create Receive picking Check there is no backorder Check if there is one move done and one move cancelled """ self.picking_type.backorder_strategy = "no_create" self._process_picking() backorder = self.picking_obj.search([("backorder_id", "=", self.picking.id)]) self.assertFalse(backorder) states = list(set(self.picking.move_lines.mapped("state"))) self.assertEqual( "done", self.picking.state, ) self.assertListEqual( ["cancel", "done"], sorted(states), ) def test_backorder_strategy_cancel(self): """Set strategy for stock.picking_type_in to cancel Receive picking Check the backorder state is cancel """ self.picking_type.backorder_strategy = "cancel" self._process_picking() backorder = self.picking_obj.search([("backorder_id", "=", self.picking.id)]) self.assertTrue(backorder) self.assertEqual("cancel", backorder.state) def test_backorder_strategy_manual(self): """Set strategy for stock.picking_type_in to manual Receive picking Check the backorder wizard is launched """ self.assertEqual("manual", self.picking_type.backorder_strategy) res_dict = self._process_picking() backorder_wizard = Form( self.env["stock.backorder.confirmation"].with_context(**res_dict["context"]) ).save() backorder_wizard.process() self.assertEqual( "done", self.picking.state, ) backorder_exist = self.picking_obj.search( [("backorder_id", "=", self.picking.id)] ) self.assertEqual(len(backorder_exist), 1, "Back order should be created.")
35.990741
3,887
514
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class StockPickingType(models.Model): _inherit = "stock.picking.type" backorder_strategy = fields.Selection( [ ("manual", "Manual"), ("create", "Create"), ("no_create", "No create"), ("cancel", "Cancel"), ], default="manual", help="Define what to do with backorder", required=True, )
25.7
514
339
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockMove(models.Model): _inherit = "stock.move" def _cancel_remaining_quantities(self): to_cancel = self.filtered(lambda m: m.state not in ("done", "cancel")) to_cancel._action_cancel()
28.25
339
1,003
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockPicking(models.Model): _inherit = "stock.picking" def _check_backorder(self): # If strategy == 'manual', let the normal process going on self = self.filtered(lambda p: p.picking_type_id.backorder_strategy == "manual") return super(StockPicking, self)._check_backorder() def _create_backorder(self): # Do nothing with pickings 'no_create' pickings = self.filtered( lambda p: p.picking_type_id.backorder_strategy != "no_create" ) pickings_no_create = self - pickings pickings_no_create.mapped("move_lines")._cancel_remaining_quantities() res = super(StockPicking, pickings)._create_backorder() to_cancel = res.filtered( lambda b: b.backorder_id.picking_type_id.backorder_strategy == "cancel" ) to_cancel.action_cancel() return res
37.148148
1,003
717
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Picking Whole Scrap", "summary": "Create whole scrap from a picking for move lines", "version": "15.0.1.0.1", "development_status": "Production/Stable", "category": "Warehouse", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "installable": True, "depends": ["stock"], "data": [ "security/ir.model.access.csv", "wizards/stock_picking_whole_scrap.xml", "views/stock_picking_views.xml", ], "maintainers": ["sergio-teruel"], }
35.85
717
3,482
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import UserError from odoo.tests.common import TransactionCase, tagged @tagged("post_install", "-at_install") class TestStockPickingScrapQuick(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.warehouse = cls.env.ref("stock.warehouse0") cls.picking_type_out = cls.warehouse.out_type_id cls.customer_location = cls.env.ref("stock.stock_location_customers") cls.scrap_location_id = cls.env["stock.location"].create( { "name": "Scrap location for test", "scrap_location": True, "location_id": cls.env.ref("stock.stock_location_locations_virtual").id, } ) cls.partner = cls.env["res.partner"].create({"name": "Partner - test"}) cls.product = cls.env["product.product"].create( {"name": "test", "type": "product"} ) cls.quant = cls.env["stock.quant"].create( { "product_id": cls.product.id, "location_id": cls.picking_type_out.default_location_src_id.id, "quantity": 50.0, } ) cls.picking = cls.env["stock.picking"].create( { "partner_id": cls.partner.id, "picking_type_id": cls.picking_type_out.id, "location_id": cls.picking_type_out.default_location_src_id.id, "location_dest_id": cls.customer_location.id, } ) cls.move = cls.env["stock.move"].create( { "name": "test", "product_id": cls.product.id, "picking_id": cls.picking.id, "picking_type_id": cls.picking_type_out.id, "product_uom_qty": 2.0, "product_uom": cls.product.uom_id.id, "location_id": cls.picking_type_out.default_location_src_id.id, "location_dest_id": cls.customer_location.id, "procure_method": "make_to_stock", } ) def _create_scrap_wizard(self): return ( self.env["wiz.stock.picking.scrap"] .with_context(active_id=self.picking.id) .create({"scrap_location_id": self.scrap_location_id.id}) ) def test_scrap_load_view(self): self.picking.action_assign() self.picking.move_line_ids.qty_done = 2.0 self.picking.button_validate() wiz = self._create_scrap_wizard() self.assertEqual(len(wiz.line_ids), 1) def test_scrap_picking_not_done(self): self.picking.action_assign() self.picking.move_line_ids.qty_done = 2.0 with self.assertRaises(UserError): self._create_scrap_wizard() def test_scrap_more_qty_that_done(self): self.picking.action_assign() self.picking.move_line_ids.qty_done = 2.0 self.picking.button_validate() wiz = self._create_scrap_wizard() wiz.line_ids.quantity = 10.0 with self.assertRaises(UserError): wiz.create_scrap() def test_do_scrap(self): self.picking.action_assign() self.picking.move_line_ids.qty_done = 2.0 self.picking.button_validate() wiz = self._create_scrap_wizard() scraps = wiz.create_scrap() self.assertEqual(len(scraps), 1)
38.688889
3,482
543
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, models class StockPicking(models.Model): _inherit = "stock.picking" def button_whole_scrap(self): self.ensure_one() return { "name": _("Whole Scrap"), "view_mode": "form", "res_model": "wiz.stock.picking.scrap", "type": "ir.actions.act_window", "context": {"default_picking_id": self.id}, "target": "new", }
30.166667
543
4,880
py
PYTHON
15.0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tools.float_utils import float_compare, float_round class StockPickingScrapLine(models.TransientModel): _name = "wiz.stock.picking.scrap.line" _description = "Wizard lines for picking whole scrap" _rec_name = "product_id" product_id = fields.Many2one( comodel_name="product.product", string="Product", readonly=True ) lot_id = fields.Many2one( comodel_name="stock.production.lot", string="Lot", readonly=True ) package_id = fields.Many2one( comodel_name="stock.quant.package", string="Package", readonly=True ) owner_id = fields.Many2one( comodel_name="res.partner", string="Owner", readonly=True ) quantity = fields.Float(digits="Product Unit of Measure", required=True) uom_id = fields.Many2one( comodel_name="uom.uom", string="Unit of Measure", readonly=True ) wizard_id = fields.Many2one(comodel_name="wiz.stock.picking.scrap", string="Wizard") move_line_id = fields.Many2one(comodel_name="stock.move.line", string="Move Line") class StockPickingScrap(models.TransientModel): _name = "wiz.stock.picking.scrap" _description = "Picking Whole Scrap" picking_id = fields.Many2one(comodel_name="stock.picking") line_ids = fields.One2many( comodel_name="wiz.stock.picking.scrap.line", inverse_name="wizard_id", string="Moves", ) scrap_location_id = fields.Many2one( comodel_name="stock.location", string="Scrap Location", domain=[("scrap_location", "=", True)], ) @api.model def default_get(self, fields): if len(self.env.context.get("active_ids", list())) > 1: raise UserError(_("You may only scrap one picking at a time!")) res = super().default_get(fields) scrap_lines = [] picking = self.env["stock.picking"].browse(self.env.context.get("active_id")) if picking: res.update({"picking_id": picking.id}) if picking.state != "done": raise UserError(_("You may only scrap pickings in done state")) for move_line in picking.move_line_ids: if move_line.move_id.scrapped: continue quantity = move_line.qty_done quantity = float_round( quantity, precision_rounding=move_line.product_uom_id.rounding ) scrap_lines.append( ( 0, 0, { "product_id": move_line.product_id.id, "lot_id": move_line.lot_id.id, "package_id": move_line.result_package_id.id, "owner_id": move_line.owner_id.id, "quantity": quantity, "uom_id": move_line.product_uom_id.id, "move_line_id": move_line.id, }, ) ) if "line_ids" in fields: res.update({"line_ids": scrap_lines}) if "scrap_location_id" in fields: scrap_location = self.env["stock.location"].search( [("scrap_location", "=", True)], limit=1 ) res["scrap_location_id"] = scrap_location.id return res def _prepare_stock_scrap(self, scrap_line): vals = { "product_id": scrap_line.product_id.id, "product_uom_id": scrap_line.uom_id.id, "lot_id": scrap_line.move_line_id.lot_id.id, "package_id": scrap_line.move_line_id.result_package_id.id, "owner_id": scrap_line.move_line_id.owner_id.id, "move_id": scrap_line.move_line_id.move_id.id, "picking_id": scrap_line.move_line_id.picking_id.id, "location_id": scrap_line.move_line_id.location_dest_id.id, "scrap_location_id": self.scrap_location_id.id, "scrap_qty": scrap_line.quantity, } return vals def create_scrap(self): StockScrap = self.env["stock.scrap"] new_scraps = StockScrap.browse() for line in self.line_ids.filtered("quantity"): if ( float_compare( line.quantity, line.move_line_id.qty_done, precision_rounding=line.uom_id.rounding, ) > 0 ): raise UserError(_("You can't scrap more quantity that done it")) new_scraps += StockScrap.create(self._prepare_stock_scrap(line)) new_scraps.do_scrap() return new_scraps
40.666667
4,880
647
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@camptocamp.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Picking Product Availability Search", "summary": "Filter pickings by their products availability state", "version": "15.0.1.0.1", "author": "Camptocamp, Odoo Community Association (OCA)", "maintainers": ["ivantodorovich"], "website": "https://github.com/OCA/stock-logistics-workflow", "license": "AGPL-3", "category": "Warehouse Management", "depends": ["stock"], "data": ["views/stock_picking.xml"], }
40.375
646
5,453
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@camptocamp.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import Command from odoo.tests import TransactionCase class TestSearch(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.partner = cls.env.ref("base.res_partner_1") cls.product = cls.env["product.product"].create( {"name": "Product", "type": "product"} ) cls.location_stock = cls.env.ref("stock.stock_location_stock") cls.location_customers = cls.env.ref("stock.stock_location_customers") cls.location_suppliers = cls.env.ref("stock.stock_location_suppliers") cls.picking_type_in = cls.env.ref("stock.picking_type_in") cls.picking_type_out = cls.env.ref("stock.picking_type_out") # Create some initial stocks cls.env["stock.quant"].create( { "product_id": cls.product.id, "product_uom_id": cls.product.uom_id.id, "location_id": cls.location_stock.id, "quantity": 10.00, } ) # Create some incoming pickings cls.picking_in_draft = cls._create_picking(picking_type="in", confirm=False) cls.picking_in_confirm = cls._create_picking(picking_type="in", confirm=True) cls.picking_in_done = cls._create_picking(picking_type="in", confirm=True) cls._picking_action_done(cls.picking_in_done) # Create some outgoing pickings cls.picking_out_draft = cls._create_picking(picking_type="out") cls.picking_out_confirm = cls._create_picking(picking_type="out", confirm=True) cls.picking_out_done = cls._create_picking(picking_type="out", confirm=True) cls.picking_out_unavailable = cls._create_picking( picking_type="out", quantity=500.0, confirm=True ) cls._picking_action_done(cls.picking_out_done) @classmethod def _create_picking( cls, picking_type="out", product=None, quantity=1.0, confirm=False ): assert picking_type in ("in", "out") if product is None: product = cls.product vals = { "partner_id": cls.partner.id, "picking_type_id": getattr(cls, f"picking_type_{picking_type}").id, } if picking_type == "out": vals.update( { "location_id": cls.location_stock.id, "location_dest_id": cls.location_customers.id, } ) else: vals.update( { "location_id": cls.location_suppliers.id, "location_dest_id": cls.location_stock.id, } ) vals["move_lines"] = [ Command.create( { "name": product.display_name, "product_id": product.id, "product_uom": product.uom_id.id, "product_uom_qty": quantity, "location_id": vals["location_id"], "location_dest_id": vals["location_dest_id"], } ), ] picking = cls.env["stock.picking"].create(vals) if confirm: picking.action_confirm() return picking @classmethod def _picking_action_done(cls, picking): for move in picking.move_lines: move.quantity_done = move.product_uom_qty return picking._action_done() def test_search_is_set(self): pickings = self.env["stock.picking"].search( [ ("move_lines.product_id", "=", self.product.id), ("products_availability_state", "!=", False), ] ) self.assertEqual( pickings, self.picking_out_confirm + self.picking_out_unavailable, ) def test_search_is_not_set(self): pickings = self.env["stock.picking"].search( [ ("move_lines.product_id", "=", self.product.id), ("products_availability_state", "=", False), ] ) self.assertEqual( pickings, self.picking_in_draft + self.picking_in_confirm + self.picking_in_done + self.picking_out_draft + self.picking_out_done, ) def test_search_is_available(self): pickings = self.env["stock.picking"].search( [ ("move_lines.product_id", "=", self.product.id), ("products_availability_state", "=", "available"), ] ) self.assertEqual(pickings, self.picking_out_confirm) def test_search_is_not_available(self): pickings = self.env["stock.picking"].search( [ ("move_lines.product_id", "=", self.product.id), ("products_availability_state", "!=", "available"), ] ) self.assertEqual( pickings, self.picking_in_confirm + self.picking_in_draft + self.picking_in_done + self.picking_out_draft + self.picking_out_done + self.picking_out_unavailable, )
37.342466
5,452
1,986
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA (https://www.camptocamp.com). # @author Iván Todorovich <ivan.todorovich@camptocamp.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.osv.expression import OR, distribute_not, normalize_domain class StockPicking(models.Model): _inherit = "stock.picking" products_availability_state = fields.Selection( search="_search_products_availability_state" ) @api.model def _search_products_availability_state(self, operator, value): if operator not in ("=", "!="): raise UserError(_("Invalid domain operator %s", operator)) if not isinstance(value, str) and value is not False: raise UserError(_("Invalid domain right operand %s", value)) # Search all pickings for which we need to compute the products availability. # The value would be ``False`` if the picking doesn't fall under this list. domain = [ ("picking_type_code", "=", "outgoing"), ("state", "in", ["confirmed", "waiting", "assigned"]), ] # Special case for "is set" / "is not set" domains if operator == "=" and value is False: return distribute_not(["!"] + normalize_domain(domain)) if operator == "!=" and value is False: return domain # Perform a search and compute values to filter on-the-fly res_ids = [] pickings = self.with_context(prefetch_fields=False).search(domain) for picking in pickings: if picking.products_availability_state == value: res_ids.append(picking.id) if operator == "=": return [("id", "in", res_ids)] else: return OR( [ distribute_not(["!"] + normalize_domain(domain)), [("id", "not in", res_ids)], ] )
41.354167
1,985
661
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Stock Picking Product Availability Inline", "summary": "Show product availability in product drop-down in stock picking form view.", "version": "15.0.1.0.0", "development_status": "Beta", "category": "Warehouse Management", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["stock", "base_view_inheritance_extension"], "data": ["views/stock_picking_views.xml", "views/stock_move_line_views.xml"], }
47.214286
661
2,902
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import Form, TransactionCase, tagged @tagged("post_install", "-at_install") class TestStockPickingProductAvailabilityInline(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create({"name": "Partner"}) cls.product = cls.env["product.product"].create( {"name": "Product", "type": "product"} ) cls.warehouse1 = cls.env["stock.warehouse"].create( {"name": "Warehouse 1", "code": "AI1"} ) cls.warehouse2 = cls.env["stock.warehouse"].create( {"name": "Warehouse 2", "code": "AI2"} ) StockQuant = cls.env["stock.quant"] StockQuant.create( { "product_id": cls.product.id, "product_uom_id": cls.product.uom_id.id, "location_id": cls.warehouse1.lot_stock_id.id, "quantity": 10.00, } ) StockQuant.create( { "product_id": cls.product.id, "product_uom_id": cls.product.uom_id.id, "location_id": cls.warehouse2.lot_stock_id.id, "quantity": 20.00, } ) def test_stock_picking_product_rec_name(self): self.env.ref("product.decimal_product_uom").write({"digits": 3}) # Show free_qty in warehouse1 self.assertEqual( self.product.with_context(warehouse=self.warehouse1.id).free_qty, 10.0, ) picking_form = Form( self.env["stock.picking"].with_context( warehouse=self.warehouse1.id, sp_product_stock_inline=True ) ) picking_form.partner_id = self.partner picking_form.picking_type_id = self.env.ref("stock.picking_type_out") with picking_form.move_ids_without_package.new() as line_form: line_form.product_id = self.product self.assertTrue( line_form.product_id.display_name.endswith("(10.000 Units)") ) # Show free_qty in warehouse2 self.assertEqual( self.product.with_context(warehouse=self.warehouse2.id).free_qty, 20.0, ) picking_form = Form( self.env["stock.picking"].with_context( warehouse=self.warehouse2.id, sp_product_stock_inline=True ) ) picking_form.partner_id = self.partner picking_form.picking_type_id = self.env.ref("stock.picking_type_out") with picking_form.move_ids_without_package.new() as line_form: line_form.product_id = self.product self.assertTrue( line_form.product_id.display_name.endswith("(20.000 Units)") )
38.693333
2,902
746
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class ProductProduct(models.Model): _inherit = "product.product" def name_get(self): res = super().name_get() if self.env.context.get("sp_product_stock_inline"): product_dict = {r.id: r for r in self} dp = self.env["decimal.precision"].precision_get("Product Unit of Measure") new_res = [] for rec_name in res: prod = product_dict[rec_name[0]] name = f"{rec_name[1]} ({prod.free_qty:.{dp}f} {prod.uom_id.name})" new_res.append((prod.id, name)) res = new_res return res
35.52381
746
1,724
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class StockPicking(models.Model): _inherit = "stock.picking" picking_type_warehouse_id = fields.Many2one( comodel_name="stock.warehouse", string="Stock picking type warehouse", related="picking_type_id.warehouse_id", ) class StockMove(models.Model): _inherit = "stock.move" @api.onchange("product_id") def _onchange_product_id(self): """Avoid calling product name_get method several times with 'sp_product_stock_inline' context key. """ sp_line = self if self.env.context.get("sp_product_stock_inline"): sp_line = self.with_context( sp_product_stock_inline=False, warehouse=self.warehouse_id.id ) return super(StockMove, sp_line)._onchange_product_id() class StockMoveLine(models.Model): _inherit = "stock.move.line" picking_type_warehouse_id = fields.Many2one( comodel_name="stock.warehouse", string="Stock picking type warehouse", related="picking_id.picking_type_id.warehouse_id", ) @api.onchange("product_id") def _onchange_product_id(self): """Avoid calling product name_get method several times with 'sp_product_stock_inline' context key. """ sp_line = self if self.env.context.get("sp_product_stock_inline"): sp_line = self.with_context( sp_product_stock_inline=False, warehouse=self.picking_type_warehouse_id.id, ) return super(StockMoveLine, sp_line)._onchange_product_id()
32.528302
1,724
589
py
PYTHON
15.0
# © 2016 Lorenzo Battistini - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Pickings back to draft", "summary": "Reopen cancelled pickings", "version": "15.0.1.0.1", "category": "Warehouse Management", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Agile Business Group, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["stock"], "data": ["views/picking_view.xml"], "images": ["images/picking.png"], }
36.75
588
2,841
py
PYTHON
15.0
# © 2016 Lorenzo Battistini - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.exceptions import UserError from odoo.tests.common import TransactionCase class TestPickingBackToDraft(TransactionCase): def _create_picking(self, partner, p_type, src=None, dest=None): picking = self.env["stock.picking"].create( { "partner_id": partner.id, "picking_type_id": p_type.id, "location_id": src or self.src_location.id, "location_dest_id": dest or self.cust_location.id, } ) return picking def _create_move(self, picking, product, quantity=5.0): src_location = self.env.ref("stock.stock_location_stock") dest_location = self.env.ref("stock.stock_location_customers") return self.env["stock.move"].create( { "name": "/", "picking_id": picking.id, "product_id": product.id, "product_uom_qty": quantity, "product_uom": product.uom_id.id, "location_id": src_location.id, "location_dest_id": dest_location.id, } ) def setUp(self, *args, **kwargs): super(TestPickingBackToDraft, self).setUp(*args, **kwargs) self.src_location = self.env.ref("stock.stock_location_stock") self.cust_location = self.env.ref("stock.stock_location_customers") self.partner = self.env.ref("base.res_partner_2") self.product1 = self.env.ref("product.product_product_25") self.product2 = self.env.ref("product.product_product_27") self.picking_a = self._create_picking( self.partner, self.env.ref("stock.picking_type_out") ) self.move_a_1 = self._create_move(self.picking_a, self.product1, quantity=1) self.move_a_2 = self._create_move(self.picking_a, self.product2, quantity=2) def test_back_to_draft(self): self.assertEqual(self.picking_a.state, "draft") with self.assertRaises(UserError): self.picking_a.action_back_to_draft() self.picking_a.action_cancel() self.assertEqual(self.picking_a.state, "cancel") self.picking_a.action_back_to_draft() self.assertEqual(self.picking_a.state, "draft") self.picking_a.action_confirm() self.assertEqual(self.picking_a.state, "assigned") with self.assertRaises(UserError): self.picking_a.action_back_to_draft() self.picking_a.action_cancel() self.assertEqual(self.picking_a.state, "cancel") self.picking_a.action_back_to_draft() self.assertEqual(self.picking_a.state, "draft") with self.assertRaises(UserError): self.picking_a.action_back_to_draft()
43.692308
2,840
452
py
PYTHON
15.0
# © 2016 Lorenzo Battistini - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import UserError class StockMove(models.Model): _inherit = "stock.move" def action_back_to_draft(self): if self.filtered(lambda m: m.state != "cancel"): raise UserError(_("You can set to draft cancelled moves only")) self.write({"state": "draft"})
32.214286
451
324
py
PYTHON
15.0
# © 2016 Lorenzo Battistini - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockPicking(models.Model): _inherit = "stock.picking" def action_back_to_draft(self): moves = self.mapped("move_lines") moves.action_back_to_draft()
26.916667
323
3,097
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import SUPERUSER_ID, api _logger = logging.getLogger(__name__) def pre_init_hook(cr): """Speed up the installation of the module on an existing Odoo instance""" cr.execute( """ SELECT column_name FROM information_schema.columns WHERE table_name='stock_move' AND column_name='qty_returnable' """ ) if not cr.fetchone(): _logger.info("Creating field qty_returnable on stock_move") cr.execute( """ ALTER TABLE stock_move ADD COLUMN qty_returnable float; """ ) cr.execute( """ UPDATE stock_move SET qty_returnable = 0 WHERE state IN ('draft', 'cancel') """ ) cr.execute( """ UPDATE stock_move SET qty_returnable = product_uom_qty WHERE state = 'done' """ ) def post_init_hook(cr, registry): """Set moves returnable qty on hand""" env = api.Environment(cr, SUPERUSER_ID, {}) moves_draft = env["stock.move"].search([("state", "in", ["draft", "cancel"])]) moves_no_return_pendant = env["stock.move"].search( [ ("returned_move_ids", "=", False), ("state", "not in", ["draft", "cancel", "done"]), ] ) moves_by_reserved_availability = {} for move in moves_no_return_pendant: moves_by_reserved_availability.setdefault(move.reserved_availability, []) moves_by_reserved_availability[move.reserved_availability].append(move.id) for qty, ids in moves_by_reserved_availability.items(): cr.execute( "UPDATE stock_move SET qty_returnable = %s " "WHERE id IN %s", (qty, tuple(ids)), ) moves_no_return_done = env["stock.move"].search( [ ("returned_move_ids", "=", False), ("state", "=", "done"), ] ) # Recursively solve quantities updated_moves = moves_no_return_done + moves_draft + moves_no_return_pendant remaining_moves = env["stock.move"].search( [ ("returned_move_ids", "!=", False), ("state", "=", "done"), ] ) while remaining_moves: _logger.info("{} moves left...".format(len(remaining_moves))) remaining_moves, updated_moves = update_qty_returnable( cr, remaining_moves, updated_moves ) def update_qty_returnable(cr, remaining_moves, updated_moves): for move in remaining_moves: if all([x in updated_moves for x in move.returned_move_ids]): quantity_returned = sum(move.returned_move_ids.mapped("qty_returnable")) quantity = move.product_uom_qty - quantity_returned cr.execute( "UPDATE stock_move SET qty_returnable = %s " "WHERE id = %s", (quantity, move.id), ) remaining_moves -= move updated_moves += move return remaining_moves, updated_moves
33.301075
3,097
766
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Stock Return Request", "version": "15.0.1.0.0", "category": "Stock", "website": "https://github.com/OCA/stock-logistics-workflow", "author": "Tecnativa, " "Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": [ "stock", ], "data": [ "security/ir.model.access.csv", "data/stock_return_request_data.xml", "views/stock_return_request_views.xml", "report/stock_return_report.xml", "wizard/suggest_return_request.xml", ], "pre_init_hook": "pre_init_hook", "post_init_hook": "post_init_hook", }
31.916667
766
8,664
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from .test_stock_return_request_common import StockReturnRequestCase class PurchaseReturnRequestCase(StockReturnRequestCase): @classmethod def setUpClass(cls): super().setUpClass() def test_01_return_request_to_customer(self): """Find pickings from the customer and make the return""" self.return_request_customer.write( { "line_ids": [ ( 0, 0, { "product_id": self.prod_1.id, "quantity": 12.0, }, ) ], } ) self.return_request_customer.action_confirm() pickings = self.return_request_customer.returned_picking_ids moves = self.return_request_customer.returned_picking_ids.mapped("move_lines") # There are two pickings found with 10 units delivered each. # The return moves are filled up to the needed quantity self.assertEqual(len(pickings), 2) self.assertEqual(len(moves), 2) self.assertAlmostEqual(sum(moves.mapped("product_uom_qty")), 12.0) # Process the return to validate all the pickings self.return_request_customer.action_validate() self.assertTrue( all([True if x == "done" else False for x in pickings.mapped("state")]) ) # Now we've got those 12.0 units back in our stock (there were 80.0) prod_1_qty = self.prod_1.with_context( location=self.wh1.lot_stock_id.id ).qty_available self.assertAlmostEqual(prod_1_qty, 92.0) def test_02_return_request_to_supplier(self): """Find pickings from the supplier and make the return""" self.return_request_supplier.write( { "line_ids": [ ( 0, 0, { "product_id": self.prod_1.id, "quantity": 12.0, }, ) ], } ) self.return_request_supplier.action_confirm() pickings = self.return_request_supplier.returned_picking_ids moves = self.return_request_supplier.returned_picking_ids.mapped("move_lines") # There are two pickings found with 10 and 90 units. The older beign # the one with 10. So two pickings are get. # The return moves are filled up to the needed quantity self.assertEqual(len(pickings), 2) self.assertEqual(len(moves), 2) self.assertAlmostEqual(sum(moves.mapped("product_uom_qty")), 12.0) # Process the return to validate all the pickings self.return_request_supplier.action_validate() self.assertTrue( all([True if x == "done" else False for x in pickings.mapped("state")]) ) # We've returned 12.0 units from the 80.0 we had prod_1_qty = self.prod_1.with_context( location=self.wh1.lot_stock_id.id ).qty_available self.assertAlmostEqual(prod_1_qty, 68.0) def test_03_return_request_to_supplier_with_lots(self): """Find pickings from the supplier and make the return""" self.return_request_supplier.write( { "line_ids": [ ( 0, 0, { "product_id": self.prod_3.id, "lot_id": self.prod_3_lot1.id, "quantity": 50.0, }, ), ( 0, 0, { "product_id": self.prod_3.id, "lot_id": self.prod_3_lot2.id, "quantity": 5.0, }, ), ], } ) self.return_request_supplier.action_confirm() pickings = self.return_request_supplier.returned_picking_ids moves = self.return_request_supplier.returned_picking_ids.mapped("move_lines") # There are two pickings found with that lot and 90 units. # The older has 20 and the newer 70, so only 30 units will be returned # from the second. self.assertEqual(len(pickings), 2) self.assertEqual(len(moves), 2) self.assertAlmostEqual(sum(moves.mapped("product_uom_qty")), 55.0) # Process the return to validate all the pickings self.return_request_supplier.action_validate() self.assertTrue( all([True if x == "done" else False for x in pickings.mapped("state")]) ) # We've returned 50.0 units from the 90.0 we had for that lot prod_3_qty_lot_1 = self.prod_3.with_context( location=self.wh1.lot_stock_id.id, lot_id=self.prod_3_lot1.id ).qty_available prod_3_qty_lot_2 = self.prod_3.with_context( location=self.wh1.lot_stock_id.id, lot_id=self.prod_3_lot2.id ).qty_available self.assertAlmostEqual(prod_3_qty_lot_1, 40.0) self.assertAlmostEqual(prod_3_qty_lot_2, 5.0) def test_return_child_location(self): picking = self.picking_supplier_1.copy( { "location_dest_id": self.location_child_1.id, } ) picking.move_lines.unlink() picking.move_lines = [ ( 0, 0, { "product_id": self.prod_3.id, "name": self.prod_3.name, "product_uom": self.prod_3.uom_id.id, "location_id": picking.location_id.id, "location_dest_id": picking.location_dest_id.id, }, ) ] picking.action_confirm() for move in picking.move_lines: vals = { "picking_id": picking.id, "product_id": move.product_id.id, "product_uom_id": move.product_id.uom_id.id, "location_id": picking.location_id.id, "location_dest_id": picking.location_dest_id.id, "lot_id": self.prod_3_lot3.id, "qty_done": 30.0, } move.write({"move_line_ids": [(0, 0, vals)], "quantity_done": 30.0}) picking._action_done() self.return_request_supplier.write( { "line_ids": [ ( 0, 0, { "product_id": self.prod_3.id, "lot_id": self.prod_3_lot3.id, "quantity": 30.0, }, ), ], } ) self.return_request_supplier.action_confirm() returned_pickings = self.return_request_supplier.returned_picking_ids self.assertEqual( returned_pickings.mapped("move_line_ids.location_id"), self.location_child_1 ) def test_return_request_putaway_from_customer(self): """Test that the putaway strategy has been applied""" self.return_request_customer.write( {"line_ids": [(0, 0, {"product_id": self.prod_1.id, "quantity": 5.0})]} ) self.return_request_customer.action_confirm() stock_move_lines = self.return_request_customer.returned_picking_ids.mapped( "move_line_ids" ) # No putaway strategy is applied self.assertEqual( stock_move_lines.mapped("location_dest_id"), self.wh1.lot_stock_id ) # Create a putaway rule to test self.env["stock.putaway.rule"].create( { "product_id": self.prod_1.id, "location_in_id": self.wh1.lot_stock_id.id, "location_out_id": self.location_child_1.id, } ) self.return_request_customer.action_cancel() self.return_request_customer.action_cancel_to_draft() self.return_request_customer.action_confirm() stock_move_lines = self.return_request_customer.returned_picking_ids.mapped( "move_line_ids" ) self.assertEqual( stock_move_lines.mapped("location_dest_id"), self.location_child_1 )
40.111111
8,664
16,221
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from dateutil.relativedelta import relativedelta from odoo import fields from odoo.tests.common import TransactionCase class StockReturnRequestCase(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product_obj = cls.env["product.product"] cls.product_obj2 = cls.env["product.product"] cls.product_obj3 = cls.env["product.product"] cls.company = cls.env.ref("base.main_company") cls.prod_1 = cls.product_obj.create( { "name": "Test Product 1", "type": "product", "company_id": cls.company.id, } ) cls.prod_2 = cls.product_obj2.create( { "name": "Test Product 2", "type": "product", "company_id": cls.company.id, } ) cls.prod_3 = cls.product_obj3.create( { "name": "Test Product 3", "type": "product", "tracking": "lot", "company_id": cls.company.id, } ) cls.prod_3_lot1 = cls.env["stock.production.lot"].create( { "name": "TSTPROD3LOT0001", "product_id": cls.prod_3.id, "company_id": cls.company.id, } ) cls.prod_3_lot2 = cls.prod_3_lot1.copy( { "name": "TSTPROD3LOT0002", } ) cls.prod_3_lot3 = cls.prod_3_lot1.copy( { "name": "TSTPROD3LOT0003", } ) cls.wh1 = cls.env["stock.warehouse"].create( { "name": "TEST WH1", "code": "TST1", "company_id": cls.company.id, } ) # Locations (WH1 locations are created automatically) location_obj = cls.env["stock.location"] cls.supplier_loc = location_obj.create( { "name": "Test supplier location", "usage": "supplier", "company_id": cls.company.id, } ) cls.customer_loc = location_obj.create( { "name": "Test customer location", "usage": "customer", "company_id": cls.company.id, } ) # Create child locations cls.location_child_1 = location_obj.create( { "location_id": cls.wh1.lot_stock_id.id, "name": "Location child 1", "company_id": cls.company.id, } ) cls.location_child_2 = location_obj.create( { "location_id": cls.wh1.lot_stock_id.id, "name": "Location child 2", "company_id": cls.company.id, } ) # Create partners cls.partner_customer = cls.env["res.partner"].create( { "name": "Mr. Odoo", "property_stock_supplier": cls.supplier_loc.id, "property_stock_customer": cls.customer_loc.id, "company_id": cls.company.id, } ) cls.partner_supplier = cls.env["res.partner"].create( { "name": "Mrs. OCA", "property_stock_supplier": cls.supplier_loc.id, "property_stock_customer": cls.customer_loc.id, "company_id": cls.company.id, } ) # Create deliveries and receipts orders to have a history # First, some incoming pickings cls.picking_obj = cls.env["stock.picking"] cls.picking_supplier_1 = cls.picking_obj.create( { "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "partner_id": cls.partner_supplier.id, "company_id": cls.company.id, "picking_type_id": cls.wh1.in_type_id.id, "move_lines": [ ( 0, 0, { "name": cls.prod_1.name, "product_id": cls.prod_1.id, "product_uom_qty": 10.0, "product_uom": cls.prod_1.uom_id.id, "quantity_done": 10.0, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, }, ), ( 0, 0, { "name": cls.prod_2.name, "product_id": cls.prod_2.id, "product_uom_qty": 20.0, "product_uom": cls.prod_2.uom_id.id, "quantity_done": 20.0, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, }, ), ( 0, 0, { "name": cls.prod_3.name, "product_id": cls.prod_3.id, "product_uom_qty": 30.0, "product_uom": cls.prod_3.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, }, ), ( 0, 0, { "name": cls.prod_1.name, "product_id": cls.prod_1.id, "product_uom_qty": 50.0, "product_uom": cls.prod_1.uom_id.id, "location_dest_id": cls.location_child_1.id, "location_id": cls.supplier_loc.id, }, ), ( 0, 0, { "name": cls.prod_1.name, "product_id": cls.prod_1.id, "product_uom_qty": 75.0, "product_uom": cls.prod_1.uom_id.id, "location_dest_id": cls.location_child_2.id, "location_id": cls.supplier_loc.id, }, ), ], } ) move3 = cls.picking_supplier_1.move_lines.filtered( lambda x: x.product_id == cls.prod_3 ) move3.write( { "move_line_ids": [ ( 0, 0, { "picking_id": cls.picking_supplier_1.id, "lot_id": cls.prod_3_lot1.id, "product_id": cls.prod_3.id, "product_uom_id": cls.prod_3.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "qty_done": 20, }, ), ( 0, 0, { "picking_id": cls.picking_supplier_1.id, "product_id": cls.prod_3.id, "product_uom_id": cls.prod_3.uom_id.id, "lot_id": cls.prod_3_lot2.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "qty_done": 10, }, ), ], } ) move3.quantity_done = 30 cls.picking_supplier_1.action_confirm() cls.picking_supplier_1.action_assign() cls.picking_supplier_1._action_done() cls.picking_supplier_2 = cls.picking_supplier_1.copy( { "move_lines": [ ( 0, 0, { "name": cls.prod_1.name, "product_id": cls.prod_1.id, "product_uom_qty": 90.0, "product_uom": cls.prod_1.uom_id.id, "quantity_done": 90.0, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, }, ), ( 0, 0, { "name": cls.prod_2.name, "product_id": cls.prod_2.id, "product_uom_qty": 80.0, "product_uom": cls.prod_2.uom_id.id, "quantity_done": 90.0, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, }, ), ( 0, 0, { "name": cls.prod_3.name, "product_id": cls.prod_3.id, "product_uom_qty": 70.0, "product_uom": cls.prod_3.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, }, ), ], } ) move3 = cls.picking_supplier_2.move_lines.filtered( lambda x: x.product_id == cls.prod_3 ) move3.write( { "move_line_ids": [ ( 0, 0, { "picking_id": cls.picking_supplier_2.id, "lot_id": cls.prod_3_lot1.id, "product_id": cls.prod_3.id, "product_uom_id": cls.prod_3.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "qty_done": 70, }, ), ], } ) move3.quantity_done = 70 cls.picking_supplier_2.action_confirm() cls.picking_supplier_2.action_assign() cls.picking_supplier_2._action_done() # Test could run so fast that the move lines date would be in the same # second. We need to sort them by date, so we'll be faking the line # dates after the picking is done. cls.picking_supplier_2.move_lines.write( {"date": fields.Datetime.now() + relativedelta(seconds=1)} ) # We'll have 100 units of each product # No we deliver some products cls.picking_customer_1 = cls.picking_obj.create( { "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "company_id": cls.company.id, "partner_id": cls.partner_customer.id, "picking_type_id": cls.wh1.out_type_id.id, "move_lines": [ ( 0, 0, { "name": cls.prod_1.name, "product_id": cls.prod_1.id, "product_uom_qty": 10.0, "product_uom": cls.prod_1.uom_id.id, "quantity_done": 10.0, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, }, ), ( 0, 0, { "name": cls.prod_2.name, "product_id": cls.prod_2.id, "product_uom_qty": 20.0, "product_uom": cls.prod_2.uom_id.id, "quantity_done": 20.0, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, }, ), ], } ) cls.picking_customer_1.action_confirm() cls.picking_customer_1.action_assign() cls.picking_customer_1._action_done() cls.picking_customer_2 = cls.picking_customer_1.copy( { "move_lines": [ ( 0, 0, { "name": cls.prod_1.name, "product_id": cls.prod_1.id, "product_uom_qty": 10.0, "product_uom": cls.prod_1.uom_id.id, "quantity_done": 10.0, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, }, ), ( 0, 0, { "name": cls.prod_2.name, "product_id": cls.prod_2.id, "product_uom_qty": 10.0, "product_uom": cls.prod_2.uom_id.id, "quantity_done": 10.0, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, }, ), ], } ) cls.picking_customer_2.action_confirm() cls.picking_customer_2.action_assign() cls.picking_customer_2._action_done() # Test could run so fast that the move lines date would be in the same # second. We need to sort them by date, so we'll be faking the line # dates after the picking is done. cls.picking_customer_2.move_lines.write( {"date": fields.Datetime.now() + relativedelta(seconds=1)} ) # Stock in wh1.lot_stock_id # prod_1: 80.0 / prod_2: 70.0 / prod_3: 100.0 cls.return_request_obj = cls.env["stock.return.request"] # Return from customer cls.return_request_customer = cls.return_request_obj.create( { "partner_id": cls.partner_customer.id, "return_type": "customer", "return_to_location": cls.wh1.lot_stock_id.id, "return_from_location": cls.wh1.lot_stock_id.id, "return_order": "date desc, id desc", # Newer first } ) cls.return_request_customer.onchange_locations() cls.return_request_supplier = cls.return_request_customer.copy( { "partner_id": cls.partner_supplier.id, "return_to_location": cls.wh1.lot_stock_id.id, "return_from_location": cls.wh1.lot_stock_id.id, "return_type": "supplier", "return_order": "date asc, id desc", # Older first } ) cls.return_request_supplier.onchange_locations()
39.757353
16,221
4,033
py
PYTHON
15.0
# Copyright 2020 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SuggestReturnRequestLot(models.TransientModel): _name = "suggest.return.request.lot" _description = "Suggest lots for the return request line" request_line_id = fields.Many2one( comodel_name="stock.return.request.line", default=lambda self: self._default_request_line_id(), required=True, readonly=True, ondelete="cascade", ) lot_suggestion_mode = fields.Selection( selection=[ ("sum", "Total by lot"), ("detail", "Total by move"), ], default="sum", ) suggested_lot = fields.Selection( selection="_get_suggested_lots_selection", string="Suggested Lots", help="You can return these lots", ) suggested_lot_detail = fields.Selection( selection="_get_suggested_lots_detail_selection", string="Suggested Lots Detailed", help="You can return these lots", ) @api.model def _default_request_line_id(self): if self.env.context.get("active_model", False) != "stock.return.request.line": return False return self.env.context.get("active_id", False) def _get_suggested_lots_data(self): """Returns dict with returnable lots and qty""" if self.env.context.get("active_model", False) != "stock.return.request.line": return (False, False) request_line = self.request_line_id or self.request_line_id.browse( self.env.context.get("active_id") ) if not request_line: return (False, False) moves = self.env["stock.move"].search( request_line.with_context(ignore_rr_lots=True)._get_moves_domain(), order=request_line.request_id.return_order, ) suggested_lots_totals = {} suggested_lots_moves = {} for line in moves.mapped("move_line_ids"): qty = line.move_id._get_lot_returnable_qty(line.lot_id) suggested_lots_moves[line] = qty suggested_lots_totals.setdefault(line.lot_id, 0) suggested_lots_totals[line.lot_id] += qty return (suggested_lots_totals, suggested_lots_moves) def _get_suggested_lots_selection(self): """Return selection tuple with lots selections and qtys""" suggested_lots, suggested_lots_moves = self._get_suggested_lots_data() if not suggested_lots: return if self.lot_suggestion_mode == "detail": return [ ( ml.lot_id.id, "{date} - {name} - {moves}".format( date=ml.date, name=ml.name, moves=suggested_lots_moves[ml] ), ) for ml in suggested_lots_moves.keys() ] return [ (x.id, "{name} - {lots}".format(name=x.name, lots=suggested_lots[x])) for x in suggested_lots.keys() ] def _get_suggested_lots_detail_selection(self): """Return selection tuple with lots selections and qtys""" suggested_lots, suggested_lots_moves = self._get_suggested_lots_data() if not suggested_lots_moves: return return [ ( ml.lot_id.id, "{date} - {lot} - {ref} - {moves}".format( date=ml.date, lot=ml.lot_id.name, ref=ml.reference, moves=suggested_lots_moves[ml], ), ) for ml in suggested_lots_moves.keys() ] def action_confirm(self): if self.lot_suggestion_mode == "sum" and self.suggested_lot: self.request_line_id.lot_id = int(self.suggested_lot) elif self.lot_suggestion_mode == "detail" and self.suggested_lot_detail: self.request_line_id.lot_id = int(self.suggested_lot_detail)
38.409524
4,033
2,156
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class StockMove(models.Model): _inherit = "stock.move" qty_returnable = fields.Float( digits="Product Unit of Measure", string="Returnable Quantity", compute="_compute_qty_returnable", readonly=True, store=True, recursive=True, ) @api.depends( "state", "returned_move_ids", "quantity_done", "reserved_availability", "returned_move_ids.qty_returnable", ) def _compute_qty_returnable(self): """Looks for chained returned moves to compute how much quantity from the original can be returned""" for move in self.filtered(lambda x: x.state not in ["draft", "cancel"]): if not move.returned_move_ids: if move.state == "done": move.qty_returnable = move.quantity_done else: move.qty_returnable = move.reserved_availability continue move.returned_move_ids._compute_qty_returnable() move.qty_returnable = move.quantity_done - sum( move.returned_move_ids.mapped("qty_returnable") ) def _get_lot_returnable_qty(self, lot_id, qty=0): """Looks for chained returned moves to compute how much quantity from the original can be returned for a given lot""" for move in self.filtered(lambda x: x.state not in ["draft", "cancel"]): mls = move.move_line_ids.filtered(lambda x: x.lot_id == lot_id) if move.state == "done": qty += sum(mls.mapped("qty_done")) else: qty += sum(mls.mapped("product_uom_qty")) qty -= move.returned_move_ids._get_lot_returnable_qty(lot_id) return qty def _action_assign(self): if self.env.context.get("skip_assign_move", False): # Avoid assign stock moves allowing create stock move lines manually return return super(StockMove, self)._action_assign()
38.5
2,156
780
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class StockPicking(models.Model): _inherit = "stock.picking" stock_return_request_id = fields.Many2one( comodel_name="stock.return.request", ) def _create_backorder(self): """When we make a backorder of a picking in a return request, we want to have it linked to the return request itself""" backorders = super()._create_backorder() rbo = backorders.filtered("backorder_id.stock_return_request_id") for backorder in rbo: backorder.stock_return_request_id = ( backorder.backorder_id.stock_return_request_id ) return backorders
35.454545
780