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
704
py
PYTHON
15.0
# Copyright 2023 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock Picking Origin Destination Link", "summary": """ This addon link the pickings with their respective Origin and Destination Pickings. """, "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse Management", "license": "AGPL-3", "depends": ["stock"], "data": ["views/stock_picking_views.xml"], "installable": True, "pre_init_hook": "pre_init_hook", "post_init_hook": "post_init_hook", }
39.111111
704
3,376
py
PYTHON
15.0
# Copyright 2023 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestPickingOrigDestLink(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) # Models cls.product_model = cls.env["product.product"] cls.picking_model = cls.env["stock.picking"] cls.partner_model = cls.env["res.partner"] cls.move_model = cls.env["stock.move"] # Created records cls.product = cls.product_model.create({"name": "Test Product"}) cls.partner = cls.partner_model.create({"name": "Test Partner"}) # Data records cls.pick_type_in = cls.env.ref("stock.picking_type_in") cls.pick_type_out = cls.env.ref("stock.picking_type_out") cls.stock_location = cls.env.ref("stock.stock_location_stock") cls.customers_location = cls.env.ref("stock.stock_location_customers") cls.suppliers_location = cls.env.ref("stock.stock_location_suppliers") @classmethod def _create_in_picking(cls): picking = cls.picking_model.create( { "partner_id": cls.partner.id, "picking_type_id": cls.pick_type_in.id, "location_id": cls.suppliers_location.id, "location_dest_id": cls.stock_location.id, } ) move_vals = { "picking_id": picking.id, "product_id": cls.product.id, "location_dest_id": cls.stock_location.id, "location_id": cls.suppliers_location.id, "name": cls.product.name, "product_uom_qty": 1, "product_uom": cls.product.uom_id.id, } cls.move_model.create(move_vals) return picking @classmethod def _create_out_picking(cls): picking = cls.picking_model.create( { "partner_id": cls.partner.id, "picking_type_id": cls.pick_type_out.id, "location_id": cls.stock_location.id, "location_dest_id": cls.customers_location.id, } ) move_vals = { "picking_id": picking.id, "product_id": cls.product.id, "location_id": cls.stock_location.id, "location_dest_id": cls.customers_location.id, "name": cls.product.name, "product_uom_qty": 1, "product_uom": cls.product.uom_id.id, } cls.move_model.create(move_vals) return picking @classmethod def _link_moves_from_pickings(cls, in_picking, out_picking): in_move_ids = in_picking.move_lines out_move_ids = out_picking.move_lines return in_move_ids.write({"move_dest_ids": out_move_ids}) def test_01_in_out_pickings(self): # create in and out picking and links their moves in_pick = self._create_in_picking() out_pick = self._create_out_picking() result = self._link_moves_from_pickings(in_pick, out_pick) self.assertTrue(result) # check that pickings have also been linked self.assertEqual(in_pick.dest_picking_ids, out_pick) self.assertEqual(out_pick.orig_picking_ids, in_pick)
38.804598
3,376
1,756
py
PYTHON
15.0
# Copyright 2023 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class StockPicking(models.Model): _inherit = "stock.picking" orig_picking_ids = fields.Many2many( comodel_name="stock.picking", relation="stock_picking_orig_dest_rel", column1="dest_picking_id", column2="orig_picking_id", string="Origin Transfer/s", compute="_compute_origin_dest_picking", store=True, readonly=True, ) dest_picking_ids = fields.Many2many( comodel_name="stock.picking", relation="stock_picking_orig_dest_rel", column1="orig_picking_id", column2="dest_picking_id", string="Destination Transfer/s", compute="_compute_origin_dest_picking", store=True, readonly=True, ) def _get_orig_picking_ids(self): """ Returns the Origin Pickings from a single picking. Done in method to be inherited in other modules, if needed. """ self.ensure_one() return self.mapped("move_lines.move_orig_ids.picking_id") def _get_dest_picking_ids(self): """ Returns the Destination Pickings from a single picking. Done in method to be inherited in other modules, if needed. """ self.ensure_one() return self.mapped("move_lines.move_dest_ids.picking_id") @api.depends("move_lines.move_orig_ids", "move_lines.move_dest_ids") def _compute_origin_dest_picking(self): for picking in self: picking.orig_picking_ids = picking._get_orig_picking_ids() picking.dest_picking_ids = picking._get_dest_picking_ids()
34.431373
1,756
616
py
PYTHON
15.0
# Copyright 2014 Camptocamp, Akretion, Numérigraphe # Copyright 2016 Sodexis # Copyright 2019 Sergio Díaz <sergiodm.1989@gmail.com> # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Ignore planned receptions in quantity available to promise", "version": "15.0.1.0.0", "depends": ["stock_available"], "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "Camptocamp,Sodexis,Odoo Community Association (OCA),Sergio Díaz", "license": "AGPL-3", "category": "Hidden", "installable": True, }
38.3125
613
4,781
py
PYTHON
15.0
# Copyright 2014 Camptocamp, Akretion, Numérigraphe # Copyright 2016 Sodexis # Copyright 2019 Sergio Díaz <sergiodm.1989@gmail.com> # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestStockLogisticsWarehouse(TransactionCase): def test01_stock_levels(self): """ Checking that immediately_usable_qty actually reflects the variations in stock, both on product and template. """ moveObj = self.env["stock.move"] templateObj = self.env["product.template"] supplier_location = self.env.ref("stock.stock_location_suppliers") stock_location = self.env.ref("stock.stock_location_stock") customer_location = self.env.ref("stock.stock_location_customers") uom_unit = self.env.ref("uom.product_uom_unit") # Create product template with 2 variant templateAB = templateObj.create( {"name": "templAB", "uom_id": uom_unit.id, "type": "product"} ) templateAB = templateAB.with_context(test_stock_available_immediately=True) self.env["product.template.attribute.line"].create( { "product_tmpl_id": templateAB.id, "attribute_id": self.env.ref("product.product_attribute_2").id, "value_ids": [ ( 6, 0, [ self.env.ref("product.product_attribute_value_3").id, self.env.ref("product.product_attribute_value_4").id, ], ) ], } ) # Create product A and B productA = templateAB.product_variant_ids[0] productB = templateAB.product_variant_ids[1] # Create a stock move from INCOMING to STOCK stockMoveInA = moveObj.create( { "location_id": supplier_location.id, "location_dest_id": stock_location.id, "name": "MOVE INCOMING -> STOCK ", "product_id": productA.id, "product_uom": productA.uom_id.id, "product_uom_qty": 2, } ) stockMoveInB = moveObj.create( { "location_id": supplier_location.id, "location_dest_id": stock_location.id, "name": "MOVE INCOMING -> STOCK ", "product_id": productB.id, "product_uom": productB.uom_id.id, "product_uom_qty": 3, } ) def compare_product_usable_qty(product, value): # Refresh, because the function field is not recalculated between # transactions product.refresh() self.assertEqual(product.immediately_usable_qty, value) compare_product_usable_qty(productA, 0) compare_product_usable_qty(templateAB, 0) stockMoveInA._action_confirm() compare_product_usable_qty(productA, 0) compare_product_usable_qty(templateAB, 0) stockMoveInA._action_assign() compare_product_usable_qty(productA, 0) compare_product_usable_qty(templateAB, 0) stockMoveInA.move_line_ids.write({"qty_done": 2.0}) stockMoveInA._action_done() compare_product_usable_qty(productA, 2) compare_product_usable_qty(templateAB, 2) # will directly trigger action_done on productB stockMoveInB._action_confirm() stockMoveInB._action_assign() stockMoveInB.move_line_ids.write({"qty_done": 3.0}) stockMoveInB._action_done() compare_product_usable_qty(productA, 2) compare_product_usable_qty(productB, 3) compare_product_usable_qty(templateAB, 5) # Create a stock move from STOCK to CUSTOMER stockMoveOutA = moveObj.create( { "location_id": stock_location.id, "location_dest_id": customer_location.id, "name": " STOCK --> CUSTOMER ", "product_id": productA.id, "product_uom": productA.uom_id.id, "product_uom_qty": 1, "state": "confirmed", } ) stockMoveOutA._action_confirm() stockMoveOutA._action_assign() stockMoveOutA.move_line_ids.write({"qty_done": 1.0}) stockMoveOutA._action_done() compare_product_usable_qty(productA, 1) compare_product_usable_qty(templateAB, 4) # Potential Qty is set as 0.0 by default self.assertEqual(templateAB.potential_qty, 0.0) self.assertEqual(productA.potential_qty, 0.0)
38.232
4,779
953
py
PYTHON
15.0
# Copyright 2014 Camptocamp, Akretion, Numérigraphe # Copyright 2016 Sodexis # Copyright 2019 Sergio Díaz <sergiodm.1989@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models from odoo.tools import config class ProductProduct(models.Model): _inherit = "product.product" def _compute_available_quantities_dict(self): res, stock_dict = super()._compute_available_quantities_dict() if config["test_enable"] and not self.env.context.get( "test_stock_available_immediately" ): return res, stock_dict for product in self: res[product.id]["immediately_usable_qty"] -= stock_dict[product.id][ "incoming_qty" ] return res, stock_dict @api.depends("virtual_available", "incoming_qty") def _compute_available_quantities(self): return super()._compute_available_quantities()
35.222222
951
841
py
PYTHON
15.0
# Copyright 2015 Mikel Arregi - AvanzOSC # Copyright 2017 ForgeFlow - Jordi Ballester # Copyright 2018 Fanha Giang # Copyright 2018 Tecnativa - Vicent Cubells # Copyright 2016-2018 Tecnativa - Pedro M. Baeza # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { "name": "Stock - Manual Quant Assignment", "version": "15.0.1.2.1", "category": "Warehouse", "license": "AGPL-3", "author": "AvanzOSC, " "Tecnativa, " "ForgeFlow, " "Fanha Giang, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "depends": ["stock"], "data": [ "wizard/assign_manual_quants_view.xml", "views/stock_move_view.xml", "security/ir.model.access.csv", "views/stock_picking_type_views.xml", ], "installable": True, }
31.148148
841
7,119
py
PYTHON
15.0
# Copyright 2015 Oihane Crucelaegui - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestStockQuantManualAssign(TransactionCase): def setUp(self): super(TestStockQuantManualAssign, self).setUp() self.quant_model = self.env["stock.quant"] self.picking_model = self.env["stock.picking"] self.location_model = self.env["stock.location"] self.move_model = self.env["stock.move"] self.quant_assign_wizard = self.env["assign.manual.quants"] self.ModelDataObj = self.env["ir.model.data"] self.product = self.env["product.product"].create( {"name": "Product 4 test", "type": "product"} ) self.location_src = self.env.ref("stock.stock_location_locations_virtual") self.location_dst = self.env.ref("stock.stock_location_customers") self.picking_type_out = self.ModelDataObj._xmlid_to_res_id( "stock.picking_type_out" ) self.env["stock.picking.type"].browse( self.picking_type_out ).reservation_method = "manual" self.location1 = self.location_model.create( { "name": "Location 1", "usage": "internal", "location_id": self.location_src.id, } ) self.location2 = self.location_model.create( { "name": "Location 2", "usage": "internal", "location_id": self.location_src.id, } ) self.location3 = self.location_model.create( { "name": "Location 3", "usage": "internal", "location_id": self.location_src.id, } ) self.picking_type = self.env.ref("stock.picking_type_out") self.quant1 = self.quant_model.sudo().create( { "product_id": self.product.id, "quantity": 100.0, "location_id": self.location1.id, } ) self.quant2 = self.quant_model.sudo().create( { "product_id": self.product.id, "quantity": 100.0, "location_id": self.location2.id, } ) self.quant3 = self.quant_model.sudo().create( { "product_id": self.product.id, "quantity": 100.0, "location_id": self.location3.id, } ) self.move = self.move_model.create( { "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 400.0, "product_uom": self.product.uom_id.id, "location_id": self.location_src.id, "location_dest_id": self.location_dst.id, "picking_type_id": self.picking_type.id, } ) self.move._action_confirm() def test_quant_assign_wizard(self): wizard = self.quant_assign_wizard.with_context(active_id=self.move.id).create( {} ) self.assertEqual( len(wizard.quants_lines.ids), 3, "Three quants created, three quants got by default", ) self.assertEqual( len(wizard.quants_lines.filtered("selected").ids), 0, "None of the quants must have been selected", ) self.assertEqual(wizard.lines_qty, 0.0, "None selected must give 0") self.assertEqual( sum(line.qty for line in wizard.quants_lines), self.move.reserved_availability, ) self.assertEqual(wizard.move_qty, self.move.product_uom_qty) def test_quant_assign_wizard_constraint(self): wizard = self.quant_assign_wizard.with_context(active_id=self.move.id).create( {} ) self.assertEqual( len(wizard.quants_lines.ids), 3, "Three quants created, three quants got by default", ) self.assertEqual( len(wizard.quants_lines.filtered("selected").ids), 0, "None of the quants must have been selected", ) self.assertEqual(wizard.lines_qty, 0.0, "None selected must give 0") with self.assertRaises(ValidationError): wizard.write( { "quants_lines": [ (1, wizard.quants_lines[:1].id, {"selected": True, "qty": 500}) ] } ) def test_quant_manual_assign(self): wizard = self.quant_assign_wizard.with_context(active_id=self.move.id).create( {} ) self.assertEqual( len(wizard.quants_lines.ids), 3, "Three quants created, three quants got by default", ) wizard.quants_lines[0].write({"selected": True}) wizard.quants_lines[0]._onchange_selected() wizard.quants_lines[1].write({"selected": True, "qty": 50.0}) self.assertEqual(wizard.lines_qty, 150.0) self.assertEqual(wizard.move_qty, 250.0) wizard.assign_quants() self.assertAlmostEqual( len(self.move.move_line_ids), 2, "There are 2 quants selected", ) self.assertFalse(self.move.picking_type_id.auto_fill_qty_done) self.assertEqual(sum(self.move.move_line_ids.mapped("qty_done")), 0.0) def test_quant_manual_assign_auto_fill_qty_done(self): wizard = self.quant_assign_wizard.with_context(active_id=self.move.id).create( {} ) wizard.quants_lines[0].write({"selected": True}) wizard.quants_lines[0]._onchange_selected() wizard.quants_lines[1].write({"selected": True, "qty": 50.0}) self.assertEqual(wizard.lines_qty, 150.0) self.picking_type.auto_fill_qty_done = True wizard.assign_quants() self.assertTrue(self.move.picking_type_id.auto_fill_qty_done) self.assertEqual(sum(self.move.move_line_ids.mapped("qty_done")), 150.0) def test_quant_assign_wizard_after_availability_check(self): self.move._action_assign() wizard = self.quant_assign_wizard.with_context(active_id=self.move.id).create( {} ) self.assertEqual( len(wizard.quants_lines.ids), 3, "Three quants created, three quants got by default", ) self.assertEqual( len(wizard.quants_lines.filtered("selected").ids), 3, "All the quants must have been selected", ) self.assertEqual(wizard.lines_qty, 300.0) self.assertEqual(wizard.move_qty, 100.0) self.assertEqual( len(wizard.quants_lines.filtered("selected")), len(self.move.move_line_ids) ) self.assertEqual( sum(line.qty for line in wizard.quants_lines), self.move.reserved_availability, )
37.867021
7,119
9,429
py
PYTHON
15.0
# Copyright 2015 Mikel Arregi - AvanzOSC # Copyright 2015 Oihane Crucelaegui - AvanzOSC # Copyright 2018 Fanha Giang # Copyright 2018 Tecnativa - Vicent Cubells # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.tools.float_utils import float_compare class AssignManualQuants(models.TransientModel): _name = "assign.manual.quants" _description = "Assign Manual Quants" @api.constrains("quants_lines") def _check_qty(self): precision_digits = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) for record in self.filtered("quants_lines"): if ( float_compare( record.lines_qty, record.move_id.product_qty, precision_digits=precision_digits, ) > 0 ): raise ValidationError(_("Quantity is higher than the needed one")) @api.depends("move_id", "quants_lines", "quants_lines.qty") def _compute_qties(self): for record in self: record.lines_qty = sum( record.quants_lines.filtered("selected").mapped("qty") ) record.move_qty = record.move_id.product_qty - record.lines_qty lines_qty = fields.Float( string="Reserved qty", compute="_compute_qties", digits="Product Unit of Measure", ) move_qty = fields.Float( string="Remaining qty", compute="_compute_qties", digits="Product Unit of Measure", ) quants_lines = fields.One2many( "assign.manual.quants.lines", "assign_wizard", string="Quants" ) move_id = fields.Many2one( comodel_name="stock.move", string="Move", ) def assign_quants(self): move = self.move_id move._do_unreserve() for line in self.quants_lines: line._assign_quant_line() if move.picking_type_id.auto_fill_qty_done: # Auto-fill all lines as done for ml in move.move_line_ids: ml.qty_done = ml.product_qty move._recompute_state() move.mapped("picking_id")._compute_state() return {} @api.model def _domain_for_available_quants(self, move): return [ ("location_id", "child_of", move.location_id.id), ("product_id", "=", move.product_id.id), ("quantity", ">", 0), ] @api.model def _get_available_quants(self, move): domain = self._domain_for_available_quants(move) return self.env["stock.quant"].search(domain) @api.model def default_get(self, fields): res = super(AssignManualQuants, self).default_get(fields) move = self.env["stock.move"].browse(self.env.context["active_id"]) available_quants = self._get_available_quants(move) q_lines = [] for quant in available_quants: line = self._prepare_wizard_line(move, quant) q_lines.append(line) res.update({"quants_lines": [(0, 0, x) for x in q_lines], "move_id": move.id}) return res @api.model def _prepare_wizard_line(self, move, quant): line = { "quant_id": quant.id, "on_hand": quant.quantity, "location_id": quant.location_id.id, "lot_id": quant.lot_id.id, "package_id": quant.package_id.id, "owner_id": quant.owner_id.id, "selected": False, } move_lines = move.move_line_ids.filtered( lambda ml: ( ml.location_id == quant.location_id and ml.lot_id == quant.lot_id and ml.owner_id == quant.owner_id and ml.package_id == quant.package_id ) ) line["qty"] = sum(move_lines.mapped("product_uom_qty")) line["selected"] = bool(line["qty"]) line["reserved"] = quant.reserved_quantity - line["qty"] return line class AssignManualQuantsLines(models.TransientModel): _name = "assign.manual.quants.lines" _description = "Assign Manual Quants Lines" _rec_name = "quant_id" _order = "location_id, lot_id, package_id" assign_wizard = fields.Many2one( comodel_name="assign.manual.quants", string="Move", required=True, ondelete="cascade", ) quant_id = fields.Many2one( comodel_name="stock.quant", string="Quant", required=True, ondelete="cascade", ) # Fields below are storable in order to be able to order by them. However, # there is a side effect: It is not possible to directly read the related # fields, e.g `self.lot_id`, because they are stored fields and have a group # restriction, so an access error would raise. To work around it, we should # access these fields from the quant: `self.quant_id.lot_id`. location_id = fields.Many2one( comodel_name="stock.location", string="Location", related="quant_id.location_id", groups="stock.group_stock_multi_locations", store=True, ) lot_id = fields.Many2one( comodel_name="stock.production.lot", string="Lot", related="quant_id.lot_id", groups="stock.group_production_lot", store=True, ) package_id = fields.Many2one( comodel_name="stock.quant.package", string="Package", related="quant_id.package_id", groups="stock.group_tracking_lot", store=True, ) owner_id = fields.Many2one( comodel_name="res.partner", string="Owner", related="quant_id.owner_id", groups="stock.group_tracking_owner", store=True, ) # This is not correctly shown as related or computed, so we make it regular on_hand = fields.Float( readonly=True, digits="Product Unit of Measure", ) reserved = fields.Float( string="Others Reserved", digits="Product Unit of Measure", readonly=True ) selected = fields.Boolean(string="Select") qty = fields.Float(string="QTY", digits="Product Unit of Measure") @api.onchange("selected") def _onchange_selected(self): for record in self: if not record.selected: record.qty = 0 elif not record.qty: # This takes current "snapshot" situation, so that we don't # have to compute each time if current reserved quantity is # for this current move. If other operations change available # quantity on quant, a constraint would be raised later on # validation. quant_qty = record.on_hand - record.reserved remaining_qty = record.assign_wizard.move_qty record.qty = min(quant_qty, remaining_qty) @api.constrains("qty") def _check_qty(self): precision_digits = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) for record in self.filtered("qty"): quant = record.quant_id move_lines = record.assign_wizard.move_id.move_line_ids.filtered( lambda ml: ( ml.location_id == quant.location_id and ml.lot_id == quant.lot_id ) ) reserved = quant.reserved_quantity - sum( move_lines.mapped("product_uom_qty") ) if ( float_compare( record.qty, record.quant_id.quantity - reserved, precision_digits=precision_digits, ) > 0 ): raise ValidationError( _( "Selected line quantity is higher than the available " "one. Maybe an operation with this product has been " "done meanwhile or you have manually increased the " "suggested value." ) ) def _assign_quant_line(self): self.ensure_one() quant = self.env["stock.quant"] precision_digits = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) move = self.assign_wizard.move_id if float_compare(self.qty, 0.0, precision_digits=precision_digits) > 0: available_quantity = quant._get_available_quantity( move.product_id, self.quant_id.location_id, lot_id=self.quant_id.lot_id, package_id=self.quant_id.package_id, owner_id=self.quant_id.owner_id, ) if ( float_compare( available_quantity, 0.0, precision_digits=precision_digits ) <= 0 ): return move._update_reserved_quantity( self.qty, available_quantity, self.quant_id.location_id, lot_id=self.quant_id.lot_id, package_id=self.quant_id.package_id, owner_id=self.quant_id.owner_id, strict=True, )
36.126437
9,429
431
py
PYTHON
15.0
# Copyright 2021 Quartile Limited # 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" auto_fill_qty_done = fields.Boolean( "Auto-fill Quantity Done", help="Select this in case done quantity of the stock move line should " "be auto-filled when quants are manually assigned.", )
30.785714
431
2,970
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, fields from odoo.exceptions import UserError from odoo.tools.float_utils import float_compare from odoo.addons.stock.models.stock_quant import StockQuant def post_load_hook(): def _apply_inventory_discrepancy(self): """Override method to avoid inline group validation""" move_vals = [] # START HOOK: - Allow specific group to validate inventory # - Allow validate on pending status if ( not self.user_has_groups("stock.group_stock_manager") and not self.user_has_groups( "stock_inventory_discrepancy.group_stock_inventory_validation" ) and not self.user_has_groups( "stock_inventory_discrepancy.group_stock_inventory_validation_always" ) ): raise UserError( _("Only a stock manager can validate an inventory adjustment.") ) # Allow to write last_inventory_date on stock.location self = self.sudo() # END HOOK for quant in self: # Create and validate a move so that the quant matches its `inventory_quantity`. if ( float_compare( quant.inventory_diff_quantity, 0, precision_rounding=quant.product_uom_id.rounding, ) > 0 ): move_vals.append( quant._get_inventory_move_values( quant.inventory_diff_quantity, quant.product_id.with_company( quant.company_id ).property_stock_inventory, quant.location_id, ) ) else: move_vals.append( quant._get_inventory_move_values( -quant.inventory_diff_quantity, quant.location_id, quant.product_id.with_company( quant.company_id ).property_stock_inventory, out=True, ) ) moves = ( self.env["stock.move"].with_context(inventory_mode=False).create(move_vals) ) moves._action_done() self.location_id.write({"last_inventory_date": fields.Date.today()}) date_by_location = { loc: loc._get_next_inventory_date() for loc in self.mapped("location_id") } for quant in self: quant.inventory_date = date_by_location[quant.location_id] self.write({"inventory_quantity": 0, "user_id": False}) self.write({"inventory_diff_quantity": 0}) StockQuant._patch_method("_apply_inventory", _apply_inventory_discrepancy)
39.078947
2,970
993
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow S.L. (http://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Stock Inventory Discrepancy", "summary": "Adds the capability to show the discrepancy of every line in " "an inventory and to block the inventory validation when the " "discrepancy is over a user defined threshold.", "version": "15.0.1.0.1", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse", "depends": ["stock"], "data": [ "security/stock_inventory_discrepancy_security.xml", "security/ir.model.access.csv", "views/stock_quant_view.xml", "views/stock_warehouse_view.xml", "views/stock_location_view.xml", "wizards/confirm_discrepancy_wiz.xml", ], "license": "AGPL-3", "post_load": "post_load_hook", "installable": True, "application": False, }
39.72
993
347
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): openupgrade.load_data( env.cr, "stock_inventory_discrepancy", "migrations/15.0.1.0.0/noupdate_changes.xml", )
26.692308
347
9,225
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.exceptions import UserError from odoo.tests.common import TransactionCase, tagged @tagged("post_install", "-at_install") class TestInventoryDiscrepancy(TransactionCase): def setUp(self): super().setUp() self.obj_location = self.env["stock.location"] self.obj_product = self.env["product.product"] self.obj_warehouse = self.env["stock.warehouse"] self.obj_quant = self.env["stock.quant"] self.product1 = self.obj_product.create( {"name": "Test Product 1", "type": "product", "default_code": "PROD1"} ) self.product2 = self.obj_product.create( {"name": "Test Product 2", "type": "product", "default_code": "PROD2"} ) self.test_loc = self.obj_location.create( {"name": "Test Location", "usage": "internal", "discrepancy_threshold": 10} ) self.test_wh = self.obj_warehouse.create( {"name": "Test WH", "code": "T", "discrepancy_threshold": 20} ) self.obj_location._parent_store_compute() # Create Stock manager able to force validation on inventories. group_stock_man = self.env.ref("stock.group_stock_manager") group_inventory_all = self.env.ref( "stock_inventory_discrepancy.group_stock_inventory_validation_always" ) group_employee = self.env.ref("base.group_user") self.manager = self.env["res.users"].create( { "name": "Test Manager", "login": "manager", "email": "test.manager@example.com", "groups_id": [(6, 0, [group_stock_man.id, group_inventory_all.id])], } ) group_stock_user = self.env.ref("stock.group_stock_user") group_inventory = self.env.ref( "stock_inventory_discrepancy.group_stock_inventory_validation" ) self.user = self.env["res.users"].create( { "name": "Test User", "login": "user", "email": "test.user@example.com", "groups_id": [(6, 0, [group_stock_user.id, group_inventory.id])], } ) self.user_2 = self.env["res.users"].create( { "name": "Test User 2", "login": "user_2", "email": "test2.user@example.com", "groups_id": [(6, 0, [group_stock_user.id, group_inventory_all.id])], } ) self.no_user = self.env["res.users"].create( { "name": "No User", "login": "no_user", "email": "test.no_user@example.com", "groups_id": [(6, 0, [group_employee.id])], } ) self.quant_line1 = self.obj_quant.with_context(inventory_mode=True).create( { "product_id": self.product1.id, "quantity": 2.0, "location_id": self.test_loc.id, } ) self.quant_line2 = self.obj_quant.with_context(inventory_mode=True).create( { "product_id": self.product2.id, "quantity": 4.0, "location_id": self.test_loc.id, } ) # starting_inv = self.obj_inventory.create( # { # "name": "Starting inventory", # "line_ids": [ # ( # 0, # 0, # { # "product_id": self.product1.id, # "product_uom_id": self.env.ref("uom.product_uom_unit").id, # "product_qty": 2.0, # "location_id": self.test_loc.id, # }, # ), # ( # 0, # 0, # { # "product_id": self.product2.id, # "product_uom_id": self.env.ref("uom.product_uom_unit").id, # "product_qty": 4.0, # "location_id": self.test_loc.id, # }, # ), # ], # } # ) # starting_inv.action_force_done() def test_discrepancy_validation(self): """Tests the new workflow""" # quant_line1 is over discrepancy but quant_line2 is not self.quant_line1.write( { "inventory_quantity": 3.0, "inventory_quantity_set": True, } ) self.quant_line1._compute_discrepancy_threshold() self.assertEqual(self.quant_line1.discrepancy_threshold, 10) self.assertEqual(self.quant_line1.discrepancy_percent, 50) self.assertTrue(self.quant_line1.has_over_discrepancy) self.quant_line2.inventory_quantity = 4.1 self.quant_line2._compute_discrepancy_threshold() self.assertEqual(self.quant_line1.discrepancy_threshold, 10) self.assertEqual(self.quant_line2.discrepancy_percent, 2.5) self.assertFalse(self.quant_line2.has_over_discrepancy) # Select all quants and try to apply the quantity adjustment all_quants = self.quant_line1 | self.quant_line2 action_dic = all_quants.with_user(self.user).action_apply_inventory() model_wiz = action_dic["res_model"] wiz = ( self.env[model_wiz] .with_user(self.user) .with_context( action_dic["context"], active_model="stock.quant", active_ids=all_quants.ids, ) .create({}) ) # Apply the wizard with a stock user will get an error self.assertEqual(wiz.discrepancy_quant_ids, self.quant_line1) with self.assertRaises(UserError): wiz.button_apply() # Apply the wizard with a stock manager will apply the adjustment wiz.with_user(self.manager).button_apply() self.assertEqual(self.quant_line1.quantity, 3) self.assertEqual(self.quant_line2.quantity, 4.1) def test_discrepancy_validation_always(self): """Tests the new workflow""" self.quant_line1.inventory_quantity = 3.0 self.quant_line1._compute_discrepancy_threshold() self.assertEqual(self.quant_line1.discrepancy_threshold, 10) self.assertEqual(self.quant_line1.discrepancy_percent, 50) self.assertTrue(self.quant_line1.has_over_discrepancy) self.quant_line2.inventory_quantity = 4.1 self.quant_line2._compute_discrepancy_threshold() self.assertEqual(self.quant_line1.discrepancy_threshold, 10) self.assertEqual(self.quant_line2.discrepancy_percent, 2.5) self.assertFalse(self.quant_line2.has_over_discrepancy) # Select all quants and try to apply the quantity adjustment all_quants = self.quant_line1 | self.quant_line2 action_dic = all_quants.with_user(self.user).action_apply_inventory() model_wiz = action_dic["res_model"] wiz = ( self.env[model_wiz] .with_user(self.user) .with_context( action_dic["context"], active_model="stock.quant", active_ids=all_quants.ids, ) .create({}) ) # Apply the wizard with a stock user will get an error self.assertEqual(wiz.discrepancy_quant_ids, self.quant_line1) with self.assertRaises(UserError): wiz.button_apply() # Apply the wizard with a stock manager will apply the adjustment wiz.with_user(self.user_2).button_apply() self.assertEqual(self.quant_line1.quantity, 3) self.assertEqual(self.quant_line2.quantity, 4.1) def test_warehouse_threshold(self): """Tests the behaviour if the threshold is set on the WH.""" quant_other_loc = self.obj_quant.with_context(inventory_mode=True).create( { "product_id": self.product1.id, "inventory_quantity": 3.0, "location_id": self.test_wh.lot_stock_id.id, } ) self.assertEqual(quant_other_loc.discrepancy_threshold, 20) def test_propagate_discrepancy_threshold(self): view_test_loc = self.obj_location.create( {"name": "Test Location", "usage": "view", "discrepancy_threshold": 0.1} ) child_test_loc = self.obj_location.create( { "name": "Child Test Location", "usage": "internal", "discrepancy_threshold": 0.2, "location_id": view_test_loc.id, } ) view_test_loc.write( {"discrepancy_threshold": 0.3, "propagate_discrepancy_threshold": True} ) self.assertEqual( child_test_loc.discrepancy_threshold, 0.3, "Threshold Discrepancy wrongly propagated", )
40.460526
9,225
1,344
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class StockLocation(models.Model): _inherit = "stock.location" discrepancy_threshold = fields.Float( string="Maximum Discrepancy Rate Threshold", digits=(3, 2), help="Maximum Discrepancy Rate allowed for any product when doing " "an Inventory Adjustment. Thresholds defined in Locations have " "preference over Warehouse's ones.", ) propagate_discrepancy_threshold = fields.Boolean( string="Propagate discrepancy threshold", help="Propagate Maximum Discrepancy Rate Threshold to child locations", ) def write(self, values): res = super().write(values) # Set the discrepancy threshold for all child locations if values.get("discrepancy_threshold", False): for location in self.filtered( lambda loc: loc.propagate_discrepancy_threshold and loc.child_ids ): location.child_ids.write( { "discrepancy_threshold": values["discrepancy_threshold"], "propagate_discrepancy_threshold": True, } ) return res
37.333333
1,344
545
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow S.L. # (http://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class StockWarehouse(models.Model): _inherit = "stock.warehouse" discrepancy_threshold = fields.Float( string="Maximum Discrepancy Rate Threshold", digits=(3, 2), help="Maximum Discrepancy Rate allowed for any product when doing " "an Inventory Adjustment. Threshold defined in involved Location " "has preference.", )
32.058824
545
2,573
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class StockQuant(models.Model): _inherit = "stock.quant" discrepancy_percent = fields.Float( string="Discrepancy percent (%)", compute="_compute_discrepancy", digits=(3, 2), help="The discrepancy expressed in percent with theoretical quantity " "as basis", group_operator="avg", store=True, compute_sudo=True, ) discrepancy_threshold = fields.Float( string="Threshold (%)", digits=(3, 2), help="Maximum Discrepancy Rate Threshold", compute="_compute_discrepancy_threshold", ) has_over_discrepancy = fields.Boolean( compute="_compute_has_over_discrepancy", ) @api.depends("quantity", "inventory_quantity") def _compute_discrepancy(self): for quant in self: if not quant.quantity or not quant.inventory_quantity_set: quant.discrepancy_percent = 0 else: quant.discrepancy_percent = abs( 100 * (quant.inventory_diff_quantity) / quant.quantity ) def _compute_discrepancy_threshold(self): for quant in self: whs = quant.location_id.warehouse_id if quant.location_id.discrepancy_threshold > 0.0: quant.discrepancy_threshold = quant.location_id.discrepancy_threshold elif whs.discrepancy_threshold > 0.0: quant.discrepancy_threshold = whs.discrepancy_threshold else: quant.discrepancy_threshold = False def _compute_has_over_discrepancy(self): for rec in self: rec.has_over_discrepancy = ( rec.discrepancy_percent > rec.discrepancy_threshold ) def action_apply_inventory(self): if self.env.context.get("skip_exceeded_discrepancy", False): return super().action_apply_inventory() over_discrepancy = self.filtered(lambda r: r.has_over_discrepancy) if over_discrepancy: action = self.env["ir.actions.act_window"]._for_xml_id( "stock_inventory_discrepancy.confirm_discrepancy_action" ) action["context"] = dict( self._context.copy(), discrepancy_quant_ids=over_discrepancy.ids, active_ids=self.ids, ) return action return super().action_apply_inventory()
37.289855
2,573
1,386
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import Command, _, fields, models from odoo.exceptions import UserError class ConfirmDiscrepancyWiz(models.TransientModel): _name = "confirm.discrepancy.wiz" _description = "Confim discrepancy wizard" def _default_discrepancy_quant_ids(self): return [ Command.set( self.env["stock.quant"] .browse(self.env.context.get("discrepancy_quant_ids")) .ids ) ] discrepancy_quant_ids = fields.Many2many( comodel_name="stock.quant", readonly=True, default=_default_discrepancy_quant_ids, ) def button_apply(self): self.ensure_one() if not self.user_has_groups( "stock_inventory_discrepancy.group_stock_inventory_validation_always" ): raise UserError( _( "You cannot apply inventory adjustments " "if there are products that exceed the discrepancy threshold. " "Only users with rights to apply them can proceed." ) ) self.env["stock.quant"].browse(self.env.context.get("active_ids")).with_context( skip_exceeded_discrepancy=True ).action_apply_inventory()
33.804878
1,386
572
py
PYTHON
15.0
# Copyright 2023 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Stock Request Separate Picking", "summary": "Separate one picking per one stock request", "version": "15.0.1.0.0", "license": "LGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "Ecosoft, Odoo Community Association (OCA)", "category": "Warehouse Management", "depends": ["stock_request"], "data": ["views/res_config_settings_views.xml"], "installable": True, }
38.133333
572
3,994
py
PYTHON
15.0
# Copyright 2023 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields from odoo.addons.stock_request.tests import test_stock_request class TestStockRequestSeparatePicking(test_stock_request.TestStockRequest): def setUp(self): super().setUp() self.expected_date = fields.Datetime.now() self.main_company.stock_request_allow_separate_picking = True def test_create_stock_request(self): vals = { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": self.expected_date, } self.product.route_ids = [(6, 0, self.route.ids)] # Create stock requests stock_request_1 = self.stock_request.with_user(self.stock_request_user).create( vals ) stock_request_2 = self.stock_request.with_user(self.stock_request_user).create( vals ) self.assertEqual(stock_request_1.state, "draft") self.assertEqual(len(stock_request_1.picking_ids), 0) self.assertEqual(stock_request_2.state, "draft") self.assertEqual(len(stock_request_2.picking_ids), 0) # Confirm stock requests stock_request_1.with_user(self.stock_request_manager).action_confirm() stock_request_2.with_user(self.stock_request_manager).action_confirm() self.assertEqual(stock_request_1.state, "open") self.assertEqual(len(stock_request_1.picking_ids), 1) self.assertEqual(stock_request_2.state, "open") self.assertEqual(len(stock_request_2.picking_ids), 1) self.assertNotEqual(stock_request_1.picking_ids, stock_request_2.picking_ids) def test_create_stock_request_order(self): vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": self.expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": self.expected_date, }, ) ], } self.product.route_ids = [(6, 0, self.route.ids)] # Create stock request order stock_request_order_1 = self.request_order.with_user( self.stock_request_user ).create(vals) stock_request_order_2 = self.request_order.with_user( self.stock_request_user ).create(vals) self.assertEqual(stock_request_order_1.state, "draft") self.assertEqual(len(stock_request_order_1.picking_ids), 0) self.assertEqual(stock_request_order_2.state, "draft") self.assertEqual(len(stock_request_order_2.picking_ids), 0) # Confirm stock requests stock_request_order_1.with_user(self.stock_request_manager).action_confirm() stock_request_order_2.with_user(self.stock_request_manager).action_confirm() self.assertEqual(stock_request_order_1.state, "open") self.assertEqual(len(stock_request_order_1.picking_ids), 1) self.assertEqual(stock_request_order_2.state, "open") self.assertEqual(len(stock_request_order_2.picking_ids), 1) self.assertNotEqual( stock_request_order_1.picking_ids, stock_request_order_2.picking_ids )
44.876404
3,994
790
py
PYTHON
15.0
# Copyright 2023 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" procurement_group_id = fields.Many2one( copy=False, ) @api.model def create(self, vals): res = super().create(vals) if ( self.env.company.stock_request_allow_separate_picking and not res.procurement_group_id ): res.procurement_group_id = self.env["procurement.group"].create( {"name": res.name} ) for line in res.stock_request_ids: line.procurement_group_id = res.procurement_group_id return res
30.384615
790
349
py
PYTHON
15.0
# Copyright 2023 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" stock_request_allow_separate_picking = fields.Boolean( string="Allow Separate Picking on Stock Requests" )
26.846154
349
405
py
PYTHON
15.0
# Copyright 2023 Ecosoft Co., Ltd (http://ecosoft.co.th/) # 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" stock_request_allow_separate_picking = fields.Boolean( related="company_id.stock_request_allow_separate_picking", readonly=False, )
31.153846
405
824
py
PYTHON
15.0
# Copyright 2023 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class StockRequestAbstract(models.AbstractModel): _inherit = "stock.request.abstract" procurement_group_id = fields.Many2one( copy=False, ) @api.model def create(self, vals): res = super().create(vals) if ( self.env.company.stock_request_allow_separate_picking and not res.procurement_group_id ): if res.order_id: res.procurement_group_id = res.order_id.procurement_group_id else: res.procurement_group_id = self.env["procurement.group"].create( {"name": res.name} ) return res
30.518519
824
544
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Stock MTS+MTO Rule", "summary": "Add a MTS+MTO route", "version": "15.0.1.0.1", "development_status": "Mature", "category": "Warehouse", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "Akretion,Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["stock"], "data": ["data/stock_data.xml", "view/pull_rule.xml", "view/warehouse.xml"], }
34
544
9,792
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import exceptions from odoo.tests.common import TransactionCase class TestMtoMtsRoute(TransactionCase): def _create_quant(self, qty): self.quant = self.env["stock.quant"].create( { "owner_id": self.company_partner.id, "location_id": self.env.ref("stock.stock_location_stock").id, "product_id": self.product.id, "quantity": qty, } ) def test_standard_mto_route(self): mto_route = self.env.ref("stock.route_warehouse0_mto") mto_route.active = True self.product.route_ids = [(6, 0, [mto_route.id])] self.env["procurement.group"].run( [ self.group.Procurement( self.product, 2.0, self.uom, self.customer_loc, self.product.name, "test", self.warehouse.company_id, self.procurement_vals, ) ] ) moves = self.move_obj.search([("group_id", "=", self.group.id)]) self.assertEqual(len(moves), 2) def test_standard_mts_route(self): self.env["procurement.group"].run( [ self.group.Procurement( self.product, 2.0, self.uom, self.customer_loc, self.product.name, "test", self.warehouse.company_id, self.procurement_vals, ) ] ) moves = self.move_obj.search([("group_id", "=", self.group.id)]) self.assertEqual(len(moves), 1) def test_mts_mto_route_split(self): mto_mts_route = self.env.ref("stock_mts_mto_rule.route_mto_mts") self.product.route_ids = [(6, 0, [mto_mts_route.id])] self._create_quant(1.0) self.env["procurement.group"].run( [ self.group.Procurement( self.product, 2.0, self.uom, self.customer_loc, self.product.name, "test", self.warehouse.company_id, self.procurement_vals, ) ] ) moves = self.env["stock.move"].search([("group_id", "=", self.group.id)]) self.assertEqual(3, len(moves)) move_mts = self.env["stock.move"].search( [ ("group_id", "=", self.group.id), ("location_dest_id", "=", self.customer_loc.id), ("procure_method", "=", "make_to_stock"), ] ) self.assertEqual(1, len(move_mts)) self.assertEqual(1.0, move_mts.product_uom_qty) self.assertEqual("assigned", move_mts.state) move_mto = self.env["stock.move"].search( [ ("group_id", "=", self.group.id), ("location_dest_id", "=", self.customer_loc.id), ("procure_method", "=", "make_to_order"), ] ) self.assertEqual(1, len(move_mto)) self.assertEqual("waiting", move_mto.state) def test_mts_mto_route_mto_only(self): mto_mts_route = self.env.ref("stock_mts_mto_rule.route_mto_mts") self.product.route_ids = [(6, 0, [mto_mts_route.id])] self.env["procurement.group"].run( [ self.group.Procurement( self.product, 2.0, self.uom, self.customer_loc, self.product.name, "test", self.warehouse.company_id, self.procurement_vals, ) ] ) moves = self.env["stock.move"].search( [ ("group_id", "=", self.group.id), ("location_dest_id", "=", self.customer_loc.id), ] ) self.assertEqual(1, len(moves)) self.assertEqual(2.0, moves[0].product_uom_qty) self.assertEqual("make_to_order", moves[0].procure_method) def test_mts_mto_route_mts_only(self): mto_mts_route = self.env.ref("stock_mts_mto_rule.route_mto_mts") self.product.route_ids = [(6, 0, [mto_mts_route.id])] self._create_quant(3.0) self.env["procurement.group"].run( [ self.group.Procurement( self.product, 2.0, self.uom, self.customer_loc, self.product.name, "test", self.warehouse.company_id, self.procurement_vals, ) ] ) moves = self.env["stock.move"].search([("group_id", "=", self.group.id)]) self.assertEqual(1, len(moves)) self.assertEqual(2.0, moves[0].product_uom_qty) self.assertEqual("make_to_stock", moves[0].procure_method) def test_mts_mto_rule_contrains(self): rule = self.env["stock.rule"].search( [("action", "=", "split_procurement")], limit=1 ) with self.assertRaises(exceptions.ValidationError): rule.write({"mts_rule_id": False}) with self.assertRaises(exceptions.ValidationError): rule.write({"mts_rule_id": self.dummy_rule.id}) def test_mts_mto_route_mto_removed(self): self.env.ref("stock_mts_mto_rule.route_mto_mts").unlink() with self.assertRaises(exceptions.UserError): # mts_mto_rule_id is checked as a global rule self.warehouse.mts_mto_rule_id = False def test_mts_mto_route_mts_removed(self): self.warehouse.mto_mts_management = True rules = self.env["stock.rule"].search( [ ("location_src_id", "=", self.warehouse.lot_stock_id.id), ("route_id", "=", self.warehouse.delivery_route_id.id), ] ) self.env.cr.execute( "UPDATE stock_move SET rule_id = NULL WHERE rule_id IN %s", (tuple(rules.ids),), ) self.warehouse.mts_mto_rule_id = False self.warehouse.mto_mts_management = True self.assertTrue(self.warehouse.mts_mto_rule_id) def test_mts_mto_route_mto_no_mts_rule(self): self.warehouse.mts_mto_rule_id = False self.warehouse.mto_pull_id = False self.warehouse.mto_mts_management = True self.assertTrue(self.warehouse.mts_mto_rule_id) def test_create_routes(self): self.warehouse._create_or_update_route() mts_mto_route = self.warehouse.mts_mto_rule_id self.assertEqual(mts_mto_route.warehouse_id, self.warehouse) self.assertEqual( mts_mto_route.location_id, self.warehouse.mto_pull_id.location_id ) self.assertEqual( mts_mto_route.picking_type_id, self.warehouse.mto_pull_id.picking_type_id ) self.assertEqual( mts_mto_route.route_id, self.env.ref("stock_mts_mto_rule.route_mto_mts") ) def test_remove_mts_mto_management(self): warehouse_rule = self.warehouse.mts_mto_rule_id self.assertTrue(self.warehouse.mts_mto_rule_id) self.warehouse.mto_mts_management = False self.assertFalse(warehouse_rule.active) def test_get_all_routes_for_wh(self): routes = self.warehouse._get_all_routes() self.assertTrue(self.warehouse.mts_mto_rule_id) self.assertTrue(self.warehouse.mts_mto_rule_id.route_id in routes) def test_rename_warehouse(self): rule_name = self.warehouse.mts_mto_rule_id.name new_warehouse_name = "NewName" new_rule_name = rule_name.replace(self.warehouse.name, new_warehouse_name, 1) self.warehouse.name = new_warehouse_name self.assertEqual(new_rule_name, self.warehouse.mts_mto_rule_id.name) def setUp(self): super(TestMtoMtsRoute, self).setUp() self.move_obj = self.env["stock.move"] self.warehouse = self.env.ref("stock.warehouse0") self.uom = self.env["uom.uom"].browse(1) self.warehouse.mto_mts_management = True self.customer_loc = self.env.ref("stock.stock_location_customers") self.product = self.env["product.product"].create( {"name": "Test product", "type": "product"} ) self.company_partner = self.env.ref("base.main_partner") self.group = self.env["procurement.group"].create({"name": "test"}) self.procurement_vals = {"warehouse_id": self.warehouse, "group_id": self.group} # Since mrp and purchase modules may not be installed, we need to # create a dummy step to show that mts, mto, and mts+mto flows work. # Else, if purchase/manufacture are not installed, the mto would fail. route_vals = { "warehouse_selectable": True, "name": "dummy route", } self.dummy_route = self.env["stock.location.route"].create(route_vals) rule_vals = { "location_id": self.env.ref("stock.stock_location_stock").id, "location_src_id": self.env.ref("stock.stock_location_suppliers").id, "action": "pull", "warehouse_id": self.warehouse.id, "picking_type_id": self.env.ref("stock.picking_type_out").id, "name": "dummy rule", "route_id": self.dummy_route.id, } self.dummy_rule = self.env["stock.rule"].create(rule_vals) self.warehouse.write({"route_ids": [(4, self.dummy_route.id)]})
39.643725
9,792
4,178
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, fields, models class StockWarehouse(models.Model): _inherit = "stock.warehouse" mto_mts_management = fields.Boolean( "Use MTO+MTS rules", help="If this new route is selected on product form view, a " "purchase order will be created only if the virtual stock is " "less than 0 else, the product will be taken from stocks", ) mts_mto_rule_id = fields.Many2one("stock.rule", "MTO+MTS rule", check_company=True) def _get_all_routes(self): routes = super(StockWarehouse, self)._get_all_routes() routes |= self.mapped("mts_mto_rule_id.route_id") return routes def _update_name_and_code(self, new_name=False, new_code=False): res = super(StockWarehouse, self)._update_name_and_code(new_name, new_code) if not new_name: return res for warehouse in self.filtered("mts_mto_rule_id"): warehouse.mts_mto_rule_id.write( { "name": warehouse.mts_mto_rule_id.name.replace( warehouse.name, new_name, 1 ), } ) return res def _get_route_name(self, route_type): if route_type == "mts_mto": return _("MTS+MTO") return super(StockWarehouse, self)._get_route_name(route_type) def _get_global_route_rules_values(self): rule = self.get_rules_dict()[self.id][self.delivery_steps] rule = [r for r in rule if r.from_loc == self.lot_stock_id][0] location_id = rule.from_loc location_dest_id = rule.dest_loc picking_type_id = rule.picking_type res = super(StockWarehouse, self)._get_global_route_rules_values() res.update( { "mts_mto_rule_id": { "depends": ["delivery_steps", "mto_mts_management"], "create_values": { "action": "pull", "procure_method": "make_to_order", "company_id": self.company_id.id, "auto": "manual", "propagate_cancel": True, "route_id": self._find_global_route( "stock_mts_mto_rule.route_mto_mts", _("Make To Order + Make To Stock"), ).id, }, "update_values": { "active": self.mto_mts_management, "name": self._format_rulename( location_id, location_dest_id, "MTS+MTO" ), "location_id": location_dest_id.id, "location_src_id": location_id.id, "picking_type_id": picking_type_id.id, }, }, } ) return res def _create_or_update_global_routes_rules(self): res = super(StockWarehouse, self)._create_or_update_global_routes_rules() if ( self.mto_mts_management and self.mts_mto_rule_id and self.mts_mto_rule_id.action != "split_procurement" ): # Cannot create or update with the 'split_procurement' action due # to constraint and the fact that the constrained rule_ids may # not exist during the initial (or really any) calls of # _get_global_route_rules_values rule = self.env["stock.rule"].search( [ ("location_id", "=", self.mts_mto_rule_id.location_id.id), ("location_src_id", "=", self.mts_mto_rule_id.location_src_id.id), ("route_id", "=", self.delivery_route_id.id), ], limit=1, ) self.mts_mto_rule_id.write( { "action": "split_procurement", "mts_rule_id": rule.id, "mto_rule_id": self.mto_pull_id.id, } ) return res
40.173077
4,178
4,650
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.osv import expression from odoo.tools import float_compare, float_is_zero class StockRule(models.Model): _inherit = "stock.rule" action = fields.Selection( selection_add=[("split_procurement", "Choose between MTS and MTO")], ondelete={"split_procurement": "cascade"}, ) mts_rule_id = fields.Many2one("stock.rule", string="MTS Rule", check_company=True) mto_rule_id = fields.Many2one("stock.rule", string="MTO Rule", check_company=True) @api.constrains("action", "mts_rule_id", "mto_rule_id") def _check_mts_mto_rule(self): for rule in self: if rule.action == "split_procurement": if not rule.mts_rule_id or not rule.mto_rule_id: msg = _( "No MTS or MTO rule configured on procurement " "rule: %s!" ) % (rule.name,) raise ValidationError(msg) if ( rule.mts_rule_id.location_src_id.id != rule.mto_rule_id.location_src_id.id ): msg = _( "Inconsistency between the source locations of " "the mts and mto rules linked to the procurement " "rule: %s! It should be the same." ) % (rule.name,) raise ValidationError(msg) def get_mto_qty_to_order(self, product, product_qty, product_uom, values): self.ensure_one() precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) src_location_id = self.mts_rule_id.location_src_id.id product_location = product.with_context(location=src_location_id) virtual_available = product_location.virtual_available qty_available = product.uom_id._compute_quantity(virtual_available, product_uom) if float_compare(qty_available, 0.0, precision_digits=precision) > 0: if ( float_compare(qty_available, product_qty, precision_digits=precision) >= 0 ): return 0.0 else: return product_qty - qty_available return product_qty def _run_split_procurement(self, procurements): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) for procurement, rule in procurements: domain = self.env["procurement.group"]._get_moves_to_assign_domain( procurement.company_id.id ) needed_qty = rule.get_mto_qty_to_order( procurement.product_id, procurement.product_qty, procurement.product_uom, procurement.values, ) if float_is_zero(needed_qty, precision_digits=precision): getattr(self.env["stock.rule"], "_run_%s" % rule.mts_rule_id.action)( [(procurement, rule.mts_rule_id)] ) elif ( float_compare( needed_qty, procurement.product_qty, precision_digits=precision ) == 0.0 ): getattr(self.env["stock.rule"], "_run_%s" % rule.mto_rule_id.action)( [(procurement, rule.mto_rule_id)] ) else: mts_qty = procurement.product_qty - needed_qty mts_procurement = procurement._replace(product_qty=mts_qty) getattr(self.env["stock.rule"], "_run_%s" % rule.mts_rule_id.action)( [(mts_procurement, rule.mts_rule_id)] ) # Search all confirmed stock_moves of mts_procuremet and assign them # to adjust the product's free qty group_id = mts_procurement.values.get("group_id") group_domain = expression.AND( [domain, [("group_id", "=", group_id.id)]] ) moves_to_assign = self.env["stock.move"].search( group_domain, order="priority desc, date asc" ) moves_to_assign._action_assign() mto_procurement = procurement._replace(product_qty=needed_qty) getattr(self.env["stock.rule"], "_run_%s" % rule.mto_rule_id.action)( [(mto_procurement, rule.mto_rule_id)] ) return True
43.457944
4,650
665
py
PYTHON
15.0
{ "name": "Stock Inventory Adjustment", "version": "15.0.1.0.1", "license": "LGPL-3", "maintainer": ["DavidJForgeFlow"], "development_status": "Beta", "category": "Inventory/Inventory", "summary": "Allows to do an easier follow up of the Inventory Adjustments", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "depends": ["stock"], "data": [ "security/ir.model.access.csv", "views/stock_inventory.xml", "views/stock_quant.xml", "views/stock_move_line.xml", ], "installable": True, "application": False, }
33.25
665
13,765
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestStockInventory(TransactionCase): def setUp(self): super(TestStockInventory, self).setUp() self.quant_model = self.env["stock.quant"] self.move_model = self.env["stock.move.line"] self.inventory_model = self.env["stock.inventory"] self.location_model = self.env["stock.location"] self.product_categ = self.env["product.category"].create({"name": "Test Categ"}) self.product = self.env["product.product"].create( { "name": "Product 1 test", "type": "product", "tracking": "lot", } ) self.product2 = self.env["product.product"].create( { "name": "Product 1 test", "type": "product", "categ_id": self.product_categ.id, } ) self.lot_1 = self.env["stock.production.lot"].create( { "product_id": self.product.id, "name": "Lot 1", "company_id": self.env.company.id, } ) self.lot_2 = self.env["stock.production.lot"].create( { "product_id": self.product.id, "name": "Lot 2", "company_id": self.env.company.id, } ) self.lot_3 = self.env["stock.production.lot"].create( { "product_id": self.product.id, "name": "Lot 3", "company_id": self.env.company.id, } ) self.location_src = self.env.ref("stock.stock_location_locations_virtual") self.location_dst = self.env.ref("stock.stock_location_customers") self.location1 = self.location_model.create( { "name": "Location 1", "usage": "internal", "warehouse_id": self.location_src.id, } ) self.location2 = self.location_model.create( { "name": "Location 2", "usage": "internal", "location_id": self.location_src.id, } ) self.location3 = self.location_model.create( { "name": "Location 3", "usage": "internal", "location_id": self.location1.id, } ) self.quant1 = self.quant_model.sudo().create( { "product_id": self.product.id, "lot_id": self.lot_1.id, "quantity": 100.0, "location_id": self.location1.id, } ) self.quant2 = self.quant_model.sudo().create( { "product_id": self.product.id, "lot_id": self.lot_2.id, "quantity": 100.0, "location_id": self.location2.id, } ) self.quant3 = self.quant_model.sudo().create( { "product_id": self.product.id, "lot_id": self.lot_3.id, "quantity": 100.0, "location_id": self.location3.id, } ) self.quant4 = self.quant_model.sudo().create( { "product_id": self.product2.id, "quantity": 100.0, "location_id": self.location3.id, } ) def test_01_all_locations(self): inventory1 = self.inventory_model.create( { "name": "Inventory_Test_1", "product_selection": "all", "location_ids": [self.location1.id], } ) inventory1.action_state_to_in_progress() inventory2 = self.inventory_model.create( { "name": "Inventory_Test_2", "product_selection": "all", "location_ids": [self.location1.id], } ) with self.assertRaises(ValidationError), self.cr.savepoint(): inventory2.action_state_to_in_progress() self.assertEqual(inventory1.state, "in_progress") self.assertEqual( inventory1.stock_quant_ids.ids, [self.quant1.id, self.quant3.id, self.quant4.id], ) inventory1.action_state_to_draft() self.assertEqual(inventory1.stock_quant_ids.ids, []) inventory1.action_state_to_in_progress() self.assertEqual(inventory1.count_stock_moves, 0) self.assertEqual(inventory1.count_stock_quants, 3) self.assertEqual(inventory1.count_stock_quants_string, "3 / 3") inventory1.action_view_inventory_adjustment() self.quant1.inventory_quantity = 92 self.quant1.action_apply_inventory() inventory1._compute_count_stock_quants() inventory1.action_view_stock_moves() self.assertEqual(inventory1.count_stock_moves, 1) self.assertEqual(inventory1.count_stock_quants, 3) self.assertEqual(inventory1.count_stock_quants_string, "2 / 3") self.assertEqual(inventory1.stock_move_ids.qty_done, 8) self.assertEqual(inventory1.stock_move_ids.product_id.id, self.product.id) self.assertEqual(inventory1.stock_move_ids.lot_id.id, self.lot_1.id) self.assertEqual(inventory1.stock_move_ids.location_id.id, self.location1.id) inventory1.action_state_to_done() def test_02_manual_selection(self): inventory1 = self.inventory_model.create( { "name": "Inventory_Test_3", "product_selection": "manual", "location_ids": [self.location1.id], "product_ids": [self.product.id], } ) inventory1.action_state_to_in_progress() self.assertEqual(inventory1.state, "in_progress") self.assertEqual( inventory1.stock_quant_ids.ids, [self.quant1.id, self.quant3.id] ) inventory1.action_state_to_draft() self.assertEqual(inventory1.stock_quant_ids.ids, []) inventory1.action_state_to_in_progress() self.assertEqual(inventory1.state, "in_progress") self.assertEqual(inventory1.count_stock_moves, 0) self.assertEqual(inventory1.count_stock_quants, 2) self.assertEqual(inventory1.count_stock_quants_string, "2 / 2") inventory1.action_view_inventory_adjustment() self.quant3.inventory_quantity = 74 self.quant3.action_apply_inventory() inventory1._compute_count_stock_quants() inventory1.action_view_stock_moves() self.assertEqual(inventory1.count_stock_moves, 1) self.assertEqual(inventory1.count_stock_quants, 2) self.assertEqual(inventory1.count_stock_quants_string, "1 / 2") self.assertEqual(inventory1.stock_move_ids.qty_done, 26) self.assertEqual(inventory1.stock_move_ids.product_id.id, self.product.id) self.assertEqual(inventory1.stock_move_ids.lot_id.id, self.lot_3.id) self.assertEqual(inventory1.stock_move_ids.location_id.id, self.location3.id) self.quant1.inventory_quantity = 65 self.quant1.action_apply_inventory() inventory1._compute_count_stock_quants() self.assertEqual(inventory1.count_stock_moves, 2) self.assertEqual(inventory1.count_stock_quants, 2) self.assertEqual(inventory1.count_stock_quants_string, "0 / 2") inventory1.action_state_to_done() def test_03_one_selection(self): with self.assertRaises(ValidationError), self.cr.savepoint(): inventory1 = self.inventory_model.create( { "name": "Inventory_Test_5", "product_selection": "one", "location_ids": [self.location1.id], "product_ids": [self.product.id, self.product2.id], } ) inventory1 = self.inventory_model.create( { "name": "Inventory_Test_5", "product_selection": "one", "location_ids": [self.location1.id], "product_ids": [self.product.id], } ) inventory1.action_state_to_in_progress() inventory1.product_ids = [self.product.id] self.assertEqual( inventory1.stock_quant_ids.ids, [self.quant1.id, self.quant3.id] ) inventory1.action_state_to_draft() self.assertEqual(inventory1.stock_quant_ids.ids, []) inventory1.action_state_to_in_progress() self.assertEqual(inventory1.state, "in_progress") self.assertEqual(inventory1.count_stock_moves, 0) self.assertEqual(inventory1.count_stock_quants, 2) self.assertEqual(inventory1.count_stock_quants_string, "2 / 2") inventory1.action_view_inventory_adjustment() self.quant3.inventory_quantity = 74 self.quant3.action_apply_inventory() inventory1._compute_count_stock_quants() inventory1.action_view_stock_moves() self.assertEqual(inventory1.count_stock_moves, 1) self.assertEqual(inventory1.count_stock_quants, 2) self.assertEqual(inventory1.count_stock_quants_string, "1 / 2") self.assertEqual(inventory1.stock_move_ids.qty_done, 26) self.assertEqual(inventory1.stock_move_ids.product_id.id, self.product.id) self.assertEqual(inventory1.stock_move_ids.lot_id.id, self.lot_3.id) self.assertEqual(inventory1.stock_move_ids.location_id.id, self.location3.id) self.quant1.inventory_quantity = 65 self.quant1.action_apply_inventory() inventory1._compute_count_stock_quants() self.assertEqual(inventory1.count_stock_moves, 2) self.assertEqual(inventory1.count_stock_quants, 2) self.assertEqual(inventory1.count_stock_quants_string, "0 / 2") inventory1.action_state_to_done() def test_04_lot_selection(self): with self.assertRaises(ValidationError), self.cr.savepoint(): inventory1 = self.inventory_model.create( { "name": "Inventory_Test_6", "product_selection": "lot", "location_ids": [self.location1.id], "lot_ids": [self.lot_3.id], "product_ids": [self.product.id, self.product2.id], } ) inventory1 = self.inventory_model.create( { "name": "Inventory_Test_6", "product_selection": "lot", "location_ids": [self.location1.id], "lot_ids": [self.lot_3.id], "product_ids": [self.product.id], } ) inventory1.product_ids = [self.product.id] inventory1.action_state_to_in_progress() self.assertEqual(inventory1.stock_quant_ids.ids, [self.quant3.id]) inventory1.action_state_to_draft() self.assertEqual(inventory1.stock_quant_ids.ids, []) inventory1.action_state_to_in_progress() self.assertEqual(inventory1.state, "in_progress") self.assertEqual(inventory1.count_stock_moves, 0) self.assertEqual(inventory1.count_stock_quants, 1) self.assertEqual(inventory1.count_stock_quants_string, "1 / 1") inventory1.action_view_inventory_adjustment() self.quant3.inventory_quantity = 74 self.quant3.action_apply_inventory() inventory1._compute_count_stock_quants() inventory1.action_view_stock_moves() self.assertEqual(inventory1.count_stock_moves, 1) self.assertEqual(inventory1.count_stock_quants, 1) self.assertEqual(inventory1.count_stock_quants_string, "0 / 1") self.assertEqual(inventory1.stock_move_ids.qty_done, 26) self.assertEqual(inventory1.stock_move_ids.product_id.id, self.product.id) self.assertEqual(inventory1.stock_move_ids.lot_id.id, self.lot_3.id) self.assertEqual(inventory1.stock_move_ids.location_id.id, self.location3.id) inventory1.action_state_to_done() def test_05_category_selection(self): inventory1 = self.inventory_model.create( { "name": "Inventory_Test_7", "product_selection": "category", "location_ids": [self.location3.id], "category_id": self.product_categ.id, } ) inventory1.action_state_to_in_progress() self.assertEqual(inventory1.stock_quant_ids.ids, [self.quant4.id]) inventory1.action_state_to_draft() self.assertEqual(inventory1.stock_quant_ids.ids, []) inventory1.action_state_to_in_progress() self.assertEqual(inventory1.state, "in_progress") self.assertEqual(inventory1.count_stock_moves, 0) self.assertEqual(inventory1.count_stock_quants, 1) self.assertEqual(inventory1.count_stock_quants_string, "1 / 1") inventory1.action_view_inventory_adjustment() self.quant4.inventory_quantity = 74 self.quant4.action_apply_inventory() inventory1._compute_count_stock_quants() inventory1.action_view_stock_moves() self.assertEqual(inventory1.count_stock_moves, 1) self.assertEqual(inventory1.count_stock_quants, 1) self.assertEqual(inventory1.count_stock_quants_string, "0 / 1") self.assertEqual(inventory1.stock_move_ids.qty_done, 26) self.assertEqual(inventory1.stock_move_ids.product_id.id, self.product2.id) self.assertEqual(inventory1.stock_move_ids.location_id.id, self.location3.id) inventory1.action_state_to_done()
43.83758
13,765
189
py
PYTHON
15.0
from odoo import fields, models class StockMoveLine(models.Model): _inherit = "stock.move.line" inventory_adjustment_id = fields.Many2one("stock.inventory", ondelete="restrict")
27
189
1,254
py
PYTHON
15.0
from odoo import fields, models class StockQuant(models.Model): _inherit = "stock.quant" to_do = fields.Boolean(default=True) def _apply_inventory(self): res = super()._apply_inventory() record_moves = self.env["stock.move.line"] for rec in self: adjustment = ( self.env["stock.inventory"] .search([("state", "=", "in_progress")]) .filtered( lambda x: rec.location_id in x.location_ids or rec.location_id in x.location_ids.child_ids ) ) moves = record_moves.search( [ ("product_id", "=", rec.product_id.id), ("lot_id", "=", rec.lot_id.id), ("company_id", "=", rec.company_id.id), "|", ("location_id", "=", rec.location_id.id), ("location_dest_id", "=", rec.location_id.id), ], order="create_date asc", ) move = moves[len(moves) - 1] adjustment.stock_move_ids |= move move.inventory_adjustment_id = adjustment rec.to_do = False return res
34.833333
1,254
7,693
py
PYTHON
15.0
from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.osv import expression class InventoryAdjustmentsGroup(models.Model): _name = "stock.inventory" _description = "Inventory Adjustment Group" _order = "date desc, id desc" name = fields.Char(required=True, default="Inventory", string="Inventory Reference") date = fields.Datetime(default=lambda self: fields.Datetime.now()) state = fields.Selection( [("draft", "Draft"), ("in_progress", "In Progress"), ("done", "Done")], default="draft", ) owner_id = fields.Many2one( "res.partner", "Owner", help="This is the owner of the inventory adjustment" ) location_ids = fields.Many2many( "stock.location", string="Locations", domain="[('usage', '=', 'internal')]" ) product_selection = fields.Selection( [ ("all", "All Products"), ("manual", "Manual Selection"), ("category", "Product Category"), ("one", "One Product"), ("lot", "Lot/Serial Number"), ], default="all", required=True, ) product_ids = fields.Many2many("product.product", string="Products") stock_quant_ids = fields.Many2many("stock.quant", string="Inventory Adjustment") category_id = fields.Many2one("product.category", string="Product Category") lot_ids = fields.Many2many( "stock.production.lot", string="Lot/Serial Numbers", ) stock_move_ids = fields.One2many( "stock.move.line", "inventory_adjustment_id", string="Inventory Adjustments Done", ) count_stock_quants = fields.Integer( compute="_compute_count_stock_quants", string="Adjustments" ) count_stock_quants_string = fields.Char( compute="_compute_count_stock_quants", string="Adjustments" ) count_stock_moves = fields.Integer( compute="_compute_count_stock_moves", string="Stock Moves Lines" ) @api.depends("stock_quant_ids") def _compute_count_stock_quants(self): self.count_stock_quants = len(self.stock_quant_ids) count_todo = len( self.stock_quant_ids.search( [("id", "in", self.stock_quant_ids.ids), ("to_do", "=", "True")] ) ) self.count_stock_quants_string = "{} / {}".format( count_todo, self.count_stock_quants ) @api.depends("stock_move_ids") def _compute_count_stock_moves(self): sm_ids = self.mapped("stock_move_ids").ids self.count_stock_moves = len(sm_ids) def _get_quants(self, locations): domain = [] base_domain = self._get_base_domain(locations) if self.product_selection == "all": domain = self._get_domain_all_quants(base_domain) elif self.product_selection == "manual": domain = self._get_domain_manual_quants(base_domain) elif self.product_selection == "one": domain = self._get_domain_one_quant(base_domain) elif self.product_selection == "lot": domain = self._get_domain_lot_quants(base_domain) elif self.product_selection == "category": domain = self._get_domain_category_quants(base_domain) return self.env["stock.quant"].search(domain) def _get_base_domain(self, locations): return [ "|", ("location_id", "in", locations.mapped("id")), ("location_id", "in", locations.child_ids.ids), ] def _get_domain_all_quants(self, base_domain): return base_domain def _get_domain_manual_quants(self, base_domain): return expression.AND( [base_domain, [("product_id", "in", self.product_ids.ids)]] ) def _get_domain_one_quant(self, base_domain): return expression.AND( [ base_domain, [ ("product_id", "in", self.product_ids.ids), ], ] ) def _get_domain_lot_quants(self, base_domain): return expression.AND( [ base_domain, [ ("product_id", "in", self.product_ids.ids), ("lot_id", "in", self.lot_ids.ids), ], ] ) def _get_domain_category_quants(self, base_domain): return expression.AND( [ base_domain, [ "|", ("product_id.categ_id", "=", self.category_id.id), ("product_id.categ_id", "in", self.category_id.child_id.ids), ], ] ) def action_state_to_in_progress(self): active_rec = self.env["stock.inventory"].search( [ ("state", "=", "in_progress"), "|", ("location_ids", "in", self.location_ids.mapped("id")), ("location_ids", "in", self.location_ids.child_ids.ids), ], limit=1, ) if active_rec: raise ValidationError( _( "There's already an Adjustment in Process using one requested Location: %s" ) % active_rec.name ) self.state = "in_progress" self.stock_quant_ids = self._get_quants(self.location_ids) self.stock_quant_ids.update({"to_do": True}) return def action_state_to_done(self): self.state = "done" self.stock_quant_ids.update({"to_do": True}) return def action_state_to_draft(self): self.state = "draft" self.stock_quant_ids.update({"to_do": True}) self.stock_quant_ids = None return def action_view_inventory_adjustment(self): result = self.env["stock.quant"].action_view_inventory() ia_ids = self.mapped("stock_quant_ids").ids result["domain"] = [("id", "in", ia_ids)] result["search_view_id"] = self.env.ref("stock.quant_search_view").id result["context"]["search_default_to_do"] = 1 return result def action_view_stock_moves(self): result = self.env["ir.actions.act_window"]._for_xml_id( "stock_inventory.action_view_stock_move_line_inventory_tree" ) sm_ids = self.mapped("stock_move_ids").ids result["domain"] = [("id", "in", sm_ids)] result["context"] = [] return result @api.constrains("product_selection", "product_ids") def _check_one_product_in_product_selection(self): for rec in self: if len(rec.product_ids) > 1: if rec.product_selection == "one": raise ValidationError( _( "When 'Product Selection: One Product' is selected" " you are only able to add one product." ) ) elif rec.product_selection == "lot": raise ValidationError( _( "When 'Product Selection: Lot Serial Number' is selected" " you are only able to add one product." ) ) def unlink(self): for adjustment in self: if adjustment.state != "draft": raise UserError( _( "You can only delete inventory adjustments groups in" " draft state." ) ) return super().unlink()
33.889868
7,693
951
py
PYTHON
15.0
# Copyright 2017-2021 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "Stock Request", "summary": "Internal request for stock", "version": "15.0.1.6.2", "license": "LGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "ForgeFlow, Odoo Community Association (OCA)", "category": "Warehouse Management", "depends": ["stock"], "data": [ "security/stock_request_security.xml", "security/ir.model.access.csv", "views/product.xml", "views/stock_request_views.xml", "views/stock_request_allocation_views.xml", "views/stock_move_views.xml", "views/stock_picking_views.xml", "views/stock_request_order_views.xml", "views/res_config_settings_views.xml", "views/stock_request_menu.xml", "data/stock_request_sequence_data.xml", ], "installable": True, }
35.222222
951
315
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): openupgrade.load_data( env.cr, "stock_request", "migrations/15.0.1.4.0/noupdate_changes.xml" )
31.5
315
45,492
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # Copyright 2022 Tecnativa - Víctor Martínez # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from collections import Counter from datetime import datetime from odoo import exceptions, fields from odoo.tests import common, new_test_user class TestStockRequest(common.TransactionCase): def setUp(self): super().setUp() # common models self.stock_request = self.env["stock.request"] self.request_order = self.env["stock.request.order"] # refs self.stock_request_user_group = self.env.ref( "stock_request.group_stock_request_user" ) self.main_company = self.env.ref("base.main_company") self.warehouse = self.env.ref("stock.warehouse0") self.categ_unit = self.env.ref("uom.product_uom_categ_unit") self.virtual_loc = self.env.ref("stock.stock_location_customers") # common data self.company_2 = self.env["res.company"].create( {"name": "Comp2", "parent_id": self.main_company.id} ) self.company_2_address = ( self.env["res.partner"] .with_context(company_id=self.company_2.id) .create({"name": "Peñiscola"}) ) self.wh2 = self.env["stock.warehouse"].search( [("company_id", "=", self.company_2.id)], limit=1 ) ctx = { "mail_create_nolog": True, "mail_create_nosubscribe": True, "mail_notrack": True, "no_reset_password": True, } self.stock_request_user = new_test_user( self.env, login="stock_request_user", groups="stock_request.group_stock_request_user", company_ids=[(6, 0, [self.main_company.id, self.company_2.id])], context=ctx, ) self.stock_request_manager = new_test_user( self.env, login="stock_request_manager", groups="stock_request.group_stock_request_manager", company_ids=[(6, 0, [self.main_company.id, self.company_2.id])], context=ctx, ) self.product = self._create_product("SH", "Shoes", False) self.product_company_2 = self._create_product( "SH_2", "Shoes", self.company_2.id ) self.ressuply_loc = self._create_location( name="Ressuply", location_id=self.warehouse.view_location_id.id, company_id=self.main_company.id, ) self.ressuply_loc_2 = self._create_location( name="Ressuply", location_id=self.wh2.view_location_id.id, company_id=self.company_2.id, ) self.route = self._create_location_route( name="Transfer", company_id=self.main_company.id ) self.route_2 = self._create_location_route( name="Transfer", company_id=self.company_2.id ) self.uom_dozen = self.env["uom.uom"].create( { "name": "Test-DozenA", "category_id": self.categ_unit.id, "factor_inv": 12, "uom_type": "bigger", "rounding": 0.001, } ) self.env["stock.rule"].create( { "name": "Transfer", "route_id": self.route.id, "location_src_id": self.ressuply_loc.id, "location_id": self.warehouse.lot_stock_id.id, "action": "pull", "picking_type_id": self.warehouse.int_type_id.id, "procure_method": "make_to_stock", "warehouse_id": self.warehouse.id, "company_id": self.main_company.id, } ) self.env["stock.rule"].create( { "name": "Transfer", "route_id": self.route_2.id, "location_src_id": self.ressuply_loc_2.id, "location_id": self.wh2.lot_stock_id.id, "action": "pull", "picking_type_id": self.wh2.int_type_id.id, "procure_method": "make_to_stock", "warehouse_id": self.wh2.id, "company_id": self.company_2.id, } ) self.env["ir.config_parameter"].sudo().set_param( "stock.no_auto_scheduler", "True" ) def _create_product(self, default_code, name, company_id, **vals): return self.env["product.product"].create( dict( name=name, default_code=default_code, uom_id=self.env.ref("uom.product_uom_unit").id, company_id=company_id, type="product", **vals ) ) def _create_product_template_attribute_line( self, product_tmpl_id, attribute_id, value_id ): return self.env["product.template.attribute.line"].create( { "product_tmpl_id": product_tmpl_id, "attribute_id": attribute_id, "value_ids": value_id, } ) def _create_product_attribute_value(self, name, attribute): return self.env["product.attribute.value"].create( {"name": name, "attribute_id": attribute} ) def _create_product_attribute(self, name): return self.env["product.attribute"].create({"name": name}) def _create_location(self, **vals): return self.env["stock.location"].create(dict(usage="internal", **vals)) def _create_location_route(self, **vals): return self.env["stock.location.route"].create( dict( product_categ_selectable=False, product_selectable=True, sequence=10, **vals ) ) class TestStockRequestBase(TestStockRequest): def setUp(self): super().setUp() def test_defaults(self): vals = { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, } stock_request = ( self.stock_request.with_user(self.stock_request_user) .with_context(company_id=self.main_company.id) .create(vals) ) self.assertEqual(stock_request.requested_by, self.stock_request_user) self.assertEqual(stock_request.warehouse_id, self.warehouse) self.assertEqual(stock_request.location_id, self.warehouse.lot_stock_id) def test_defaults_order(self): vals = {} order = ( self.request_order.with_user(self.stock_request_user) .with_context(company_id=self.main_company.id) .create(vals) ) self.assertEqual(order.requested_by, self.stock_request_user) self.assertEqual(order.warehouse_id, self.warehouse) self.assertEqual(order.location_id, self.warehouse.lot_stock_id) def test_onchanges_order(self): expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } order = self.request_order.with_user(self.stock_request_user).new(vals) self.stock_request_user.company_id = self.company_2 order.company_id = self.company_2 order.onchange_company_id() stock_request = order.stock_request_ids self.assertEqual(order.warehouse_id, self.wh2) self.assertEqual(order.location_id, self.wh2.lot_stock_id) self.assertEqual(order.warehouse_id, stock_request.warehouse_id) procurement_group = self.env["procurement.group"].create({"name": "TEST"}) order.procurement_group_id = procurement_group order.onchange_procurement_group_id() self.assertEqual( order.procurement_group_id, order.stock_request_ids.procurement_group_id ) order.procurement_group_id = procurement_group order.onchange_procurement_group_id() self.assertEqual( order.procurement_group_id, order.stock_request_ids.procurement_group_id ) order.picking_policy = "one" order.onchange_picking_policy() self.assertEqual(order.picking_policy, order.stock_request_ids.picking_policy) order.expected_date = datetime.now() order.onchange_expected_date() self.assertEqual(order.expected_date, order.stock_request_ids.expected_date) order.requested_by = self.stock_request_manager order.onchange_requested_by() self.assertEqual(order.requested_by, order.stock_request_ids.requested_by) def test_onchanges(self): self.product.route_ids = [(6, 0, self.route.ids)] vals = { "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, } stock_request = self.stock_request.with_user(self.stock_request_user).new(vals) stock_request.product_id = self.product vals = stock_request.default_get(["warehouse_id", "company_id"]) stock_request.update(vals) stock_request.onchange_product_id() self.assertIn(self.route.id, stock_request.route_ids.ids) self.stock_request_user.company_id = self.company_2 stock_request.company_id = self.company_2 stock_request.onchange_company_id() self.assertEqual(stock_request.warehouse_id, self.wh2) self.assertEqual(stock_request.location_id, self.wh2.lot_stock_id) product = self.env["product.product"].create( { "name": "Wheat", "uom_id": self.env.ref("uom.product_uom_kgm").id, "uom_po_id": self.env.ref("uom.product_uom_kgm").id, } ) # Test onchange_product_id stock_request.product_id = product stock_request.onchange_product_id() self.assertEqual( stock_request.product_uom_id, self.env.ref("uom.product_uom_kgm") ) stock_request.product_id = self.env["product.product"] # Test onchange_warehouse_id wh2_2 = ( self.env["stock.warehouse"] .with_context(company_id=self.company_2.id) .create( { "name": "C2_2", "code": "C2_2", "company_id": self.company_2.id, "partner_id": self.company_2_address.id, } ) ) stock_request.warehouse_id = wh2_2 stock_request.onchange_warehouse_id() self.assertEqual(stock_request.warehouse_id, wh2_2) self.stock_request_user.company_id = self.main_company stock_request.warehouse_id = self.warehouse stock_request.onchange_warehouse_id() self.assertEqual(stock_request.company_id, self.main_company) self.assertEqual(stock_request.location_id, self.warehouse.lot_stock_id) def test_stock_request_order_validations_01(self): """Testing the discrepancy in warehouse_id between stock request and order""" expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.wh2.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } with self.assertRaises(exceptions.ValidationError): self.request_order.with_user(self.stock_request_user).create(vals) def test_stock_request_order_validations_02(self): """Testing the discrepancy in location_id between stock request and order""" expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.wh2.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } with self.assertRaises(exceptions.ValidationError): self.request_order.with_user(self.stock_request_user).create(vals) def test_stock_request_order_validations_03(self): """Testing the discrepancy in requested_by between stock request and order""" expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "requested_by": self.stock_request_user.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "requested_by": self.stock_request_manager.id, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } with self.assertRaises(exceptions.ValidationError): self.request_order.with_user(self.stock_request_user).create(vals) def test_stock_request_order_validations_04(self): """Testing the discrepancy in procurement_group_id between stock request and order""" procurement_group = self.env["procurement.group"].create( {"name": "Procurement"} ) expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "procurement_group_id": procurement_group.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } with self.assertRaises(exceptions.ValidationError): self.request_order.with_user(self.stock_request_user).create(vals) def test_stock_request_order_validations_05(self): """Testing the discrepancy in company between stock request and order""" expected_date = fields.Datetime.now() vals = { "company_id": self.company_2.id, "warehouse_id": self.wh2.id, "location_id": self.wh2.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.company_2.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } with self.assertRaises(exceptions.ValidationError): self.request_order.with_user(self.stock_request_user).create(vals) def test_stock_request_order_validations_06(self): """Testing the discrepancy in expected dates between stock request and order""" expected_date = fields.Datetime.now() child_expected_date = "2015-01-01" vals = { "company_id": self.company_2.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": child_expected_date, }, ) ], } with self.assertRaises(exceptions.ValidationError): self.request_order.create(vals) def test_stock_request_order_validations_07(self): """Testing the discrepancy in picking policy between stock request and order""" expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "picking_policy": "one", "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } with self.assertRaises(exceptions.ValidationError): self.request_order.with_user(self.stock_request_user).create(vals) def test_stock_request_validations_01(self): vals = { "product_id": self.product.id, "product_uom_id": self.env.ref("uom.product_uom_kgm").id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, } # Select a UoM that is incompatible with the product's UoM with self.assertRaises(exceptions.ValidationError): self.stock_request.with_user(self.stock_request_user).create(vals) def test_create_request_01(self): expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } order = self.request_order.with_user(self.stock_request_user).create(vals) stock_request = order.stock_request_ids self.product.route_ids = [(6, 0, self.route.ids)] order.with_user(self.stock_request_manager).action_confirm() self.assertEqual(order.state, "open") self.assertEqual(stock_request.state, "open") self.assertEqual(len(order.picking_ids), 1) self.assertEqual(len(order.move_ids), 1) self.assertEqual(len(stock_request.picking_ids), 1) self.assertEqual(len(stock_request.move_ids), 1) self.assertEqual( stock_request.move_ids[0].location_dest_id, stock_request.location_id ) self.assertEqual(stock_request.qty_in_progress, stock_request.product_uom_qty) self.env["stock.quant"].create( { "product_id": self.product.id, "location_id": self.ressuply_loc.id, "quantity": 5.0, } ) picking = stock_request.picking_ids[0] picking.with_user(self.stock_request_manager).action_confirm() self.assertEqual(stock_request.qty_in_progress, 5.0) self.assertEqual(stock_request.qty_done, 0.0) picking.with_user(self.stock_request_manager).action_assign() self.assertEqual(picking.origin, order.name) packout1 = picking.move_line_ids[0] packout1.qty_done = 5 picking.with_user(self.stock_request_manager)._action_done() self.assertEqual(stock_request.qty_in_progress, 0.0) self.assertEqual(stock_request.qty_done, stock_request.product_uom_qty) self.assertEqual(order.state, "done") self.assertEqual(stock_request.state, "done") def test_create_request_02(self): """Use different UoM's""" vals = { "product_id": self.product.id, "product_uom_id": self.uom_dozen.id, "product_uom_qty": 1.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, } stock_request = self.stock_request.with_user(self.stock_request_user).create( vals ) self.product.route_ids = [(6, 0, self.route.ids)] stock_request.with_user(self.stock_request_manager).action_confirm() self.assertEqual(stock_request.state, "open") self.assertEqual(len(stock_request.picking_ids), 1) self.assertEqual(len(stock_request.move_ids), 1) self.assertEqual( stock_request.move_ids[0].location_dest_id, stock_request.location_id ) self.assertEqual(stock_request.qty_in_progress, stock_request.product_uom_qty) self.env["stock.quant"].create( { "product_id": self.product.id, "location_id": self.ressuply_loc.id, "quantity": 12.0, } ) picking = stock_request.picking_ids[0] picking.with_user(self.stock_request_manager).action_confirm() self.assertEqual(stock_request.qty_in_progress, 1.0) self.assertEqual(stock_request.qty_done, 0.0) picking.with_user(self.stock_request_manager).action_assign() packout1 = picking.move_line_ids[0] packout1.qty_done = 1 picking.with_user(self.stock_request_manager)._action_done() self.assertEqual(stock_request.qty_in_progress, 0.0) self.assertEqual(stock_request.qty_done, stock_request.product_uom_qty) self.assertEqual(stock_request.state, "done") def test_create_request_03(self): """Multiple stock requests""" vals = { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 4.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, } stock_request_1 = ( self.env["stock.request"].with_user(self.stock_request_user).create(vals) ) stock_request_2 = ( self.env["stock.request"] .with_user(self.stock_request_manager.id) .create(vals) ) stock_request_2.product_uom_qty = 6.0 self.product.route_ids = [(6, 0, self.route.ids)] stock_request_1.sudo().action_confirm() stock_request_2.sudo().action_confirm() self.assertEqual(len(stock_request_1.sudo().picking_ids), 1) self.assertEqual( stock_request_1.sudo().picking_ids, stock_request_2.sudo().picking_ids ) self.assertEqual( stock_request_1.sudo().move_ids, stock_request_2.sudo().move_ids ) self.env["stock.quant"].create( { "product_id": self.product.id, "location_id": self.ressuply_loc.id, "quantity": 10.0, } ) picking = stock_request_1.sudo().picking_ids[0] picking.action_confirm() picking.action_assign() self.assertEqual(stock_request_1.qty_in_progress, 4) self.assertEqual(stock_request_1.qty_done, 0) self.assertEqual(stock_request_1.qty_cancelled, 0) self.assertEqual(stock_request_2.qty_in_progress, 6) self.assertEqual(stock_request_2.qty_done, 0) self.assertEqual(stock_request_2.qty_cancelled, 0) packout1 = picking.move_line_ids[0] packout1.qty_done = 4 self.env["stock.backorder.confirmation"].with_context( button_validate_picking_ids=[picking.id] ).create({"pick_ids": [(4, picking.id)]}).process_cancel_backorder() self.assertEqual(stock_request_1.qty_in_progress, 0) self.assertEqual(stock_request_1.qty_done, 4) self.assertEqual(stock_request_1.qty_cancelled, 0) self.assertEqual(stock_request_1.state, "done") self.assertEqual(stock_request_2.qty_in_progress, 0) self.assertEqual(stock_request_2.qty_done, 0) self.assertEqual(stock_request_2.qty_cancelled, 6) self.assertEqual(stock_request_2.state, "cancel") def test_cancel_request(self): expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } order = self.request_order.with_user(self.stock_request_user).create(vals) self.product.route_ids = [(6, 0, self.route.ids)] order.with_user(self.stock_request_manager).action_confirm() stock_request = order.stock_request_ids self.assertEqual(len(order.picking_ids), 1) self.assertEqual(len(order.move_ids), 1) self.assertEqual(len(stock_request.picking_ids), 1) self.assertEqual(len(stock_request.move_ids), 1) self.assertEqual( stock_request.move_ids[0].location_dest_id, stock_request.location_id ) self.assertEqual(stock_request.qty_in_progress, stock_request.product_uom_qty) self.env["stock.quant"].create( { "product_id": self.product.id, "location_id": self.ressuply_loc.id, "quantity": 5.0, } ) picking = stock_request.picking_ids[0] picking.with_user(self.stock_request_user).action_confirm() self.assertEqual(stock_request.qty_in_progress, 5.0) self.assertEqual(stock_request.qty_done, 0.0) picking.with_user(self.stock_request_manager).action_assign() order.with_user(self.stock_request_manager).action_cancel() self.assertEqual(stock_request.qty_in_progress, 0.0) self.assertEqual(stock_request.qty_done, 0.0) self.assertEqual(len(stock_request.picking_ids), 0) # Set the request back to draft order.with_user(self.stock_request_user).action_draft() self.assertEqual(order.state, "draft") self.assertEqual(stock_request.state, "draft") # Re-confirm. We expect new pickings to be created order.with_user(self.stock_request_manager).action_confirm() self.assertEqual(len(stock_request.picking_ids), 1) self.assertEqual(len(stock_request.move_ids), 2) def test_view_actions(self): expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } order = self.request_order.create(vals) self.product.route_ids = [(6, 0, self.route.ids)] order.with_user(self.stock_request_manager).action_confirm() stock_request = order.stock_request_ids self.assertTrue(stock_request.picking_ids) self.assertTrue(order.picking_ids) action = order.action_view_transfer() self.assertEqual("domain" in action.keys(), True) self.assertEqual("views" in action.keys(), True) self.assertEqual(action["res_id"], order.picking_ids[0].id) action = order.action_view_stock_requests() self.assertEqual("domain" in action.keys(), True) self.assertEqual("views" in action.keys(), True) self.assertEqual(action["res_id"], stock_request[0].id) action = stock_request.action_view_transfer() self.assertEqual("domain" in action.keys(), True) self.assertEqual("views" in action.keys(), True) self.assertEqual(action["res_id"], stock_request.picking_ids[0].id) action = stock_request.picking_ids[0].action_view_stock_request() self.assertEqual(action["type"], "ir.actions.act_window") self.assertEqual(action["res_id"], stock_request.id) def test_stock_request_constrains(self): vals = { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, } stock_request = self.stock_request.with_user(self.stock_request_user).create( vals ) # Cannot assign a warehouse that belongs to another company with self.assertRaises(exceptions.ValidationError): stock_request.warehouse_id = self.wh2 # Cannot assign a product that belongs to another company with self.assertRaises(exceptions.ValidationError): stock_request.product_id = self.product_company_2 # Cannot assign a location that belongs to another company with self.assertRaises(exceptions.ValidationError): stock_request.location_id = self.wh2.lot_stock_id # Cannot assign a route that belongs to another company with self.assertRaises(exceptions.ValidationError): stock_request.route_id = self.route_2 def test_stock_request_order_from_products(self): template_a = self.env["product.template"].create({"name": "ProductTemplate"}) product_attribute = self._create_product_attribute("Attribute") product_att_value = self._create_product_attribute_value( "Name-1", product_attribute.id ) product_tmpl_att_line = self._create_product_template_attribute_line( template_a.id, product_attribute.id, product_att_value ) template_a.attribute_line_ids |= product_tmpl_att_line product_tmpl_att_value = self.env["product.template.attribute.value"].search( [] )[-1] product_a1 = self.env["product.product"].search( [ ( "product_template_variant_value_ids.name", "=", product_tmpl_att_value.name, ) ] ) product_att_value = self._create_product_attribute_value( "Name-2", product_attribute.id ) template_a.attribute_line_ids.value_ids |= product_att_value product_a2 = self.env["product.product"].search( [("product_template_variant_value_ids.name", "=", product_att_value.name)] ) product_att_value = self._create_product_attribute_value( "Name-3", product_attribute.id ) template_a.attribute_line_ids.value_ids |= product_att_value product_a3 = self.env["product.product"].search( [("product_template_variant_value_ids.name", "=", product_att_value.name)] ) product_b1 = self._create_product("CODEB1", "Product B1", self.main_company.id) template_b = product_b1.product_tmpl_id # One archived variant of B self._create_product( "CODEB2", "Product B2", self.main_company.id, product_tmpl_id=template_b.id, active=False, ) order = self.request_order # Selecting some variants and creating an order preexisting = order.search([]) wanted_products = product_a1 + product_a2 + product_b1 action = order._create_from_product_multiselect(wanted_products) new_order = order.search([]) - preexisting self.assertEqual(len(new_order), 1) self.assertEqual( action["res_id"], new_order.id, msg="Returned action references the wrong record", ) self.assertEqual( Counter(wanted_products), Counter(new_order.stock_request_ids.mapped("product_id")), msg="Not all wanted products were ordered", ) # Selecting a template and creating an order preexisting = order.search([]) action = order._create_from_product_multiselect(template_a) new_order = order.search([]) - preexisting self.assertEqual(len(new_order), 1) self.assertEqual( action["res_id"], new_order.id, msg="Returned action references the wrong record", ) self.assertEqual( Counter(product_a1 + product_a2 + product_a3), Counter(new_order.stock_request_ids.mapped("product_id")), msg="Not all of the template's variants were ordered", ) # Selecting a template preexisting = order.search([]) action = order._create_from_product_multiselect(template_a + template_b) new_order = order.search([]) - preexisting self.assertEqual(len(new_order), 1) self.assertEqual( action["res_id"], new_order.id, msg="Returned action references the wrong record", ) self.assertEqual( Counter(product_a1 + product_a2 + product_a3 + product_b1), Counter(new_order.stock_request_ids.mapped("product_id")), msg="Inactive variant was ordered though it shouldn't have been", ) # If a user does not have stock request rights, they can still trigger # the action from the products, so test that they get a friendlier # error message. self.stock_request_user.groups_id -= self.stock_request_user_group with self.assertRaises(exceptions.AccessError): order.with_user(self.stock_request_user)._create_from_product_multiselect( template_a + template_b ) # Empty recordsets should just return False self.assertFalse( order._create_from_product_multiselect(self.env["product.product"]) ) # Wrong model should just raise ValidationError with self.assertRaises(exceptions.ValidationError): order._create_from_product_multiselect(self.stock_request_user) def test_allow_virtual_location(self): self.main_company.stock_request_allow_virtual_loc = True vals = { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.virtual_loc.id, } stock_request = self.stock_request.with_user(self.stock_request_user).create( vals ) self.assertTrue(stock_request.allow_virtual_location) vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.virtual_loc.id, } order = self.request_order.with_user(self.stock_request_user).create(vals) self.assertTrue(order.allow_virtual_location) def test_onchange_wh_no_effect_from_order(self): expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.virtual_loc.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.virtual_loc.id, "expected_date": expected_date, }, ) ], } order = self.request_order.with_user(self.stock_request_user).create(vals) order.stock_request_ids.onchange_warehouse_id() self.assertEqual(order.stock_request_ids[0].location_id, self.virtual_loc) def test_cancellation(self): group = self.env["procurement.group"].create({"name": "Procurement group"}) product2 = self._create_product("SH2", "Shoes2", False) product3 = self._create_product("SH3", "Shoes3", False) self.product.type = "consu" product2.type = "consu" product3.type = "consu" vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.virtual_loc.id, "procurement_group_id": group.id, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "procurement_group_id": group.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.virtual_loc.id, }, ), ( 0, 0, { "product_id": product2.id, "product_uom_id": self.product.uom_id.id, "procurement_group_id": group.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.virtual_loc.id, }, ), ( 0, 0, { "product_id": product3.id, "product_uom_id": self.product.uom_id.id, "procurement_group_id": group.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.virtual_loc.id, }, ), ], } order = self.request_order.create(vals) self.product.route_ids = [(6, 0, self.route.ids)] product2.route_ids = [(6, 0, self.route.ids)] product3.route_ids = [(6, 0, self.route.ids)] order.action_confirm() picking = order.picking_ids self.assertEqual(1, len(picking)) picking.action_assign() self.assertEqual(3, len(picking.move_lines)) line = picking.move_lines.filtered(lambda r: r.product_id == self.product) line.quantity_done = 1 sr1 = order.stock_request_ids.filtered(lambda r: r.product_id == self.product) sr2 = order.stock_request_ids.filtered(lambda r: r.product_id == product2) sr3 = order.stock_request_ids.filtered(lambda r: r.product_id == product3) self.assertNotEqual(sr1.state, "done") self.assertNotEqual(sr2.state, "done") self.assertNotEqual(sr3.state, "done") self.env["stock.backorder.confirmation"].with_context( button_validate_picking_ids=[picking.id] ).create({"pick_ids": [(4, picking.id)]}).process() sr1.refresh() sr2.refresh() sr3.refresh() self.assertNotEqual(sr1.state, "done") self.assertNotEqual(sr2.state, "done") self.assertNotEqual(sr3.state, "done") picking = order.picking_ids.filtered( lambda r: r.state not in ["done", "cancel"] ) self.assertEqual(1, len(picking)) picking.action_assign() self.assertEqual(3, len(picking.move_lines)) line = picking.move_lines.filtered(lambda r: r.product_id == self.product) line.quantity_done = 4 line = picking.move_lines.filtered(lambda r: r.product_id == product2) line.quantity_done = 1 self.env["stock.backorder.confirmation"].with_context( button_validate_picking_ids=[picking.id] ).create({"pick_ids": [(4, picking.id)]}).process_cancel_backorder() sr1.refresh() sr2.refresh() sr3.refresh() self.assertEqual(sr1.state, "done") self.assertEqual(sr1.qty_done, 5) self.assertEqual(sr1.qty_cancelled, 0) self.assertEqual(sr2.state, "cancel") self.assertEqual(sr2.qty_done, 1) self.assertEqual(sr2.qty_cancelled, 4) self.assertEqual(sr3.state, "cancel") self.assertEqual(sr3.qty_done, 0) self.assertEqual(sr3.qty_cancelled, 5) # Set the request order to done if there are any delivered lines self.assertEqual(order.state, "done")
40.724261
45,489
12,533
py
PYTHON
15.0
# Copyright 2018 Creu Blanca # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError class StockRequestOrder(models.Model): _name = "stock.request.order" _description = "Stock Request Order" _inherit = ["mail.thread", "mail.activity.mixin"] _order = "id desc" @api.model def default_get(self, fields): res = super().default_get(fields) warehouse = None if "warehouse_id" not in res and res.get("company_id"): warehouse = self.env["stock.warehouse"].search( [("company_id", "=", res["company_id"])], limit=1 ) if warehouse: res["warehouse_id"] = warehouse.id res["location_id"] = warehouse.lot_stock_id.id return res def __get_request_order_states(self): return self.env["stock.request"].fields_get(allfields=["state"])["state"][ "selection" ] def _get_request_order_states(self): return self.__get_request_order_states() def _get_default_requested_by(self): return self.env["res.users"].browse(self.env.uid) name = fields.Char( copy=False, required=True, readonly=True, states={"draft": [("readonly", False)]}, default="/", ) state = fields.Selection( selection=_get_request_order_states, string="Status", copy=False, default="draft", index=True, readonly=True, tracking=True, ) requested_by = fields.Many2one( "res.users", required=True, tracking=True, default=lambda s: s._get_default_requested_by(), ) warehouse_id = fields.Many2one( comodel_name="stock.warehouse", string="Warehouse", check_company=True, readonly=True, ondelete="cascade", required=True, states={"draft": [("readonly", False)]}, ) location_id = fields.Many2one( comodel_name="stock.location", string="Location", domain="not allow_virtual_location and " "[('usage', 'in', ['internal', 'transit'])] or []", readonly=True, ondelete="cascade", required=True, states={"draft": [("readonly", False)]}, ) allow_virtual_location = fields.Boolean( related="company_id.stock_request_allow_virtual_loc", readonly=True ) procurement_group_id = fields.Many2one( "procurement.group", "Procurement Group", readonly=True, states={"draft": [("readonly", False)]}, help="Moves created through this stock request will be put in this " "procurement group. If none is given, the moves generated by " "procurement rules will be grouped into one big picking.", ) company_id = fields.Many2one( "res.company", "Company", required=True, readonly=True, states={"draft": [("readonly", False)]}, default=lambda self: self.env.company, ) expected_date = fields.Datetime( default=fields.Datetime.now, index=True, required=True, readonly=True, states={"draft": [("readonly", False)]}, help="Date when you expect to receive the goods.", ) picking_policy = fields.Selection( [ ("direct", "Receive each product when available"), ("one", "Receive all products at once"), ], string="Shipping Policy", required=True, readonly=True, states={"draft": [("readonly", False)]}, default="direct", ) move_ids = fields.One2many( comodel_name="stock.move", compute="_compute_move_ids", string="Stock Moves", readonly=True, ) picking_ids = fields.One2many( "stock.picking", compute="_compute_picking_ids", string="Pickings", readonly=True, ) picking_count = fields.Integer( string="Delivery Orders", compute="_compute_picking_ids", readonly=True ) stock_request_ids = fields.One2many( "stock.request", inverse_name="order_id", copy=True ) stock_request_count = fields.Integer( string="Stock requests", compute="_compute_stock_request_count", readonly=True ) _sql_constraints = [ ("name_uniq", "unique(name, company_id)", "Stock Request name must be unique") ] @api.depends("stock_request_ids.allocation_ids") def _compute_picking_ids(self): for record in self: record.picking_ids = record.stock_request_ids.mapped("picking_ids") record.picking_count = len(record.picking_ids) @api.depends("stock_request_ids") def _compute_move_ids(self): for record in self: record.move_ids = record.stock_request_ids.mapped("move_ids") @api.depends("stock_request_ids") def _compute_stock_request_count(self): for record in self: record.stock_request_count = len(record.stock_request_ids) @api.onchange("requested_by") def onchange_requested_by(self): self.change_childs() @api.onchange("expected_date") def onchange_expected_date(self): self.change_childs() @api.onchange("picking_policy") def onchange_picking_policy(self): self.change_childs() @api.onchange("location_id") def onchange_location_id(self): if self.location_id: loc_wh = self.location_id.warehouse_id if loc_wh and self.warehouse_id != loc_wh: self.warehouse_id = loc_wh self.with_context(no_change_childs=True).onchange_warehouse_id() self.change_childs() @api.onchange("warehouse_id") def onchange_warehouse_id(self): if self.warehouse_id: # search with sudo because the user may not have permissions loc_wh = self.location_id.warehouse_id if self.warehouse_id != loc_wh: self.location_id = self.warehouse_id.lot_stock_id self.with_context(no_change_childs=True).onchange_location_id() if self.warehouse_id.company_id != self.company_id: self.company_id = self.warehouse_id.company_id self.with_context(no_change_childs=True).onchange_company_id() self.change_childs() @api.onchange("procurement_group_id") def onchange_procurement_group_id(self): self.change_childs() @api.onchange("company_id") def onchange_company_id(self): if self.company_id and ( not self.warehouse_id or self.warehouse_id.company_id != self.company_id ): self.warehouse_id = self.env["stock.warehouse"].search( [("company_id", "=", self.company_id.id)], limit=1 ) self.with_context(no_change_childs=True).onchange_warehouse_id() self.change_childs() def change_childs(self): if not self._context.get("no_change_childs", False): for line in self.stock_request_ids: line.warehouse_id = self.warehouse_id line.location_id = self.location_id line.company_id = self.company_id line.picking_policy = self.picking_policy line.expected_date = self.expected_date line.requested_by = self.requested_by line.procurement_group_id = self.procurement_group_id def action_confirm(self): if not self.stock_request_ids: raise UserError( _("There should be at least one request item for confirming the order.") ) self.mapped("stock_request_ids").action_confirm() self.write({"state": "open"}) return True def action_draft(self): self.mapped("stock_request_ids").action_draft() self.write({"state": "draft"}) return True def action_cancel(self): self.mapped("stock_request_ids").action_cancel() self.write({"state": "cancel"}) return True def action_done(self): self.write({"state": "done"}) return True def check_done(self): for rec in self: if not rec.stock_request_ids.filtered( lambda r: r.state not in ["done", "cancel"] ): rec.action_done() return def check_cancel(self): for rec in self: if not rec.stock_request_ids.filtered(lambda r: r.state != "cancel"): rec.write({"state": "cancel"}) return def action_view_transfer(self): action = self.env["ir.actions.act_window"]._for_xml_id( "stock.action_picking_tree_all" ) pickings = self.mapped("picking_ids") if len(pickings) > 1: action["domain"] = [("id", "in", pickings.ids)] elif pickings: action["views"] = [(self.env.ref("stock.view_picking_form").id, "form")] action["res_id"] = pickings.id return action def action_view_stock_requests(self): action = self.env["ir.actions.act_window"]._for_xml_id( "stock_request.action_stock_request_form" ) if len(self.stock_request_ids) > 1: action["domain"] = [("order_id", "in", self.ids)] elif self.stock_request_ids: action["views"] = [ (self.env.ref("stock_request.view_stock_request_form").id, "form") ] action["res_id"] = self.stock_request_ids.id return action @api.model def create(self, vals): upd_vals = vals.copy() if upd_vals.get("name", "/") == "/": upd_vals["name"] = self.env["ir.sequence"].next_by_code( "stock.request.order" ) return super().create(upd_vals) def unlink(self): if self.filtered(lambda r: r.state != "draft"): raise UserError(_("Only orders on draft state can be unlinked")) return super().unlink() @api.constrains("warehouse_id", "company_id") def _check_warehouse_company(self): if any( request.warehouse_id.company_id != request.company_id for request in self ): raise ValidationError( _( "The company of the stock request must match with " "that of the warehouse." ) ) @api.constrains("location_id", "company_id") def _check_location_company(self): if any( request.location_id.company_id and request.location_id.company_id != request.company_id for request in self ): raise ValidationError( _( "The company of the stock request must match with " "that of the location." ) ) @api.model def _create_from_product_multiselect(self, products): if not products: return False if products._name not in ("product.product", "product.template"): raise ValidationError( _("This action only works in the context of products") ) if products._name == "product.template": # search instead of mapped so we don't include archived variants products = self.env["product.product"].search( [("product_tmpl_id", "in", products.ids)] ) expected = self.default_get(["expected_date"])["expected_date"] order = self.env["stock.request.order"].create( dict( expected_date=expected, stock_request_ids=[ ( 0, 0, dict( product_id=product.id, product_uom_id=product.uom_id.id, product_uom_qty=1.0, expected_date=expected, ), ) for product in products ], ) ) action = self.env["ir.actions.act_window"]._for_xml_id( "stock_request.stock_request_order_action" ) action["views"] = [ (self.env.ref("stock_request.stock_request_order_form").id, "form") ] action["res_id"] = order.id return action
34.621547
12,533
1,474
py
PYTHON
15.0
# Copyright 2018 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError class StockLocation(models.Model): _inherit = "stock.location" @api.constrains("company_id") def _check_company_stock_request(self): if any( rec.company_id and self.env["stock.request"].search( [("company_id", "!=", rec.company_id.id), ("location_id", "=", rec.id)], limit=1, ) for rec in self ): raise ValidationError( _( "You cannot change the company of the location, as it is " "already assigned to stock requests that belong to " "another company." ) ) if any( rec.company_id and self.env["stock.request.order"].search( [ ("company_id", "!=", rec.company_id.id), ("warehouse_id", "=", rec.id), ], limit=1, ) for rec in self ): raise ValidationError( _( "You cannot change the company of the location, as it is " "already assigned to stock request orders that belong to " "another company." ) )
32.755556
1,474
2,867
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestAllocation(models.Model): _name = "stock.request.allocation" _description = "Stock Request Allocation" stock_request_id = fields.Many2one( string="Stock Request", comodel_name="stock.request", required=True, ondelete="cascade", ) company_id = fields.Many2one( string="Company", comodel_name="res.company", readonly=True, related="stock_request_id.company_id", store=True, ) stock_move_id = fields.Many2one( string="Stock Move", comodel_name="stock.move", required=True, ondelete="cascade", ) product_id = fields.Many2one( string="Product", comodel_name="product.product", related="stock_request_id.product_id", readonly=True, ) product_uom_id = fields.Many2one( string="UoM", comodel_name="uom.uom", related="stock_request_id.product_uom_id", readonly=True, ) requested_product_uom_qty = fields.Float( "Requested Quantity (UoM)", help="Quantity of the stock request allocated to the stock move, " "in the UoM of the Stock Request", ) requested_product_qty = fields.Float( "Requested Quantity", help="Quantity of the stock request allocated to the stock move, " "in the default UoM of the product", compute="_compute_requested_product_qty", ) allocated_product_qty = fields.Float( "Allocated Quantity", copy=False, help="Quantity of the stock request allocated to the stock move, " "in the default UoM of the product", ) open_product_qty = fields.Float( "Open Quantity", compute="_compute_open_product_qty", ) @api.depends( "stock_request_id.product_id", "stock_request_id.product_uom_id", "requested_product_uom_qty", ) def _compute_requested_product_qty(self): for rec in self: rec.requested_product_qty = rec.product_uom_id._compute_quantity( rec.requested_product_uom_qty, rec.product_id.uom_id ) @api.depends( "requested_product_qty", "allocated_product_qty", "stock_move_id", "stock_move_id.state", ) def _compute_open_product_qty(self): for rec in self: if rec.stock_move_id.state in ["cancel", "done"]: rec.open_product_qty = 0.0 else: rec.open_product_qty = ( rec.requested_product_qty - rec.allocated_product_qty ) if rec.open_product_qty < 0.0: rec.open_product_qty = 0.0
31.855556
2,867
1,476
py
PYTHON
15.0
# Copyright 2018 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError class StockWarehouse(models.Model): _inherit = "stock.warehouse" @api.constrains("company_id") def _check_company_stock_request(self): if any( self.env["stock.request"].search( [ ("company_id", "!=", rec.company_id.id), ("warehouse_id", "=", rec.id), ], limit=1, ) for rec in self ): raise ValidationError( _( "You cannot change the company of the warehouse, as it is " "already assigned to stock requests that belong to " "another company." ) ) if any( self.env["stock.request.order"].search( [ ("company_id", "!=", rec.company_id.id), ("warehouse_id", "=", rec.id), ], limit=1, ) for rec in self ): raise ValidationError( _( "You cannot change the company of the warehouse, as it is " "already assigned to stock request orders that belong to " "another company." ) )
32.086957
1,476
2,773
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo import _, api, models class StockMoveLine(models.Model): _inherit = "stock.move.line" @api.model def _stock_request_confirm_done_message_content(self, message_data): title = ( _("Receipt confirmation %(picking_name)s for your Request %(request_name)s") % message_data ) message = "<h3>%s</h3>" % title message += ( _( "The following requested items from Stock Request %(request_name)s " "have now been received in %(location_name)s using Picking %(picking_name)s:" ) % message_data ) message += "<ul>" message += ( _( "<li><b>%(product_name)s</b>: Transferred quantity %(product_qty)s" "%(product_uom)s</li>" ) % message_data ) message += "</ul>" return message def _prepare_message_data(self, ml, request, allocated_qty): return { "request_name": request.name, "picking_name": ml.picking_id.name, "product_name": ml.product_id.name_get()[0][1], "product_qty": allocated_qty, "product_uom": ml.product_uom_id.name, "location_name": ml.location_dest_id.name_get()[0][1], } def _action_done(self): res = super(StockMoveLine, self)._action_done() for ml in self.filtered(lambda m: m.exists() and m.move_id.allocation_ids): qty_done = ml.product_uom_id._compute_quantity( ml.qty_done, ml.product_id.uom_id ) # We do sudo because potentially the user that completes the move # may not have permissions for stock.request. to_allocate_qty = qty_done for allocation in ml.move_id.allocation_ids.sudo(): allocated_qty = 0.0 if allocation.open_product_qty: allocated_qty = min(allocation.open_product_qty, to_allocate_qty) allocation.allocated_product_qty += allocated_qty to_allocate_qty -= allocated_qty if allocated_qty: request = allocation.stock_request_id message_data = self._prepare_message_data( ml, request, allocated_qty ) message = self._stock_request_confirm_done_message_content( message_data ) request.message_post(body=message, subtype_xmlid="mail.mt_comment") request.check_done() return res
39.056338
2,773
13,469
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools import float_compare class StockRequest(models.Model): _name = "stock.request" _description = "Stock Request" _inherit = "stock.request.abstract" _order = "id desc" def _get_default_requested_by(self): return self.env["res.users"].browse(self.env.uid) @staticmethod def _get_expected_date(): return fields.Datetime.now() name = fields.Char(states={"draft": [("readonly", False)]}) state = fields.Selection( selection=[ ("draft", "Draft"), ("open", "In progress"), ("done", "Done"), ("cancel", "Cancelled"), ], string="Status", copy=False, default="draft", index=True, readonly=True, tracking=True, ) requested_by = fields.Many2one( "res.users", required=True, tracking=True, default=lambda s: s._get_default_requested_by(), ) expected_date = fields.Datetime( index=True, required=True, readonly=True, states={"draft": [("readonly", False)]}, help="Date when you expect to receive the goods.", ) picking_policy = fields.Selection( [ ("direct", "Receive each product when available"), ("one", "Receive all products at once"), ], string="Shipping Policy", required=True, readonly=True, states={"draft": [("readonly", False)]}, default="direct", ) move_ids = fields.One2many( comodel_name="stock.move", compute="_compute_move_ids", string="Stock Moves", readonly=True, ) picking_ids = fields.One2many( "stock.picking", compute="_compute_picking_ids", string="Pickings", readonly=True, ) qty_in_progress = fields.Float( digits="Product Unit of Measure", readonly=True, compute="_compute_qty", store=True, help="Quantity in progress.", ) qty_done = fields.Float( digits="Product Unit of Measure", readonly=True, compute="_compute_qty", store=True, help="Quantity completed", ) qty_cancelled = fields.Float( digits="Product Unit of Measure", readonly=True, compute="_compute_qty", store=True, help="Quantity cancelled", ) picking_count = fields.Integer( string="Delivery Orders", compute="_compute_picking_ids", readonly=True, ) allocation_ids = fields.One2many( comodel_name="stock.request.allocation", inverse_name="stock_request_id", string="Stock Request Allocation", ) order_id = fields.Many2one("stock.request.order", readonly=True) warehouse_id = fields.Many2one( states={"draft": [("readonly", False)]}, readonly=True ) location_id = fields.Many2one( states={"draft": [("readonly", False)]}, readonly=True ) product_id = fields.Many2one(states={"draft": [("readonly", False)]}, readonly=True) product_uom_id = fields.Many2one( states={"draft": [("readonly", False)]}, readonly=True ) product_uom_qty = fields.Float( states={"draft": [("readonly", False)]}, readonly=True ) procurement_group_id = fields.Many2one( states={"draft": [("readonly", False)]}, readonly=True ) company_id = fields.Many2one(states={"draft": [("readonly", False)]}, readonly=True) route_id = fields.Many2one(states={"draft": [("readonly", False)]}, readonly=True) _sql_constraints = [ ("name_uniq", "unique(name, company_id)", "Stock Request name must be unique") ] @api.depends("allocation_ids", "allocation_ids.stock_move_id") def _compute_move_ids(self): for request in self: request.move_ids = request.allocation_ids.mapped("stock_move_id") @api.depends( "allocation_ids", "allocation_ids.stock_move_id", "allocation_ids.stock_move_id.picking_id", ) def _compute_picking_ids(self): for request in self: request.picking_count = 0 request.picking_ids = self.env["stock.picking"] request.picking_ids = request.move_ids.filtered( lambda m: m.state != "cancel" ).mapped("picking_id") request.picking_count = len(request.picking_ids) @api.depends( "allocation_ids", "allocation_ids.stock_move_id.state", "allocation_ids.stock_move_id.move_line_ids", "allocation_ids.stock_move_id.move_line_ids.qty_done", ) def _compute_qty(self): for request in self: incoming_qty = 0.0 other_qty = 0.0 for allocation in request.allocation_ids: if allocation.stock_move_id.picking_code == "incoming": incoming_qty += allocation.allocated_product_qty else: other_qty += allocation.allocated_product_qty done_qty = abs(other_qty - incoming_qty) open_qty = sum(request.allocation_ids.mapped("open_product_qty")) uom = request.product_id.uom_id request.qty_done = uom._compute_quantity(done_qty, request.product_uom_id) request.qty_in_progress = uom._compute_quantity( open_qty, request.product_uom_id ) request.qty_cancelled = ( max( 0, uom._compute_quantity( request.product_qty - done_qty - open_qty, request.product_uom_id, ), ) if request.allocation_ids else 0 ) @api.constrains("order_id", "requested_by") def check_order_requested_by(self): if self.order_id and self.order_id.requested_by != self.requested_by: raise ValidationError(_("Requested by must be equal to the order")) @api.constrains("order_id", "warehouse_id") def check_order_warehouse_id(self): if self.order_id and self.order_id.warehouse_id != self.warehouse_id: raise ValidationError(_("Warehouse must be equal to the order")) @api.constrains("order_id", "location_id") def check_order_location(self): if self.order_id and self.order_id.location_id != self.location_id: raise ValidationError(_("Location must be equal to the order")) @api.constrains("order_id", "procurement_group_id") def check_order_procurement_group(self): if ( self.order_id and self.order_id.procurement_group_id != self.procurement_group_id ): raise ValidationError(_("Procurement group must be equal to the order")) @api.constrains("order_id", "company_id") def check_order_company(self): if self.order_id and self.order_id.company_id != self.company_id: raise ValidationError(_("Company must be equal to the order")) @api.constrains("order_id", "expected_date") def check_order_expected_date(self): if self.order_id and self.order_id.expected_date != self.expected_date: raise ValidationError(_("Expected date must be equal to the order")) @api.constrains("order_id", "picking_policy") def check_order_picking_policy(self): if self.order_id and self.order_id.picking_policy != self.picking_policy: raise ValidationError(_("The picking policy must be equal to the order")) def _action_confirm(self): self._action_launch_procurement_rule() self.write({"state": "open"}) def action_confirm(self): self._action_confirm() return True def action_draft(self): self.write({"state": "draft"}) return True def action_cancel(self): self.sudo().mapped("move_ids")._action_cancel() self.write({"state": "cancel"}) self.mapped("order_id").check_cancel() return True def action_done(self): self.write({"state": "done"}) self.mapped("order_id").check_done() return True def check_cancel(self): for request in self: if request._check_cancel_allocation(): request.write({"state": "cancel"}) request.mapped("order_id").check_cancel() def check_done(self): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) for request in self: allocated_qty = sum(request.allocation_ids.mapped("allocated_product_qty")) qty_done = request.product_id.uom_id._compute_quantity( allocated_qty, request.product_uom_id ) if ( float_compare( qty_done, request.product_uom_qty, precision_digits=precision ) >= 0 ): request.action_done() elif request._check_cancel_allocation(): # If qty_done=0 and qty_cancelled>0 it's cancelled request.write({"state": "cancel"}) request.mapped("order_id").check_cancel() return True def _check_cancel_allocation(self): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) self.ensure_one() return ( self.allocation_ids and float_compare(self.qty_cancelled, 0, precision_digits=precision) > 0 ) def _prepare_procurement_values(self, group_id=False): """Prepare specific key for moves or other components that will be created from a procurement rule coming from a stock request. This method could be override in order to add other custom key that could be used in move/po creation. """ return { "date_planned": self.expected_date, "warehouse_id": self.warehouse_id, "stock_request_allocation_ids": self.id, "group_id": group_id or self.procurement_group_id.id or False, "route_ids": self.route_id, "stock_request_id": self.id, } def _skip_procurement(self): return self.state != "draft" or self.product_id.type not in ("consu", "product") def _action_launch_procurement_rule(self): """ Launch procurement group run method with required/custom fields genrated by a stock request. procurement group will launch '_run_move', '_run_buy' or '_run_manufacture' depending on the stock request product rule. """ precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) errors = [] for request in self: if request._skip_procurement(): continue qty = 0.0 for move in request.move_ids.filtered(lambda r: r.state != "cancel"): qty += move.product_qty if float_compare(qty, request.product_qty, precision_digits=precision) >= 0: continue values = request._prepare_procurement_values( group_id=request.procurement_group_id ) try: procurements = [] procurements.append( self.env["procurement.group"].Procurement( request.product_id, request.product_uom_qty, request.product_uom_id, request.location_id, request.name, request.name, self.env.company, values, ) ) self.env["procurement.group"].run(procurements) except UserError as error: errors.append(error.name) if errors: raise UserError("\n".join(errors)) return True def action_view_transfer(self): action = self.env["ir.actions.act_window"]._for_xml_id( "stock.action_picking_tree_all" ) pickings = self.mapped("picking_ids") if len(pickings) > 1: action["domain"] = [("id", "in", pickings.ids)] elif pickings: action["views"] = [(self.env.ref("stock.view_picking_form").id, "form")] action["res_id"] = pickings.id return action @api.model def create(self, vals): upd_vals = vals.copy() if upd_vals.get("name", "/") == "/": upd_vals["name"] = self.env["ir.sequence"].next_by_code("stock.request") if "order_id" in upd_vals: order_id = self.env["stock.request.order"].browse(upd_vals["order_id"]) upd_vals["expected_date"] = order_id.expected_date else: upd_vals["expected_date"] = self._get_expected_date() return super().create(upd_vals) def unlink(self): if self.filtered(lambda r: r.state != "draft"): raise UserError(_("Only requests on draft state can be unlinked")) return super(StockRequest, self).unlink()
36.10992
13,469
2,812
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class StockMove(models.Model): _inherit = "stock.move" allocation_ids = fields.One2many( comodel_name="stock.request.allocation", inverse_name="stock_move_id", string="Stock Request Allocation", ) stock_request_ids = fields.One2many( comodel_name="stock.request", string="Stock Requests", compute="_compute_stock_request_ids", ) @api.depends("allocation_ids") def _compute_stock_request_ids(self): for rec in self: rec.stock_request_ids = rec.allocation_ids.mapped("stock_request_id") def _merge_moves_fields(self): res = super(StockMove, self)._merge_moves_fields() res["allocation_ids"] = [(4, m.id) for m in self.mapped("allocation_ids")] return res @api.constrains("company_id") def _check_company_stock_request(self): if any( self.env["stock.request.allocation"].search( [ ("company_id", "!=", rec.company_id.id), ("stock_move_id", "=", rec.id), ], limit=1, ) for rec in self ): raise ValidationError( _( "The company of the stock request must match with " "that of the location." ) ) def copy_data(self, default=None): if not default: default = {} if "allocation_ids" not in default: default["allocation_ids"] = [] for alloc in self.allocation_ids: default["allocation_ids"].append( ( 0, 0, { "stock_request_id": alloc.stock_request_id.id, "requested_product_uom_qty": alloc.requested_product_uom_qty, }, ) ) return super(StockMove, self).copy_data(default) def _action_cancel(self): """Apply sudo to prevent requests ACL errors if the user does not have permissions (example: productions).""" res = super()._action_cancel() self.mapped("allocation_ids.stock_request_id").sudo().check_cancel() return res def _action_done(self, cancel_backorder=False): """Apply sudo to prevent requests ACL errors if the user does not have permissions (example: productions).""" res = super()._action_done(cancel_backorder=cancel_backorder) self.mapped("allocation_ids.stock_request_id").sudo().check_done() return res
34.292683
2,812
350
py
PYTHON
15.0
# Copyright 2018 ForgeFlow S.L. # (http://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class ResCompany(models.Model): _inherit = "res.company" stock_request_allow_virtual_loc = fields.Boolean( string="Allow Virtual locations on Stock Requests" )
25
350
1,343
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockPicking(models.Model): _inherit = "stock.picking" stock_request_ids = fields.One2many( comodel_name="stock.request", string="Stock Requests", compute="_compute_stock_request_ids", ) stock_request_count = fields.Integer( "Stock Request #", compute="_compute_stock_request_ids" ) @api.depends("move_lines") def _compute_stock_request_ids(self): for rec in self: rec.stock_request_ids = rec.move_lines.mapped("stock_request_ids") rec.stock_request_count = len(rec.stock_request_ids) def action_view_stock_request(self): """ :return dict: dictionary value for created view """ action = self.env["ir.actions.act_window"]._for_xml_id( "stock_request.action_stock_request_form" ) requests = self.mapped("stock_request_ids") if len(requests) > 1: action["domain"] = [("id", "in", requests.ids)] elif requests: action["views"] = [ (self.env.ref("stock_request.view_stock_request_form").id, "form") ] action["res_id"] = requests.id return action
32.756098
1,343
870
py
PYTHON
15.0
# Copyright 2018 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError class StockLocationRoute(models.Model): _inherit = "stock.location.route" @api.constrains("company_id") def _check_company_stock_request(self): if any( rec.company_id and self.env["stock.request"].search( [("company_id", "!=", rec.company_id.id), ("route_id", "=", rec.id)], limit=1, ) for rec in self ): raise ValidationError( _( "You cannot change the company of the route, as it is " "already assigned to stock requests that belong to " "another company." ) )
32.222222
870
1,085
py
PYTHON
15.0
# Copyright (C) 2019 Open Source Integrators # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import api, models class ProcurementGroup(models.Model): _inherit = "procurement.group" @api.model def run(self, procurements, raise_user_error=True): indexes_to_pop = [] new_procs = [] for i, procurement in enumerate(procurements): if "stock_request_id" in procurement.values and procurement.values.get( "stock_request_id" ): req = self.env["stock.request"].browse( procurement.values.get("stock_request_id") ) if req.order_id: new_procs.append(procurement._replace(origin=req.order_id.name)) indexes_to_pop.append(i) if new_procs: indexes_to_pop.reverse() for index in indexes_to_pop: procurements.pop(index) procurements.extend(new_procs) return super().run(procurements, raise_user_error=raise_user_error)
37.413793
1,085
1,048
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _get_stock_move_values( self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values, ): result = super(StockRule, self)._get_stock_move_values( product_id, product_qty, product_uom, location_id, name, origin, company_id, values, ) if values.get("stock_request_id", False): result["allocation_ids"] = [ ( 0, 0, { "stock_request_id": values.get("stock_request_id"), "requested_product_uom_qty": product_qty, }, ) ] return result
24.952381
1,048
1,234
py
PYTHON
15.0
# Copyright 2018 Creu Blanca # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" group_stock_request_order = fields.Boolean( implied_group="stock_request.group_stock_request_order" ) module_stock_request_purchase = fields.Boolean( string="Stock Requests for Purchases" ) module_stock_request_kanban = fields.Boolean( string="Stock Requests Kanban integration" ) stock_request_allow_virtual_loc = fields.Boolean( related="company_id.stock_request_allow_virtual_loc", readonly=False ) module_stock_request_analytic = fields.Boolean( string="Stock Requests Analytic integration" ) module_stock_request_submit = fields.Boolean( string="Submitted state in Stock Requests" ) module_stock_request_mrp = fields.Boolean(string="Stock Request for Manufacturing") # Dependencies @api.onchange("stock_request_allow_virtual_loc") def _onchange_stock_request_allow_virtual_loc(self): if self.stock_request_allow_virtual_loc: self.group_stock_multi_locations = True
30.85
1,234
9,501
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class StockRequest(models.AbstractModel): _name = "stock.request.abstract" _description = "Stock Request Template" _inherit = ["mail.thread", "mail.activity.mixin"] @api.model def default_get(self, fields): res = super(StockRequest, self).default_get(fields) warehouse = None if "warehouse_id" not in res and res.get("company_id"): warehouse = self.env["stock.warehouse"].search( [("company_id", "=", res["company_id"])], limit=1 ) if warehouse: res["warehouse_id"] = warehouse.id res["location_id"] = warehouse.lot_stock_id.id return res @api.depends( "product_id", "product_uom_id", "product_uom_qty", "product_id.product_tmpl_id.uom_id", ) def _compute_product_qty(self): for rec in self: rec.product_qty = rec.product_uom_id._compute_quantity( rec.product_uom_qty, rec.product_id.product_tmpl_id.uom_id ) name = fields.Char(copy=False, required=True, readonly=True, default="/") warehouse_id = fields.Many2one( comodel_name="stock.warehouse", string="Warehouse", check_company=True, ondelete="cascade", required=True, ) location_id = fields.Many2one( comodel_name="stock.location", string="Location", domain="not allow_virtual_location and " "[('usage', 'in', ['internal', 'transit'])] or []", ondelete="cascade", required=True, ) product_id = fields.Many2one( "product.product", "Product", domain=[("type", "in", ["product", "consu"])], ondelete="cascade", required=True, ) allow_virtual_location = fields.Boolean( related="company_id.stock_request_allow_virtual_loc", readonly=True ) allowed_uom_categ_id = fields.Many2one(related="product_id.uom_id.category_id") product_uom_id = fields.Many2one( comodel_name="uom.uom", string="Product Unit of Measure", domain="[('category_id', '=?', allowed_uom_categ_id)]", required=True, default=lambda self: self._context.get("product_uom_id", False), ) product_uom_qty = fields.Float( "Quantity", digits="Product Unit of Measure", required=True, help="Quantity, specified in the unit of measure indicated in the request.", ) product_qty = fields.Float( "Real Quantity", compute="_compute_product_qty", store=True, copy=False, digits="Product Unit of Measure", help="Quantity in the default UoM of the product", ) procurement_group_id = fields.Many2one( "procurement.group", "Procurement Group", help="Moves created through this stock request will be put in this " "procurement group. If none is given, the moves generated by " "procurement rules will be grouped into one big picking.", ) company_id = fields.Many2one( "res.company", "Company", required=True, default=lambda self: self.env.company ) route_id = fields.Many2one( "stock.location.route", string="Route", domain="[('id', 'in', route_ids)]", ondelete="restrict", ) route_ids = fields.Many2many( "stock.location.route", string="Routes", compute="_compute_route_ids", readonly=True, ) _sql_constraints = [ ("name_uniq", "unique(name, company_id)", "Name must be unique") ] @api.depends("product_id", "warehouse_id", "location_id") def _compute_route_ids(self): route_obj = self.env["stock.location.route"] routes = route_obj.search( [("warehouse_ids", "in", self.mapped("warehouse_id").ids)] ) routes_by_warehouse = {} for route in routes: for warehouse in route.warehouse_ids: routes_by_warehouse.setdefault( warehouse.id, self.env["stock.location.route"] ) routes_by_warehouse[warehouse.id] |= route for record in self: routes = route_obj if record.product_id: routes += record.product_id.mapped( "route_ids" ) | record.product_id.mapped("categ_id").mapped("total_route_ids") if record.warehouse_id and routes_by_warehouse.get(record.warehouse_id.id): routes |= routes_by_warehouse[record.warehouse_id.id] parents = record.get_parents().ids record.route_ids = routes.filtered( lambda r: any(p.location_id.id in parents for p in r.rule_ids) ) def get_parents(self): location = self.location_id result = location while location.location_id: location = location.location_id result |= location return result @api.constrains( "company_id", "product_id", "warehouse_id", "location_id", "route_id" ) def _check_company_constrains(self): """Check if the related models have the same company""" for rec in self: if ( rec.product_id.company_id and rec.product_id.company_id != rec.company_id ): raise ValidationError( _( "You have entered a product that is assigned " "to another company." ) ) if ( rec.location_id.company_id and rec.location_id.company_id != rec.company_id ): raise ValidationError( _( "You have entered a location that is " "assigned to another company." ) ) if rec.warehouse_id.company_id != rec.company_id: raise ValidationError( _( "You have entered a warehouse that is " "assigned to another company." ) ) if ( rec.route_id and rec.route_id.company_id and rec.route_id.company_id != rec.company_id ): raise ValidationError( _( "You have entered a route that is " "assigned to another company." ) ) @api.constrains("product_id") def _check_product_uom(self): """Check if the UoM has the same category as the product standard UoM""" if any( request.product_id.uom_id.category_id != request.product_uom_id.category_id for request in self ): raise ValidationError( _( "You have to select a product unit of measure in the " "same category than the default unit " "of measure of the product" ) ) @api.constrains("product_qty") def _check_qty(self): for rec in self: if rec.product_qty <= 0: raise ValidationError( _("Stock Request product quantity has to be strictly positive.") ) @api.onchange("warehouse_id") def onchange_warehouse_id(self): """Finds location id for changed warehouse.""" if self._name == "stock.request" and self.order_id: # When the stock request is created from an order the wh and # location are taken from the order and we rely on it to change # all request associated. Thus, no need to apply # the onchange, as it could lead to inconsistencies. return if self.warehouse_id: loc_wh = self.location_id.warehouse_id if self.warehouse_id != loc_wh: self.location_id = self.warehouse_id.lot_stock_id.id if self.warehouse_id.company_id != self.company_id: self.company_id = self.warehouse_id.company_id @api.onchange("location_id") def onchange_location_id(self): if self.location_id: loc_wh = self.location_id.warehouse_id if loc_wh and self.warehouse_id != loc_wh: self.warehouse_id = loc_wh self.with_context(no_change_childs=True).onchange_warehouse_id() @api.onchange("company_id") def onchange_company_id(self): """Sets a default warehouse when the company is changed.""" if self.company_id and ( not self.warehouse_id or self.warehouse_id.company_id != self.company_id ): self.warehouse_id = self.env["stock.warehouse"].search( [ "|", ("company_id", "=", False), ("company_id", "=", self.company_id.id), ], limit=1, ) self.onchange_warehouse_id() @api.onchange("product_id") def onchange_product_id(self): if self.product_id: self.product_uom_id = self.product_id.uom_id
36.542308
9,501
506
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stock archive constraint", "version": "15.0.1.0.1", "license": "AGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "Tecnativa, Odoo Community Association (OCA)", "development_status": "Production/Stable", "category": "Warehouse", "depends": ["stock"], "installable": True, "maintainers": ["victoralmau"], }
33.6
504
7,691
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo.exceptions import ValidationError from odoo.tests.common import Form, TransactionCase class TestLocationArchiveConstraint(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env( context=dict(cls.env.context, test_stock_archive_constraint=True) ) cls.company = cls.env.ref("base.main_company") cls.product_1 = cls._create_product(cls, "Product 1") cls.product_2 = cls._create_product(cls, "Product 2") stock_location_stock = cls.env.ref("stock.stock_location_stock") cls.stock_location = cls._create_stock_location( cls, "%s (Copy)" % (stock_location_stock.name) ) cls.stock_location_child = cls._create_stock_location( cls, "%s (Child)" % (cls.stock_location.name) ) cls.stock_location_child.location_id = cls.stock_location def _create_product(self, name): product_form = Form(self.env["product.product"]) product_form.name = name product_form.detailed_type = "product" return product_form.save() def _create_stock_location(self, name): stock_location_form = Form(self.env["stock.location"]) stock_location_form.name = name stock_location_form.usage = self.env.ref("stock.stock_location_stock").usage return stock_location_form.save() def _create_stock_quant(self, location_id, product_id, qty): self.env["stock.quant"].create( { "company_id": self.company.id, "location_id": location_id.id, "product_id": product_id.id, "quantity": qty, } ) def _create_stock_move(self, location_id, location_dest_id, product_id, qty): stock_move_form = Form(self.env["stock.move"]) stock_move_form.name = product_id.display_name stock_move_form.location_id = location_id stock_move_form.location_dest_id = location_dest_id stock_move_form.product_id = product_id stock_move_form.product_uom_qty = qty stock_move = stock_move_form.save() stock_move._action_done() def _create_stock_move_line(self, location_id, location_dest_id, product_id, qty): self.env["stock.move.line"].create( { "company_id": self.company.id, "location_id": location_id.id, "location_dest_id": location_dest_id.id, "product_id": product_id.id, "product_uom_qty": qty, "product_uom_id": product_id.uom_id.id, "qty_done": qty, "state": "done", } ) def _create_stock_picking(self, location_id, location_dest_id, product_id, qty): stock_picking_form = Form(self.env["stock.picking"]) stock_picking_form.picking_type_id = self.env.ref("stock.picking_type_in") with stock_picking_form.move_ids_without_package.new() as line: line.product_id = product_id line.product_uom_qty = qty stock_picking = stock_picking_form.save() stock_picking.write( {"location_id": location_id.id, "location_dest_id": location_dest_id.id} ) stock_picking.action_confirm() for line in stock_picking.move_ids_without_package: line.quantity_done = line.product_uom_qty stock_picking.button_validate() def test_archive_product_ok(self): self.product_1.active = False self.assertFalse(self.product_1.active) self.product_2.active = False self.assertFalse(self.product_2.active) def test_archive_unarchive_product(self): self.product_1.active = False self.assertFalse(self.product_1.active) self.product_1.active = True self.assertTrue(self.product_1.active) def test_archive_product_with_stock_move_in(self): self._create_stock_move( self.env.ref("stock.stock_location_suppliers"), self.stock_location, self.product_2, 20.00, ) self.product_1.active = False self.assertFalse(self.product_1.active) with self.assertRaises(ValidationError): self.product_2.active = False def test_archive_product_with_stock_move_line_in(self): self._create_stock_move_line( self.env.ref("stock.stock_location_suppliers"), self.stock_location, self.product_2, 20.00, ) self.product_1.active = False self.assertFalse(self.product_1.active) with self.assertRaises(ValidationError): self.product_2.active = False def test_archive_product_with_stock_picking_in(self): self._create_stock_picking( self.env.ref("stock.stock_location_suppliers"), self.stock_location, self.product_2, 20.00, ) self.product_1.active = False self.assertFalse(self.product_1.active) with self.assertRaises(ValidationError): self.product_2.active = False def test_archive_product_with_stock_picking_in_out(self): self._create_stock_picking( self.env.ref("stock.stock_location_suppliers"), self.stock_location, self.product_2, 20.00, ) self._create_stock_picking( self.stock_location, self.env.ref("stock.stock_location_customers"), self.product_2, 20.00, ) self.product_1.active = False self.assertFalse(self.product_1.active) self.product_2.active = False self.assertFalse(self.product_2.active) def test_archive_product_stock_location(self): self._create_stock_quant(self.stock_location, self.product_2, 20.00) self.product_1.active = False self.assertFalse(self.product_1.active) with self.assertRaises(ValidationError): self.product_2.active = False def test_archive_product_stock_location_child(self): self._create_stock_quant(self.stock_location_child, self.product_2, 20.00) self.product_1.active = False self.assertFalse(self.product_1.active) with self.assertRaises(ValidationError): self.product_2.active = False def test_archive_unarchive_stock_location(self): self.stock_location.active = False self.assertFalse(self.stock_location.active) self.stock_location.active = True self.assertTrue(self.stock_location.active) def test_archive_stock_location_ok(self): self.stock_location.active = False self.assertFalse(self.stock_location.active) def test_archive_stock_location(self): self._create_stock_quant(self.stock_location, self.product_2, 20.00) with self.assertRaises(ValidationError): self.stock_location.with_context(do_not_check_quant=True).active = False def test_archive_unarchive_stock_location_child(self): self.stock_location_child.active = False self.assertFalse(self.stock_location_child.active) self.stock_location_child.active = True self.assertTrue(self.stock_location_child.active) def test_archive_stock_location_child(self): self._create_stock_quant(self.stock_location_child, self.product_2, 20.00) with self.assertRaises(ValidationError): self.stock_location.with_context(do_not_check_quant=True).active = False
40.046875
7,689
3,032
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError from odoo.tools import config class StockLocation(models.Model): _inherit = "stock.location" def _skip_check_archive_constraint_condition(self): return config["test_enable"] and not self.env.context.get( "test_stock_archive_constraint" ) @api.constrains("active") def _check_active_stock_archive_constraint_stock_quant(self): if self._skip_check_archive_constraint_condition(): return res = self.env["stock.quant"].search( [ "&", ("location_id.usage", "in", ("internal", "transit")), "|", ("location_id", "in", self.filtered(lambda x: not x.active).ids), ("location_id", "child_of", self.filtered(lambda x: not x.active).ids), ], limit=1, ) if res: raise ValidationError( _( "It is not possible to archive location '%(display_name)s' which has " "associated stock quantities." ) % {"display_name": res.display_name} ) @api.constrains("active") def _check_active_stock_archive_constraint_stock_move(self): if self._skip_check_archive_constraint_condition(): return res = self.env["stock.move"].search( [ "&", ("state", "not in", ("done", "cancel")), "|", ("location_id", "in", self.filtered(lambda x: not x.active).ids), ("location_id", "child_of", self.filtered(lambda x: not x.active).ids), ], limit=1, ) if res: raise ValidationError( _( "It is not possible to archive location '%(display_name)s' which has " "associated picking lines." ) % {"display_name": res.display_name} ) @api.constrains("active") def _check_active_stock_archive_constraint_stock_move_line(self): if self._skip_check_archive_constraint_condition(): return res = self.env["stock.move.line"].search( [ "&", ("state", "not in", ("done", "cancel")), "|", ("location_id", "in", self.filtered(lambda x: not x.active).ids), ("location_id", "child_of", self.filtered(lambda x: not x.active).ids), ], limit=1, ) if res: raise ValidationError( _( "It is not possible to archive location '%(display_name)s' which has " "associated stock reservations." ) % {"display_name": res.display_name} )
36.071429
3,030
378
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class ProductTemplate(models.Model): _inherit = "product.template" @api.constrains("active") def _check_active_stock_archive_constraint(self): self.product_variant_ids._check_active_stock_archive_constraint()
31.333333
376
2,712
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import ValidationError from odoo.tools import config class ProductProduct(models.Model): _inherit = "product.product" def _skip_check_archive_constraint_condition(self): return config["test_enable"] and not self.env.context.get( "test_stock_archive_constraint" ) @api.constrains("active") def _check_active_stock_archive_constraint_stock_quant(self): if self._skip_check_archive_constraint_condition(): return res = self.env["stock.quant"].search( [ ("location_id.usage", "in", ("internal", "transit")), ("product_id", "in", self.filtered(lambda x: not x.active).ids), ("quantity", "!=", 0.0), ], limit=1, ) if res: raise ValidationError( _( "It is not possible to archive product '%(display_name)s' which has " "associated stock quantities." ) % {"display_name": res.product_id.display_name} ) @api.constrains("active") def _check_active_stock_archive_constraint_stock_move(self): if self._skip_check_archive_constraint_condition(): return res = self.env["stock.move"].search( [ ("product_id", "in", self.filtered(lambda x: not x.active).ids), ("state", "not in", ("done", "cancel")), ], limit=1, ) if res: raise ValidationError( _( "It is not possible to archive product '%(display_name)s' which has " "associated picking lines." ) % {"display_name": res.product_id.display_name} ) @api.constrains("active") def _check_active_stock_archive_constraint_stock_move_line(self): if self._skip_check_archive_constraint_condition(): return res = self.env["stock.move.line"].search( [ ("product_id", "in", self.filtered(lambda x: not x.active).ids), ("state", "not in", ("done", "cancel")), ], limit=1, ) if res: raise ValidationError( _( "It is not possible to archive product '%(display_name)s' which has " "associated stock reservations." ) % {"display_name": res.product_id.display_name} )
35.657895
2,710
561
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) { "name": "Stock Location Route Description", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "summary": "Add description field on stock routes.", "category": "Stock Management", "depends": ["stock"], "data": ["views/stock_location_route_views.xml"], "installable": True, "license": "AGPL-3", }
37.4
561
942
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestStockLocationRouteDescription(TransactionCase): def setUp(self, *args, **kwargs): super(TestStockLocationRouteDescription, self).setUp(*args, **kwargs) self.model_stock_location_route = self.env["stock.location.route"] def test_display_name_stock_location_route(self): """ Test to display the name of the route with and without a context. """ route = self.model_stock_location_route.create( {"name": "Test Route", "description": "Test Description"} ) self.assertEqual(route.display_name, route.name) name_description = route.name + ": " + route.description route.with_context(show_description=True)._compute_display_name() self.assertEqual(route.display_name, name_description)
42.818182
942
713
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo import fields, models class StockLocationRoute(models.Model): _inherit = "stock.location.route" description = fields.Char(translate=True) def name_get(self): if self.env.context.get("show_description", False): result = [] for rec in self: name = "" if rec.description: name = rec.name + ": " + rec.description else: name = rec.name result.append((rec.id, name)) return result return super().name_get()
31
713
640
py
PYTHON
15.0
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Stock Orderpoint UoM", "summary": "Allows to create procurement orders in the UoM indicated in " "the orderpoint", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse Management", "depends": ["purchase_stock"], "data": ["views/stock_warehouse_orderpoint_view.xml"], "license": "AGPL-3", "installable": True, "application": False, }
40
640
5,379
py
PYTHON
15.0
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common from odoo.exceptions import ValidationError from odoo.tools import mute_logger class TestStockOrderpointProcureUom(common.TransactionCase): def setUp(self): super(TestStockOrderpointProcureUom, self).setUp() # Get required Model productObj = self.env["product.product"] self.purchase_model = self.env["purchase.order"] self.purchase_line_model = self.env["purchase.order.line"] self.warehouse = self.env.ref("stock.warehouse0") self.location_stock = self.env.ref("stock.stock_location_stock") self.uom_unit = self.env.ref("uom.product_uom_unit") self.uom_unit.rounding = 1 self.uom_dozen = self.env.ref("uom.product_uom_dozen") self.uom_dozen.rounding = 1 self.uom_kg = self.env.ref("uom.product_uom_kgm") self.productA = productObj.create( { "name": "product A", "standard_price": 1, "type": "product", "uom_id": self.uom_unit.id, "uom_po_id": self.uom_dozen.id, "default_code": "A", "variant_seller_ids": [ ( 0, 0, { "name": self.env.ref("base.res_partner_3").id, "delay": 3, "min_qty": 1, "price": 72, }, ) ], } ) def test_01_stock_orderpoint_procure_uom(self): orderpoint = self.env["stock.warehouse.orderpoint"].create( { "warehouse_id": self.warehouse.id, "location_id": self.location_stock.id, "product_id": self.productA.id, "product_max_qty": 24, "product_min_qty": 12, "product_uom": self.uom_unit.id, "procure_uom_id": self.uom_dozen.id, } ) self.env["procurement.group"].run_scheduler() # As per route configuration, it will create Purchase order purchase = self.purchase_model.search([("origin", "ilike", orderpoint.name)]) self.assertEqual(len(purchase), 1) purchase_line = self.purchase_line_model.search( [("orderpoint_id", "=", orderpoint.id), ("order_id", "=", purchase.id)] ) self.assertEqual(len(purchase_line), 1) self.assertEqual(purchase_line.product_id, self.productA) self.assertEqual(purchase_line.product_uom, self.uom_dozen) self.assertEqual(purchase_line.product_qty, 2) def test_02_stock_orderpoint_wrong_uom(self): with mute_logger("openerp.sql_db"): with self.assertRaises(ValidationError): self.env["stock.warehouse.orderpoint"].create( { "warehouse_id": self.warehouse.id, "location_id": self.location_stock.id, "product_id": self.productA.id, "product_max_qty": 24, "product_min_qty": 12, "procure_uom_id": self.uom_kg.id, } ) def test_03_regenerate_po(self): def _assert_purchase_generated(self, supplier, product): purchase = self.purchase_model.search([("partner_id", "=", supplier.id)]) self.assertEqual(len(purchase), 1) lines = purchase.order_line self.assertEqual(len(lines), 1) self.assertEqual(lines.product_id, product) self.assertEqual(lines.product_uom, self.uom_dozen) self.assertEqual(lines.product_qty, 9) return purchase supplier = self.env["res.partner"].create( {"name": "Brewery Inc", "is_company": True} ) product = self.env["product.product"].create( { "name": "Beer bottle", "standard_price": 1, "type": "product", "uom_id": self.uom_unit.id, "uom_po_id": self.uom_dozen.id, "seller_ids": [ ( 0, False, {"name": supplier.id, "delay": 1, "min_qty": 1, "price": 2}, ) ], } ) self.env["stock.warehouse.orderpoint"].create( { "warehouse_id": self.warehouse.id, "location_id": self.location_stock.id, "product_id": product.id, "product_max_qty": 100, "product_min_qty": 10, "qty_multiple": 10, "product_uom": self.uom_unit.id, "procure_uom_id": self.uom_dozen.id, } ) self.env["procurement.group"].run_scheduler() purchase1 = _assert_purchase_generated(self, supplier, product) purchase1.button_cancel() purchase1.unlink() self.env["procurement.group"].run_scheduler() _assert_purchase_generated(self, supplier, product)
37.880282
5,379
958
py
PYTHON
15.0
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, models from odoo.exceptions import UserError class ProductTemplate(models.Model): _inherit = "product.template" @api.constrains("uom_id") def _check_orderpoint_procure_uom(self): for rec in self: orderpoint = self.env["stock.warehouse.orderpoint"].search( [ ("procure_uom_id.category_id", "!=", rec.uom_id.category_id.id), ("product_id", "in", rec.product_variant_ids.ids), ], limit=1, ) if orderpoint: raise UserError( _( "At least one reordering rule for this product has a " "different Procurement unit of measure category." ) )
35.481481
958
2,080
py
PYTHON
15.0
# Copyright (C) 2018 - TODAY, Open Source Integrators # (http://www.opensourceintegrators.com) # Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, models class ProcurementGroup(models.Model): _inherit = "procurement.group" @api.model def run(self, procurements, raise_user_error=True): # 'Procurement' is a 'namedtuple', which is not editable. # The 'procurement' which needs to be edited is created new # and the previous one is deleted. Proc = self.env["procurement.group"].Procurement indexes_to_pop = [] new_procs = [] for i, procurement in enumerate(procurements): if "orderpoint_id" in procurement.values: orderpoint = procurement.values.get("orderpoint_id") if ( orderpoint.procure_uom_id and procurement.product_uom != orderpoint.procure_uom_id ): new_product_qty = procurement.product_uom._compute_quantity( procurement.product_qty, orderpoint.procure_uom_id ) new_product_uom = orderpoint.procure_uom_id new_procs.append( Proc( procurement.product_id, new_product_qty, new_product_uom, procurement.location_id, procurement.name, procurement.origin, procurement.company_id, procurement.values, ) ) indexes_to_pop.append(i) if new_procs: indexes_to_pop.reverse() for index in indexes_to_pop: procurements.pop(index) procurements.extend(new_procs) return super(ProcurementGroup, self).run(procurements, raise_user_error)
42.44898
2,080
997
py
PYTHON
15.0
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class Orderpoint(models.Model): _inherit = "stock.warehouse.orderpoint" procure_uom_id = fields.Many2one(comodel_name="uom.uom", string="Procurement UoM") @api.constrains("product_id", "procure_uom_id") def _check_procure_uom(self): if any( orderpoint.product_uom and orderpoint.procure_uom_id and orderpoint.product_uom.category_id != orderpoint.procure_uom_id.category_id for orderpoint in self ): raise ValidationError( _( "Error: The product default Unit of Measure and " "the procurement Unit of Measure must be in the " "same category." ) ) return True
34.37931
997
696
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Stock Request Analytic", "summary": "Internal request for stock", "version": "15.0.1.0.1", "license": "AGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "ForgeFlow, Odoo Community Association (OCA)", "category": "Analytic", "depends": ["stock_request", "stock_analytic"], "data": [ "security/ir.model.access.csv", "views/stock_request_views.xml", "views/stock_request_order_views.xml", "views/analytic_views.xml", ], "installable": True, }
34.8
696
7,816
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields from odoo.exceptions import UserError from odoo.tests import Form from odoo.tests.common import TransactionCase class TestStockRequestAnalytic(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Model cls.AccountAnalyticAccount = cls.env["account.analytic.account"] cls.AccountAnalyticTag = cls.env["account.analytic.tag"] cls.ProductProduct = cls.env["product.product"] cls.ResUsers = cls.env["res.users"] cls.StockRequest = cls.env["stock.request"] cls.StockRequestOrder = cls.env["stock.request.order"] cls.StockLocation = cls.env["stock.location"] cls.StockLocationRoute = cls.env["stock.location.route"] cls.StockRule = cls.env["stock.rule"] # Data cls.expected_date = fields.Datetime.now() cls.main_company = cls.env.ref("base.main_company") cls.company_2 = cls.env.ref("stock.res_company_1") cls.warehouse = cls.env.ref("stock.warehouse0") cls.stock_request_user_group = cls.env.ref( "stock_request.group_stock_request_user" ) cls.stock_request_manager_group = cls.env.ref( "stock_request.group_stock_request_manager" ) cls.analytic1 = cls.AccountAnalyticAccount.create({"name": "Analytic"}) cls.analytic2 = cls.AccountAnalyticAccount.create( {"name": "Analytic", "company_id": cls.company_2.id} ) cls.analytic3 = cls.AccountAnalyticAccount.create({"name": "Analytic 3"}) cls.demand_loc = cls.StockLocation.create( { "name": "demand_loc", "location_id": cls.warehouse.lot_stock_id.id, "usage": "internal", } ) cls.demand_route = cls.StockLocationRoute.create( { "name": "Transfer", "product_categ_selectable": False, "product_selectable": True, "company_id": cls.main_company.id, "sequence": 10, } ) cls.demand_rule = cls.StockRule.create( { "name": "Transfer", "route_id": cls.demand_route.id, "location_src_id": cls.warehouse.lot_stock_id.id, "location_id": cls.demand_loc.id, "action": "pull", "picking_type_id": cls.warehouse.int_type_id.id, "procure_method": "make_to_stock", "warehouse_id": cls.warehouse.id, "company_id": cls.main_company.id, } ) cls.product = cls.ProductProduct.create( { "name": "Test Product", "type": "product", "route_ids": [(6, 0, cls.demand_route.ids)], } ) def prepare_order_request_analytic(self, analytic, company, analytic_tags=None): analytic_tags = analytic_tags or self.AccountAnalyticTag vals = { "company_id": company.id, "warehouse_id": self.warehouse.id, "location_id": self.demand_loc.id, "expected_date": self.expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "analytic_account_id": analytic.id, "analytic_tag_ids": [(4, tag.id) for tag in analytic_tags], "company_id": company.id, "warehouse_id": self.warehouse.id, "location_id": self.demand_loc.id, "expected_date": self.expected_date, }, ) ], } return vals def prepare_order_request_multi_analytic(self, analytic1, analytic2, company): vals = { "company_id": company.id, "warehouse_id": self.warehouse.id, "location_id": self.demand_loc.id, "expected_date": self.expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "analytic_account_id": analytic1.id, "company_id": company.id, "warehouse_id": self.warehouse.id, "location_id": self.demand_loc.id, "expected_date": self.expected_date, }, ), ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "analytic_account_id": analytic2.id, "company_id": company.id, "warehouse_id": self.warehouse.id, "location_id": self.demand_loc.id, "expected_date": self.expected_date, }, ), ], } return vals def test_stock_analytic(self): analytic_tag = self.env.ref("analytic.tag_contract") vals = self.prepare_order_request_analytic( self.analytic1, self.main_company, analytic_tags=analytic_tag ) order = self.StockRequestOrder.create(vals) req = order.stock_request_ids order.action_confirm() self.assertEqual(req.move_ids.mapped("analytic_account_id"), self.analytic1) self.assertEqual(req.move_ids.mapped("analytic_tag_ids"), analytic_tag) self.assertEqual(order.analytic_count, 1) action = order.with_context( analytic_type="analytic_account" ).action_view_analytic() self.assertTrue(action["res_id"], self.analytic1.id) action2 = self.analytic1.action_view_stock_request() self.assertTrue(action2["res_id"], order.id) def test_stock_multi_analytic(self): vals = self.prepare_order_request_multi_analytic( self.analytic1, self.analytic3, self.main_company ) order = self.StockRequestOrder.create(vals) order.action_confirm() self.assertEqual(order.analytic_count, 2) def test_company(self): with self.assertRaises(UserError): vals = self.prepare_order_request_analytic( self.analytic2, self.main_company ) self.StockRequestOrder.create(vals) def test_default_analytic(self): """ Create request order with a default analytic """ vals = self.prepare_order_request_analytic( self.AccountAnalyticAccount.browse(), self.main_company ) vals.update( { "default_analytic_account_id": self.analytic1.id, } ) order = self.StockRequestOrder.create(vals) with Form(order) as order_form: with order_form.stock_request_ids.new() as line_form: line_form.product_id = self.product line_form.product_uom_qty = 5.0 self.assertEqual( order.default_analytic_account_id, order.stock_request_ids.mapped("analytic_account_id"), )
39.474747
7,816
2,806
py
PYTHON
15.0
# Copyright 2018 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError MAP_ACTIONS = { "analytic_account": "analytic.action_account_analytic_account_form", "analytic_tag": "analytic.account_analytic_tag_action", } MAP_FIELDS = { "analytic_account": "analytic_account_ids", "analytic_tag": "analytic_tag_ids", } MAP_VIEWS = { "analytic_account": "analytic.view_account_analytic_account_form", "analytic_tag": "analytic.account_analytic_tag_form_view", } class StockRequestOrder(models.Model): _inherit = "stock.request.order" analytic_count = fields.Integer( compute="_compute_analytic_ids", readonly=True, compute_sudo=True, ) analytic_tag_count = fields.Integer( compute="_compute_analytic_ids", readonly=True, compute_sudo=True, ) analytic_account_ids = fields.One2many( comodel_name="account.analytic.account", compute="_compute_analytic_ids", string="Analytic Accounts", readonly=True, compute_sudo=True, ) analytic_tag_ids = fields.One2many( comodel_name="account.analytic.tag", compute="_compute_analytic_ids", string="Analytic Tags", readonly=True, compute_sudo=True, ) default_analytic_account_id = fields.Many2one( comodel_name="account.analytic.account", string="Default Analytic Account", help="Set this if you want to define a default analytic account on requests", ) @api.depends("stock_request_ids") def _compute_analytic_ids(self): for req in self: req.analytic_account_ids = req.stock_request_ids.mapped( "analytic_account_id" ) req.analytic_tag_ids = req.stock_request_ids.mapped("analytic_tag_ids") req.analytic_count = len(req.analytic_account_ids) req.analytic_tag_count = len(req.analytic_tag_ids) def action_view_analytic(self): self.ensure_one() analytic_type = self.env.context.get("analytic_type") if not analytic_type: raise ValidationError( _("Analytic type (analytic_type) not present in the context") ) xmlid = MAP_ACTIONS[analytic_type] action = self.env["ir.actions.act_window"]._for_xml_id(xmlid) records = self.mapped(MAP_FIELDS[analytic_type]) if len(records) > 1: action["domain"] = [("id", "in", records.ids)] elif records: action["views"] = [ (self.env.ref(MAP_VIEWS[self._context["analytic_type"]]).id, "form") ] action["res_id"] = records.id return action
34.641975
2,806
1,418
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. (https://www.forgeflow.com) # Copyright 2021 Tecnativa - João Marques # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class StockRequest(models.Model): _inherit = "stock.request" _check_company_auto = True analytic_account_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic Account", compute="_compute_analytic_id", store=True, readonly=False, check_company=True, compute_sudo=True, ) analytic_tag_ids = fields.Many2many( comodel_name="account.analytic.tag", string="Analytic Tags", check_company=True, ) @api.depends("order_id") def _compute_analytic_id(self): """ Set default analytic account on lines from order if defined. """ for req in self: if req.order_id and req.order_id.default_analytic_account_id: req.analytic_account_id = req.order_id.default_analytic_account_id def _prepare_procurement_values(self, group_id=False): """ Add analytic account to procurement values """ res = super()._prepare_procurement_values(group_id=group_id) if self.analytic_account_id: res.update({"analytic_account_id": self.analytic_account_id.id}) return res
32.953488
1,417
1,111
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class ProcurementRule(models.Model): _inherit = "stock.rule" def _get_stock_move_values( self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values, ): res = super()._get_stock_move_values( product_id, product_qty, product_uom, location_id, name, origin, company_id, values, ) if values.get("stock_request_id"): stock_request = self.env["stock.request"].browse(values["stock_request_id"]) analytic_account = stock_request.analytic_account_id analytic_tags = stock_request.analytic_tag_ids res.update( analytic_account_id=analytic_account.id, analytic_tag_ids=[(4, tag.id) for tag in analytic_tags], ) return res
28.487179
1,111
995
py
PYTHON
15.0
# Copyright 2017-2020 ForgeFlow, S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountAnalyticAccount(models.Model): _inherit = "account.analytic.account" stock_request_ids = fields.One2many( comodel_name="stock.request", inverse_name="analytic_account_id", string="Stock Requests", copy=False, ) def action_view_stock_request(self): self.ensure_one() xmlid = "stock_request.action_stock_request_form" action = self.env["ir.actions.act_window"]._for_xml_id(xmlid) requests = self.mapped("stock_request_ids") if len(requests) > 1: action["domain"] = [("id", "in", requests.ids)] elif requests: action["views"] = [ (self.env.ref("stock_request.view_stock_request_form").id, "form") ] action["res_id"] = requests.id return action
34.310345
995
691
py
PYTHON
15.0
# Copyright 2012-2016 Camptocamp SA # Copyright 2019 Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Order point generator", "summary": "Mass configuration of stock order points", "version": "15.0.1.0.1", "author": "Camptocamp, Tecnativa, Odoo Community Association (OCA)", "category": "Warehouse", "license": "AGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "depends": ["stock"], "data": [ "views/orderpoint_template_views.xml", "wizard/orderpoint_generator_view.xml", "data/ir_cron.xml", "security/ir.model.access.csv", ], "installable": True, }
32.904762
691
17,062
py
PYTHON
15.0
# Copyright 2016 Cyril Gaudin (Camptocamp) # Copyright 2019 David Vidal - Tecnativa # Copyright 2020 Víctor Martínez - Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models from odoo.exceptions import UserError from odoo.tests import Form, TransactionCase class TestOrderpointGenerator(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.wizard_model = cls.env["stock.warehouse.orderpoint.generator"] cls.orderpoint_model = cls.env["stock.warehouse.orderpoint"] cls.orderpoint_template_model = cls.env["stock.warehouse.orderpoint.template"] cls.product_model = cls.env["product.product"] cls.attr = cls.env["product.attribute"].create({"name": "Size"}) cls.attr_value_a = cls.env["product.attribute.value"].create( {"name": "A", "attribute_id": cls.attr.id} ) cls.attr_value_b = cls.env["product.attribute.value"].create( {"name": "B", "attribute_id": cls.attr.id} ) cls.p1 = cls.product_model.create({"name": "Unittest P1", "type": "product"}) cls.p2 = cls.product_model.create({"name": "Unittest P2", "type": "product"}) cls.wh1 = cls.env["stock.warehouse"].create( {"name": "TEST WH1", "code": "TST1"} ) location_obj = cls.env["stock.location"] cls.supplier_loc = location_obj.create( {"name": "Test supplier location", "usage": "supplier"} ) cls.customer_loc = location_obj.create( {"name": "Test customer location", "usage": "customer"} ) cls.orderpoint_fields_dict = { "warehouse_id": cls.wh1.id, "location_id": cls.wh1.lot_stock_id.id, "name": "TEST-ORDERPOINT-001", "product_max_qty": 15.0, "product_min_qty": 5.0, "qty_multiple": 1, } cls.template = cls.orderpoint_template_model.create(cls.orderpoint_fields_dict) # Create some moves for p1 and p2 so we can have a history to test # p1 [100, 50, 45, 55, 52] # t1 - p1 - stock.move location1 100 # 100 cls.p1m1 = cls.env["stock.move"].create( { "name": cls.p1.name, "product_id": cls.p1.id, "product_uom_qty": 100, "product_uom": cls.p1.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "state": "done", "date": "2019-01-01 01:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p1m1.id, "product_id": cls.p1.id, "qty_done": 100, "product_uom_id": cls.p1.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "state": "done", "date": "2019-01-01 01:00:00", } ) # t2 - p1 - stock.move location1 -50 # 50 cls.p1m2 = cls.p1m1.copy( { "product_uom_qty": 50, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 02:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p1m2.id, "product_id": cls.p1.id, "qty_done": 50, "product_uom_id": cls.p1.uom_id.id, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 02:00:00", } ) # t3 - p1 - stock.move location1 -5 # 45 cls.p1m3 = cls.p1m1.copy( { "name": cls.p1.name, "product_id": cls.p1.id, "product_uom_qty": 5, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 03:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p1m3.id, "product_id": cls.p1.id, "qty_done": 5, "product_uom_id": cls.p1.uom_id.id, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 03:00:00", } ) # t4 - p1 - stock.move location1 10 # 55 cls.p1m4 = cls.p1m1.copy( { "product_uom_qty": 10, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "state": "done", "date": "2019-01-01 04:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p1m4.id, "product_id": cls.p1.id, "qty_done": 10, "product_uom_id": cls.p1.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "state": "done", "date": "2019-01-01 04:00:00", } ) # t5 - p1 - stock.move location1 -3 # 52 cls.p1m5 = cls.p1m1.copy( { "product_uom_qty": 3, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 05:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p1m5.id, "product_id": cls.p1.id, "qty_done": 3, "product_uom_id": cls.p1.uom_id.id, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 05:00:00", } ) # p2 # t1 - p2 - stock.move location1 1000 # 1000 cls.p2m1 = cls.env["stock.move"].create( { "name": cls.p2.name, "product_id": cls.p2.id, "product_uom": cls.p2.uom_id.id, "product_uom_qty": 1000, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "state": "done", "date": "2019-01-01 01:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p2m1.id, "product_id": cls.p2.id, "qty_done": 1000, "product_uom_id": cls.p2.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "state": "done", "date": "2019-01-01 01:00:00", } ) # t2 - p2 - stock.move location1 -50 # 950 cls.p2m2 = cls.p2m1.copy( { "product_uom_qty": 50, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 02:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p2m2.id, "product_id": cls.p2.id, "qty_done": 50, "product_uom_id": cls.p2.uom_id.id, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 02:00:00", } ) # t3 - p2 - stock.move location1 -7 # 943 cls.p2m3 = cls.p2m1.copy( { "product_uom_qty": 7, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 03:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p2m3.id, "product_id": cls.p2.id, "qty_done": 7, "product_uom_id": cls.p2.uom_id.id, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 03:00:00", } ) # t4 - p2 - stock.move location1 100 # 1043 cls.p2m4 = cls.p2m1.copy( { "product_uom_qty": 100, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "state": "done", "date": "2019-01-01 04:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p2m4.id, "product_id": cls.p2.id, "qty_done": 100, "product_uom_id": cls.p2.uom_id.id, "location_id": cls.supplier_loc.id, "location_dest_id": cls.wh1.lot_stock_id.id, "state": "done", "date": "2019-01-01 04:00:00", } ) # t5 - p2 - stock.move location1 -3 # 1040 cls.p2m5 = cls.p2m1.copy( { "product_uom_qty": 3, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 05:00:00", } ) cls.env["stock.move.line"].create( { "move_id": cls.p2m5.id, "product_id": cls.p2.id, "qty_done": 3, "product_uom_id": cls.p2.uom_id.id, "location_id": cls.wh1.lot_stock_id.id, "location_dest_id": cls.customer_loc.id, "state": "done", "date": "2019-01-01 05:00:00", } ) def check_orderpoint(self, products, template, fields_dict): orderpoints = self.orderpoint_model.search( [("name", "=", template.name)], order="product_id" ) self.assertEqual(len(products), len(orderpoints)) for i, product in enumerate(products): self.assertEqual(product, orderpoints[i].product_id) for orderpoint in orderpoints: for field in fields_dict.keys(): op_field_value = orderpoint[field] if isinstance(orderpoint[field], models.Model): op_field_value = orderpoint[field].id self.assertEqual(op_field_value, fields_dict[field]) return orderpoints def wizard_over_products(self, product, template): return self.wizard_model.with_context( active_model=product._name, active_ids=product.ids, ).create({"orderpoint_template_id": [(6, 0, template.ids)]}) def test_product_orderpoint(self): products = self.p1 + self.p2 wizard = self.wizard_over_products(products, self.template) wizard.action_configure() self.check_orderpoint(products, self.template, self.orderpoint_fields_dict) def test_template_orderpoint(self): prod_tmpl = self.p1.product_tmpl_id + self.p2.product_tmpl_id wizard = self.wizard_over_products(prod_tmpl, self.template) wizard.action_configure() products = self.p1 + self.p2 self.check_orderpoint(products, self.template, self.orderpoint_fields_dict) def test_template_variants_orderpoint(self): product_form = Form(self.p1.product_tmpl_id) with product_form.attribute_line_ids.new() as attribute: attribute.attribute_id = self.attr attribute.value_ids.add(self.attr_value_a) attribute.value_ids.add(self.attr_value_b) product_form.save() wizard = self.wizard_over_products(self.p1.product_tmpl_id, self.template) with self.assertRaises(UserError): wizard.action_configure() def test_auto_qty(self): """Compute min and max qty according to criteria""" # Max stock for p1: 100 self.template.write( { "auto_min_qty": True, "auto_min_date_start": "2019-01-01 01:30:00", "auto_min_date_end": "2019-02-01 00:00:00", "auto_min_qty_criteria": "max", } ) wizard = self.wizard_over_products(self.p1, self.template) wizard.action_configure() orderpoint_auto_dict = self.orderpoint_fields_dict.copy() orderpoint_auto_dict.update({"product_min_qty": 100.0}) self.check_orderpoint(self.p1, self.template, orderpoint_auto_dict) # Min stock for p1: 45 self.template.write({"auto_min_qty_criteria": "min"}) wizard = self.wizard_over_products(self.p1, self.template) wizard.action_configure() orderpoint_auto_dict.update({"product_min_qty": 45.0}) self.check_orderpoint(self.p1, self.template, orderpoint_auto_dict) # Median of stock for p1: 52 self.template.write({"auto_min_qty_criteria": "median"}) wizard = self.wizard_over_products(self.p1, self.template) wizard.action_configure() orderpoint_auto_dict.update({"product_min_qty": 52.0}) self.check_orderpoint(self.p1, self.template, orderpoint_auto_dict) # Average of stock for p1: 60.4 self.template.write({"auto_min_qty_criteria": "avg"}) wizard = self.wizard_over_products(self.p1, self.template) wizard.action_configure() orderpoint_auto_dict.update({"product_min_qty": 60.4}) self.check_orderpoint(self.p1, self.template, orderpoint_auto_dict) # Set auto values for min and max: 60.4 (avg) 100 (max) self.template.write( { "auto_max_qty": True, "auto_max_date_start": "2019-01-01 00:00:00", "auto_max_date_end": "2019-02-01 00:00:00", "auto_max_qty_criteria": "max", } ) wizard = self.wizard_over_products(self.p1, self.template) wizard.action_configure() orderpoint_auto_dict.update({"product_max_qty": 100}) self.check_orderpoint(self.p1, self.template, orderpoint_auto_dict) # If they have the same values, only one is computed: self.template.write({"auto_min_qty_criteria": "max"}) wizard = self.wizard_over_products(self.p1, self.template) wizard.action_configure() orderpoint_auto_dict.update({"product_min_qty": 100}) self.check_orderpoint(self.p1, self.template, orderpoint_auto_dict) # Auto min max over a shorter period self.template.write( { "auto_max_date_start": "2019-01-01 02:30:00", "auto_max_date_end": "2019-01-01 03:00:00", "auto_min_date_start": "2019-01-01 04:00:00", "auto_min_date_end": "2019-01-01 06:00:00", } ) wizard = self.wizard_over_products(self.p1, self.template) wizard.action_configure() orderpoint_auto_dict.update({"product_min_qty": 55, "product_max_qty": 50}) self.check_orderpoint(self.p1, self.template, orderpoint_auto_dict) # Check delivered self.template.auto_min_qty_criteria = "delivered" self.template.auto_max_qty_criteria = "delivered" wizard = self.wizard_over_products(self.p1, self.template) wizard.action_configure() orderpoint_auto_dict.update({"product_min_qty": 3, "product_max_qty": 5}) self.check_orderpoint(self.p1, self.template, orderpoint_auto_dict) def test_auto_qty_multi_products(self): """Each product has a different history""" products = self.p1 + self.p2 self.template.write( { "auto_min_qty": True, "auto_min_date_start": "2019-01-01 00:00:00", "auto_min_date_end": "2019-02-01 00:00:00", "auto_min_qty_criteria": "max", } ) wizard = self.wizard_over_products(products, self.template) wizard.action_configure() orderpoint_auto_dict = self.orderpoint_fields_dict.copy() del orderpoint_auto_dict["product_min_qty"] orderpoints = self.check_orderpoint( products, self.template, orderpoint_auto_dict ) self.assertEqual(orderpoints[0].product_min_qty, 100) self.assertEqual(orderpoints[1].product_min_qty, 1043)
41.009615
17,060
1,567
py
PYTHON
15.0
# Copyright 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, fields, models from odoo.exceptions import UserError _template_register = ["orderpoint_template_id"] class OrderpointGenerator(models.TransientModel): """Wizard defining stock.warehouse.orderpoint configurations for selected products. Those configs are generated using templates """ _name = "stock.warehouse.orderpoint.generator" _description = "Orderpoint Generator" orderpoint_template_id = fields.Many2many( comodel_name="stock.warehouse.orderpoint.template", relation="order_point_generator_rel", string="Reordering Rule Templates", ) def action_configure(self): """Action to retrieve wizard data and launch creation of items.""" self.ensure_one() model_obj = self.env[self.env.context.get("active_model")] record_ids = model_obj.browse(self.env.context.get("active_ids")) if not record_ids: return model_obj if self.env.context.get("active_model") == "product.template": product_ids = record_ids.mapped("product_variant_ids") if len(product_ids) != len(record_ids): raise UserError( _( "Cannot apply because some of selected " "products has multiple variants." ) ) record_ids = product_ids self.orderpoint_template_id.create_orderpoints(record_ids)
37.309524
1,567
6,871
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # Copyright 2019 David Vidal - Tecnativa # Copyright 2020 Víctor Martínez - Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from collections import OrderedDict from datetime import timedelta from odoo import api, fields, models class ProductProduct(models.Model): _inherit = "product.product" auto_orderpoint_template_ids = fields.Many2many( comodel_name="stock.warehouse.orderpoint.template", string="Automatic Reordering Rules", domain=[("auto_generate", "=", True)], help="When one or several automatic reordering rule is selected, " "a Scheduled Action will automatically generate or update " "the reordering rules of the product.", ) @api.model def create(self, vals): record = super().create(vals) if vals.get("auto_orderpoint_template_ids"): record.auto_orderpoint_template_ids.create_orderpoints(record) return record def write(self, vals): result = super().write(vals) if vals.get("auto_orderpoint_template_ids"): self.auto_orderpoint_template_ids.create_orderpoints(self) return result def _get_stock_move_domain(self, domain_move=False, from_date=False, to_date=False): domain = [("product_id", "in", self.ids), ("state", "=", "done")] + domain_move if from_date: domain += [("date", ">=", from_date)] domain += [("date", "<=", to_date)] return domain def _set_product_moves_dict( self, moves=False, location=False, from_date=False, to_date=False ): # Obtain a dict with the stock snapshot for the relative date_from # otherwise, the first move will counted as first stock value. We # default the compute the stock value anyway to default the value # for products with no moves for the given period initial_stock = {} # Compute the second before the given date so we don't duplicate # history values in case the given hour is the same than the one # of the first move from_date_stock = from_date - timedelta(seconds=1) to_date_stock = to_date + timedelta(seconds=1) initial_stock = self.with_context(location=location)._compute_quantities_dict( False, False, False, to_date=from_date_stock or to_date_stock ) product_moves_dict = {} for move in moves: product_moves_dict.setdefault(move["product_id"][0], {}) product_moves_dict[move["product_id"][0]].update( {move["date"]: {"prod_qty": move["product_qty"]}} ) for product in self.with_context(prefetch_fields=False): # If no there are no moves for a product we default the stock # to the one for the given period nevermind the dates product_moves = product_moves_dict.get(product.id) prod_initial_stock = initial_stock.get(product.id, {}) if not product_moves: product_moves_dict[product.id] = { to_date: { "prod_qty": 0, "stock": prod_initial_stock.get("qty_available", 0), }, "stock_history": [prod_initial_stock.get("qty_available", 0)], } continue # Now we'll sort the moves by date and assign an initial stock so # we can compute the stock historical values from the moves # sequence so we can exploit it statisticaly product_moves = OrderedDict(sorted(product_moves.items())) product_moves_dict[product.id]["stock_history"] = [ prod_initial_stock.get("qty_available", 0) ] stock = 0 first_item = product_moves[next(iter(product_moves))] if from_date: stock = prod_initial_stock.get("qty_available") first_item["stock"] = stock + first_item["prod_qty"] stock = first_item["stock"] iter_moves = iter(product_moves) next(iter_moves, None) for date in iter_moves: stock += product_moves[date]["prod_qty"] product_moves[date]["stock"] = stock product_moves_dict[product.id]["stock_history"] += [ v["stock"] for k, v in product_moves.items() ] return product_moves_dict def _get_delivered_to_customer_dict( self, location=False, from_date=False, to_date=False ): """Returns a dict of products with their delivered qtys for the given dates and locations """ domain = [ ("product_id", "in", self.ids), ("state", "=", "done"), ("location_dest_id.usage", "=", "customer"), ] if location: domain += [("location_id", "child_of", location.id)] if from_date: domain += [("date", ">=", from_date)] if to_date: domain += [("date", "<=", to_date)] move_lines = self.env["stock.move.line"].read_group( domain, ["product_id", "qty_done"], ["product_id"] ) return {p["product_id"][0]: p["qty_done"] for p in move_lines} def _compute_historic_quantities_dict( self, location_id=False, from_date=False, to_date=False ): """Returns a dict of products with a dict of historic moves as for a list of historic stock values resulting from those moves. If a location_id is passed, we can restrict it to such location""" location = location_id and location_id.id domain_quant_loc, domain_move_in_loc, domain_move_out_loc = self.with_context( location=location )._get_domain_locations() if not to_date: to_date = fields.Datetime.now() domain_move_in = self._get_stock_move_domain( domain_move_in_loc, from_date, to_date ) domain_move_out = self._get_stock_move_domain( domain_move_out_loc, from_date, to_date ) move_obj = self.env["stock.move"] # Positive moves moves_in = move_obj.search_read( domain_move_in, ["product_id", "product_qty", "date"], order="date asc" ) # We'll convert to negative these quantities to operate with them # to obtain the stock snapshot in every moment moves_out = move_obj.search_read( domain_move_out, ["product_id", "product_qty", "date"], order="date asc" ) for move in moves_out: move["product_qty"] *= -1 # Merge both results and group them by product id as key moves = moves_in + moves_out return self._set_product_moves_dict(moves, location, from_date, to_date)
43.751592
6,869
8,235
py
PYTHON
15.0
# Copyright 2012-2016 Camptocamp SA # Copyright 2019 David Vidal - Tecnativa # Copyright 2020 Víctor Martínez - Tecnativa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from statistics import mean, median_high from odoo import api, fields, models class OrderpointTemplate(models.Model): """Template for orderpoints Here we use same model as stock.warehouse.orderpoint but set product_id as non mandatory as we cannot remove it. This field will be ignored. This has the advantage of ensuring that the order point and the order point template have the same fields. _table is redefined to separate templates from orderpoints """ _name = "stock.warehouse.orderpoint.template" _description = "Reordering Rule Templates" _inherit = "stock.warehouse.orderpoint" _table = "stock_warehouse_orderpoint_template" name = fields.Char(copy=True) group_id = fields.Many2one(copy=True) product_id = fields.Many2one(required=False) product_uom = fields.Many2one(required=False) product_min_qty = fields.Float(required=False) product_max_qty = fields.Float(required=False) auto_min_qty = fields.Boolean( string="Auto Minimum", help="Auto compute minimum quantity per product for a given a date range", ) auto_min_date_start = fields.Datetime() auto_min_date_end = fields.Datetime() auto_min_qty_criteria = fields.Selection( selection=[ ("max", "Maximum"), ("median", "Most frequent"), ("avg", "Average"), ("min", "Minimum"), ("delivered", "Delivered"), ], default="max", help="Select a criteria to auto compute the minimum", ) auto_max_qty = fields.Boolean( string="Auto Maximum", help="Auto compute maximum quantity per product for a given a date range", ) auto_max_qty_criteria = fields.Selection( selection=[ ("max", "Maximum"), ("median", "Most frequent"), ("avg", "Average"), ("min", "Minimum"), ("delivered", "Delivered"), ], help="Select a criteria to auto compute the maximum", ) auto_max_date_start = fields.Datetime() auto_max_date_end = fields.Datetime() auto_generate = fields.Boolean( string="Create Rules Automatically", help="When checked, the 'Reordering Rule Templates Generator' " "scheduled action will automatically update the rules of a " "selection of products.", ) auto_product_ids = fields.Many2many( comodel_name="product.product", string="Products", help="A reordering rule will be automatically created by the " "scheduled action for every product in this list.", ) auto_last_generation = fields.Datetime(string="Last Automatic Generation") # Disable stock.warehouse.orderpoint which are useless for the template qty_forecast = fields.Float(compute=False, store=False) product_category_id = fields.Many2one(related=False, store=False) def _template_fields_to_discard(self): """In order to create every orderpoint we should pop this template customization fields""" return [ "auto_generate", "auto_product_ids", "auto_last_generation", "auto_min_qty", "auto_min_date_start", "auto_min_qty_criteria", "auto_min_date_end", "auto_max_date_start", "auto_max_date_end", "auto_max_qty_criteria", "auto_max_qty", ] def _remove_old_instances(self, products): """Clean old instance by setting those inactives""" self.env["stock.warehouse.orderpoint"].search( [ ("product_id", "in", products.ids), ("location_id", "=", self.location_id.id), ("company_id", "=", self.company_id.id), ] ).unlink() @api.model def _get_criteria_methods(self): """Allows to extend methods with other statistical aproaches""" return { "max": max, "median": median_high, "avg": mean, "min": min, } @api.model def _get_product_qty_by_criteria( self, products, location_id, from_date, to_date, criteria ): """Returns a dict with product ids as keys and the resulting calculation of historic moves according to criteria. If the creteria is delivered we just search how many items were delivered in the given period of time""" if criteria == "delivered": return products._get_delivered_to_customer_dict( location_id, from_date, to_date ) stock_qty_history = products._compute_historic_quantities_dict( location_id=location_id, from_date=from_date, to_date=to_date ) criteria_methods = self._get_criteria_methods() return { x: criteria_methods[criteria](y["stock_history"]) for x, y in stock_qty_history.items() } def _create_instances(self, product_ids): """Create instances of model using template inherited model and compute autovalues if needed""" orderpoint_model = self.env["stock.warehouse.orderpoint"] for record in self: # Flag equality so we compute the values just once auto_same_values = ( (record.auto_max_date_start == record.auto_min_date_start) and (record.auto_max_date_end == record.auto_max_date_end) and (record.auto_max_qty_criteria == record.auto_min_qty_criteria) ) stock_min_qty = stock_max_qty = {} if record.auto_min_qty: stock_min_qty = self._get_product_qty_by_criteria( product_ids, location_id=record.location_id, from_date=record.auto_min_date_start, to_date=record.auto_min_date_end, criteria=record.auto_min_qty_criteria, ) if auto_same_values: stock_max_qty = stock_min_qty if record.auto_max_qty and not stock_max_qty: stock_max_qty = self._get_product_qty_by_criteria( product_ids, location_id=record.location_id, from_date=record.auto_max_date_start, to_date=record.auto_max_date_end, criteria=record.auto_max_qty_criteria, ) vals_list = [] for data in record.copy_data(): for discard_field in self._template_fields_to_discard(): data.pop(discard_field) for product_id in product_ids: vals = data.copy() vals["product_id"] = product_id.id if record.auto_min_qty: vals["product_min_qty"] = stock_min_qty.get(product_id.id, 0) if record.auto_max_qty: vals["product_max_qty"] = stock_max_qty.get(product_id.id, 0) vals_list.append(vals) orderpoint_model.create(vals_list) def create_orderpoints(self, products): """Create orderpoint for *products* based on these templates. :type products: recordset of products """ for order_point in self: order_point._remove_old_instances(products) order_point._create_instances(products) def create_auto_orderpoints(self): for template in self: if not template.auto_generate: continue if ( not template.auto_last_generation or template.write_date > template.auto_last_generation ): template.auto_last_generation = fields.Datetime.now() template.create_orderpoints(template.auto_product_ids) @api.model def _cron_create_auto_orderpoints(self): self.search([("auto_generate", "=", True)]).create_auto_orderpoints()
39.581731
8,233
3,016
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). import logging from odoo import SUPERUSER_ID, api logger = logging.getLogger(__name__) def post_init_hook(cr, registry): """ The objective of this hook is to link existing MOs coming from a Stock Request. """ logger.info("Linking existing MOs coming from a Stock Request") link_existing_mos_to_stock_request(cr) def link_existing_mos_to_stock_request(cr): env = api.Environment(cr, SUPERUSER_ID, dict()) stock_request_obj = env["stock.request"] stock_request_order_obj = env["stock.request.order"] stock_request_allocation_obj = env["stock.request.allocation"] mrp_production_obj = env["mrp.production"] mos_with_sr = mrp_production_obj.search([("origin", "ilike", "SR/%")]) logger.info("Linking %s MOs records" % len(mos_with_sr)) stock_requests = stock_request_obj.search( [("name", "in", [mo.origin for mo in mos_with_sr])] ) for mo in mos_with_sr: stock_request = stock_requests.filtered(lambda x: x.name == mo.origin) if stock_request: # Link SR to MO mo.stock_request_ids = [(6, 0, stock_request.ids)] logger.info("MO {} linked to SR {}".format(mo.name, stock_request.name)) if ( not stock_request_allocation_obj.search( [("stock_request_id", "=", stock_request.id)] ) and mo.state != "cancel" ): # Create allocation for finish move logger.info("Create allocation for {}".format(stock_request.name)) mo.move_finished_ids[0].allocation_ids = [ ( 0, 0, { "stock_request_id": request.id, "requested_product_uom_qty": request.product_qty, }, ) for request in mo.stock_request_ids ] # Update allocations logger.info("Updating Allocations for SR %s" % stock_request.name) for ml in mo.finished_move_line_ids.filtered( lambda m: m.exists() and m.move_id.allocation_ids ): qty_done = ml.product_uom_id._compute_quantity( ml.qty_done, ml.product_id.uom_id ) to_allocate_qty = ml.qty_done for allocation in ml.move_id.allocation_ids: if allocation.open_product_qty: allocated_qty = min(allocation.open_product_qty, qty_done) allocation.allocated_product_qty += allocated_qty to_allocate_qty -= allocated_qty stock_request.check_done() # Update production_ids from SROs stock_request_order_obj.search([])._compute_production_ids()
41.315068
3,016
766
py
PYTHON
15.0
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "Stock Request MRP", "summary": "Manufacturing request for stock", "version": "15.0.1.1.0", "license": "LGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "ForgeFlow, Odoo Community Association (OCA)", "category": "Warehouse Management", "depends": ["stock_request", "mrp"], "data": [ "security/ir.model.access.csv", "views/stock_request_views.xml", "views/stock_request_order_views.xml", "views/mrp_production_views.xml", ], "installable": True, "auto_install": True, "post_init_hook": "post_init_hook", }
34.818182
766
5,858
py
PYTHON
15.0
# Copyright 2016-20 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2022 Tecnativa - Pedro M. Baeza # Copyright 2022 Tecnativa - Víctor Martínez # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo import fields from odoo.tests import Form from odoo.addons.stock_request.tests.test_stock_request import TestStockRequest class TestStockRequestMrp(TestStockRequest): def setUp(self): super().setUp() self.mrp_user_group = self.env.ref("mrp.group_mrp_user") # common data self.stock_request_user.write({"groups_id": [(4, self.mrp_user_group.id)]}) self.stock_request_manager.write({"groups_id": [(4, self.mrp_user_group.id)]}) self.route_manufacture = self.warehouse.manufacture_pull_id.route_id self.product.write({"route_ids": [(6, 0, self.route_manufacture.ids)]}) self.raw_1 = self._create_product("SL", "Sole", False) self._update_qty_in_location(self.warehouse.lot_stock_id, self.raw_1, 10) self.raw_2 = self._create_product("LC", "Lace", False) self._update_qty_in_location(self.warehouse.lot_stock_id, self.raw_2, 10) self.bom = self._create_mrp_bom(self.product, [self.raw_1, self.raw_2]) self.uom_pair = self.env["uom.uom"].create( { "name": "Test-Pair", "category_id": self.categ_unit.id, "factor_inv": 2, "uom_type": "bigger", "rounding": 0.001, } ) def _update_qty_in_location(self, location, product, quantity): self.env["stock.quant"]._update_available_quantity(product, location, quantity) def _create_mrp_bom(self, product_id, raw_materials): bom = self.env["mrp.bom"].create( { "product_id": product_id.id, "product_tmpl_id": product_id.product_tmpl_id.id, "product_uom_id": product_id.uom_id.id, "product_qty": 1.0, "type": "normal", } ) for raw_mat in raw_materials: self.env["mrp.bom.line"].create( {"bom_id": bom.id, "product_id": raw_mat.id, "product_qty": 1} ) return bom def _produce(self, mo, qty=0.0): mo_form = Form(mo) mo_form.qty_producing = qty mo_form.save() def _create_stock_request(self, user, products): order_form = Form( self.request_order.with_user(user).with_context( default_company_id=self.main_company.id, default_warehouse_id=self.warehouse.id, default_location_id=self.warehouse.lot_stock_id, ) ) order_form.expected_date = fields.Datetime.now() for product_data in products: with order_form.stock_request_ids.new() as item_form: item_form.product_id = product_data[0] item_form.product_uom_qty = product_data[1] return order_form.save() def test_create_request_01(self): """Single Stock request with buy rule""" order = self._create_stock_request(self.stock_request_user, [(self.product, 5)]) order.action_confirm() self.assertEqual(order.state, "open") self.assertEqual(order.stock_request_ids.state, "open") order.refresh() self.assertEqual(len(order.production_ids), 1) self.assertEqual(len(order.stock_request_ids.production_ids), 1) self.assertEqual(order.stock_request_ids.qty_in_progress, 5.0) manufacturing_order = order.production_ids[0] self.assertEqual( manufacturing_order.company_id, order.stock_request_ids[0].company_id ) manufacturing_order.action_confirm() manufacturing_order.write( {"qty_producing": manufacturing_order.product_uom_qty} ) manufacturing_order._set_qty_producing() manufacturing_order.with_context(skip_immediate=True).button_mark_done() self.assertEqual(order.stock_request_ids.qty_in_progress, 0.0) self.assertEqual(order.stock_request_ids.qty_done, 5.0) order2 = order.copy() self.assertFalse(order2.production_ids) def test_stock_request_order_action_cancel(self): order = self._create_stock_request(self.stock_request_user, [(self.product, 5)]) order.action_confirm() production = fields.first(order.stock_request_ids.production_ids) self.assertEqual(production.state, "confirmed") order.with_context(bypass_confirm_wizard=True).action_cancel() self.assertEqual(production.state, "cancel") def test_stock_request_order_production_action_cancel(self): order = self._create_stock_request(self.stock_request_user, [(self.product, 5)]) order.action_confirm() production = fields.first(order.stock_request_ids.production_ids) self.assertEqual(production.state, "confirmed") production.action_cancel() self.assertEqual(order.state, "cancel") def test_view_actions(self): order = self._create_stock_request(self.stock_request_user, [(self.product, 5)]) order.action_confirm() stock_request = order.stock_request_ids action = stock_request.action_view_mrp_production() self.assertEqual("views" in action.keys(), True) self.assertEqual(action["res_id"], stock_request.production_ids[0].id) action = stock_request.production_ids[0].action_view_stock_request() self.assertEqual(action["type"], "ir.actions.act_window") self.assertEqual(action["res_id"], stock_request.id) action = order.action_view_mrp_production() self.assertEqual("views" in action.keys(), True) self.assertEqual(action["res_id"], order.production_ids[0].id)
41.531915
5,856
1,535
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" production_ids = fields.One2many( "mrp.production", compute="_compute_production_ids", string="Manufacturing Orders", readonly=True, ) production_count = fields.Integer( string="Manufacturing Orders count", compute="_compute_production_ids", readonly=True, ) @api.depends("stock_request_ids") def _compute_production_ids(self): for req in self: req.production_ids = req.stock_request_ids.mapped("production_ids") req.production_count = len(req.production_ids) def action_view_mrp_production(self): action = self.env["ir.actions.act_window"]._for_xml_id( "mrp.mrp_production_action" ) productions = self.mapped("production_ids") if len(productions) > 1: action["domain"] = [("id", "in", productions.ids)] action["views"] = [ (self.env.ref("mrp.mrp_production_tree_view").id, "tree"), (self.env.ref("mrp.mrp_production_form_view").id, "form"), ] elif productions: action["views"] = [ (self.env.ref("mrp.mrp_production_form_view").id, "form") ] action["res_id"] = productions.id return action
34.886364
1,535
1,886
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class StockRequest(models.Model): _inherit = "stock.request" production_ids = fields.Many2many( "mrp.production", "mrp_production_stock_request_rel", "stock_request_id", "mrp_production_id", string="Manufacturing Orders", readonly=True, copy=False, ) production_count = fields.Integer( string="Manufacturing Orders count", compute="_compute_production_ids", readonly=True, ) @api.depends("production_ids") def _compute_production_ids(self): for request in self: request.production_count = len(request.production_ids) @api.constrains("production_ids", "company_id") def _check_production_company_constrains(self): if any( any( production.company_id != req.company_id for production in req.production_ids ) for req in self ): raise ValidationError( _( "You have linked to a Manufacture Order " "that belongs to another company." ) ) def action_view_mrp_production(self): action = self.env["ir.actions.act_window"]._for_xml_id( "mrp.mrp_production_action" ) productions = self.mapped("production_ids") if len(productions) > 1: action["domain"] = [("id", "in", productions.ids)] elif productions: action["views"] = [ (self.env.ref("mrp.mrp_production_form_view").id, "form") ] action["res_id"] = productions.id return action
31.966102
1,886
806
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _prepare_mo_vals( self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values, bom, ): res = super()._prepare_mo_vals( product_id, product_qty, product_uom, location_id, name, origin, company_id, values, bom, ) if "stock_request_id" in values: res["stock_request_ids"] = [(4, values["stock_request_id"])] return res
23.705882
806
2,206
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class MrpProduction(models.Model): _inherit = "mrp.production" stock_request_ids = fields.Many2many( "stock.request", "mrp_production_stock_request_rel", "mrp_production_id", "stock_request_id", string="Stock Requests", ) stock_request_count = fields.Integer( "Stock Request #", compute="_compute_stock_request_ids" ) @api.depends("stock_request_ids") def _compute_stock_request_ids(self): for rec in self: rec.stock_request_count = len(rec.stock_request_ids) def action_view_stock_request(self): """ :return dict: dictionary value for created view """ action = self.env["ir.actions.act_window"]._for_xml_id( "stock_request.action_stock_request_form" ) requests = self.mapped("stock_request_ids") if len(requests) > 1: action["domain"] = [("id", "in", requests.ids)] elif requests: action["views"] = [ (self.env.ref("stock_request.view_stock_request_form").id, "form") ] action["res_id"] = requests.id return action def _get_move_finished_values( self, product_id, product_uom_qty, product_uom, operation_id=False, byproduct_id=False, cost_share=0, ): res = super()._get_move_finished_values( product_id, product_uom_qty, product_uom, operation_id=operation_id, byproduct_id=byproduct_id, cost_share=cost_share, ) if self.stock_request_ids: res["allocation_ids"] = [ ( 0, 0, { "stock_request_id": request.id, "requested_product_uom_qty": request.product_qty, }, ) for request in self.stock_request_ids ] return res
30.219178
2,206
629
py
PYTHON
15.0
# Copyright 2018-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "Stock Orderpoint Purchase Link", "summary": "Link Reordering rules to purchase orders", "version": "15.0.1.0.0", "license": "LGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "ForgeFlow, Odoo Community Association (OCA)", "category": "Warehouse Management", "depends": ["stock_orderpoint_move_link", "purchase_stock"], "data": ["views/purchase_order_views.xml"], "installable": True, "auto_install": True, }
39.3125
629
3,216
py
PYTHON
15.0
# Copyright 2018-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo.tests import common class TestOrderpointPurchaseLink(common.TransactionCase): def setUp(self): super(TestOrderpointPurchaseLink, self).setUp() self.product_obj = self.env["product.product"] self.partner_obj = self.env["res.partner"] self.pol_obj = self.env["purchase.order.line"] self.location_obj = self.env["stock.location"] self.orderpoint_obj = self.env["stock.warehouse.orderpoint"] self.route_obj = self.env["stock.location.route"] self.rule_obj = self.env["stock.rule"] self.group_obj = self.env["procurement.group"] # WH and routes: self.warehouse = self.env.ref("stock.warehouse0") self.stock_location = self.warehouse.lot_stock_id self.test_location = self.location_obj.create( {"name": "Test", "location_id": self.warehouse.view_location_id.id} ) route_buy = self.env.ref("purchase_stock.route_warehouse0_buy").id route_test = self.route_obj.create({"name": "Stock to Test"}).id self.rule_obj.create( { "name": "Stock to Test", "action": "pull", "procure_method": "make_to_order", "location_id": self.test_location.id, "location_src_id": self.stock_location.id, "route_id": route_test, "picking_type_id": self.warehouse.int_type_id.id, "warehouse_id": self.warehouse.id, "group_propagation_option": "none", } ) # Partners: vendor1 = self.partner_obj.create({"name": "Vendor 1"}) # Create products: self.tp1 = self.product_obj.create( { "name": "Test Product 1", "type": "product", "list_price": 150.0, "route_ids": [(6, 0, [route_buy, route_test])], "seller_ids": [(0, 0, {"name": vendor1.id, "price": 20.0})], } ) # Create Orderpoints: self.op1 = self.orderpoint_obj.create( { "product_id": self.tp1.id, "location_id": self.stock_location.id, "product_min_qty": 5.0, "product_max_qty": 20.0, } ) self.op2 = self.orderpoint_obj.create( { "product_id": self.tp1.id, "location_id": self.test_location.id, "product_min_qty": 5.0, "product_max_qty": 20.0, } ) def test_01_po_line_from_orderpoints(self): """Test that a PO line created/updated by two orderpoints keeps the link with both of them.""" self.group_obj.run_scheduler() po_line = self.env["purchase.order.line"].search( [("product_id", "=", self.tp1.id)] ) self.assertTrue(po_line) # Each orderpoint must have required 20.0 units: self.assertEqual(po_line.product_qty, 40.0) self.assertEqual(len(po_line.orderpoint_ids), 2)
38.746988
3,216
1,131
py
PYTHON
15.0
# Copyright 2018-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" orderpoint_ids = fields.Many2many( comodel_name="stock.warehouse.orderpoint", string="Orderpoints", copy=False, readonly=True, ) @api.model def _prepare_purchase_order_line_from_procurement( self, product_id, product_qty, product_uom, company_id, values, po ): vals = super()._prepare_purchase_order_line_from_procurement( product_id, product_qty, product_uom, company_id, values, po ) # If the procurement was run directly by a reordering rule. if "orderpoint_id" in values and values["orderpoint_id"].id: vals["orderpoint_ids"] = [(4, values["orderpoint_id"].id)] # If the procurement was run by a stock move. elif "orderpoint_ids" in values: vals["orderpoint_ids"] = [(4, o.id) for o in values["orderpoint_ids"]] return vals
37.7
1,131
816
py
PYTHON
15.0
# Copyright 2018-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _update_purchase_order_line( self, product_id, product_qty, product_uom, company_id, values, line ): vals = super()._update_purchase_order_line( product_id, product_qty, product_uom, company_id, values, line ) if "orderpoint_id" in values and values["orderpoint_id"].id: vals["orderpoint_ids"] = [(4, values["orderpoint_id"].id)] # If the procurement was run by a stock move. elif "orderpoint_ids" in values: vals["orderpoint_ids"] = [(4, o.id) for o in values["orderpoint_ids"]] return vals
38.857143
816
433
py
PYTHON
15.0
# Copyright 2018-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import fields, models class StockWarehouseOrderpoint(models.Model): _inherit = "stock.warehouse.orderpoint" purchase_line_ids = fields.Many2many( comodel_name="purchase.order.line", string="Purchase Order Lines", copy=False, readonly=True, )
28.866667
433
791
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Sale Stock Available Info Popup", "summary": "Adds an 'Available to promise' quantity to the popover shown " "in sale order line that display stock info of the product", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Warehouse Management", "version": "15.0.1.0.0", "license": "AGPL-3", "depends": ["sale_stock", "stock_available"], "data": ["views/sale_order_views.xml"], "assets": { "web.assets_qweb": [ "sale_stock_available_info_popup/static/src/xml/qty_at_date.xml", ], }, "installable": True, }
39.55
791
3,665
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from datetime import timedelta from odoo.fields import Datetime from odoo.tests import Form, common, new_test_user from odoo.tests.common import users class SaleStockAvailableInfoPopup(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.sale_user = new_test_user( cls.env, login="sale_user", groups="sales_team.group_sale_salesman", ) cls.product = cls.env["product.product"].create( {"name": "Storable product", "detailed_type": "product"} ) cls.partner = cls.env["res.partner"].create({"name": "Mr. Odoo"}) cls.env["stock.quant"].create( { "product_id": cls.product.id, "location_id": cls.env.ref("stock.stock_location_stock").id, "quantity": 40.0, } ) picking_in = cls._create_picking(cls, cls.env.ref("stock.picking_type_in"), 5) picking_in.action_assign() picking_out = cls._create_picking(cls, cls.env.ref("stock.picking_type_out"), 3) picking_out.action_assign() def _create_picking(self, picking_type, qty): picking_form = Form(self.env["stock.picking"]) picking_form.picking_type_id = picking_type with picking_form.move_ids_without_package.new() as move: move.product_id = self.product move.product_uom_qty = qty return picking_form.save() def _create_sale(self): sale_form = Form(self.env["sale.order"]) sale_form.partner_id = self.partner sale_form.user_id = self.sale_user return sale_form def _add_sale_line(self, sale_form, product, qty=1): with sale_form.order_line.new() as line: line.product_id = self.product line.product_uom_qty = qty @users("admin", "sale_user") def test_immediately_usable_qty_today(self): sale_form = self._create_sale() self._add_sale_line(sale_form, self.product) sale = sale_form.save() # 42=40-1+3 self.assertAlmostEqual(sale.order_line.immediately_usable_qty_today, 42) @users("admin", "sale_user") def test_immediately_usable_qty_today_similar_solines(self): """Create a sale order containing three times the same product. The quantity available should be different for the 3 lines. """ # Modules like stock_available_inmmediately change the behavior of this field # so we have to evaluate their values on the fly qty = self.product.immediately_usable_qty yesterday = Datetime.now() - timedelta(days=1) sale_form = self._create_sale() self._add_sale_line(sale_form, self.product, 5) self._add_sale_line(sale_form, self.product, 5) self._add_sale_line(sale_form, self.product, 5) sale = sale_form.save() self.assertEqual( sale.order_line.mapped("immediately_usable_qty_today"), [qty, qty - 5, qty - 10], ) self.product.invalidate_cache() qty_yesterday = self.product.with_context( to_date=yesterday ).immediately_usable_qty self.assertFalse(qty == qty_yesterday) # Commitment date will affect the computation sale.commitment_date = yesterday sale.order_line.invalidate_cache() self.assertEqual( sale.order_line.mapped("immediately_usable_qty_today"), [qty_yesterday, qty_yesterday - 5, qty_yesterday - 10], )
39.836957
3,665
1,219
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from collections import defaultdict from odoo import api, fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" immediately_usable_qty_today = fields.Float( compute="_compute_immediately_usable_qty_today" ) @api.depends( "product_id", "product_uom_qty", "scheduled_date", "order_id.date_order", "warehouse_id", ) def _compute_immediately_usable_qty_today(self): qty_processed_per_product = defaultdict(lambda: 0) self.immediately_usable_qty_today = False for line in self.sorted(key=lambda r: r.sequence): if not line.display_qty_widget: continue product = line.product_id.with_context( to_date=line.scheduled_date, warehouse=line.warehouse_id.id ) qty_processed = qty_processed_per_product[product.id] line.immediately_usable_qty_today = ( product.immediately_usable_qty - qty_processed ) qty_processed_per_product[product.id] += line.product_uom_qty
33.861111
1,219
560
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Move Line Product", "version": "15.0.1.0.1", "summary": "Displays the product in the journal entries and items", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", "category": "Generic", "depends": ["account"], "license": "AGPL-3", "data": ["views/account_move_line_view.xml"], "installable": True, }
37.333333
560
570
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Stock Lot Filter Available", "summary": "Allow to filter lots by available on stock", "version": "15.0.1.0.0", "category": "Warehouse", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["stock"], "data": ["views/stock_production_lot_views.xml"], "website": "https://github.com/OCA/stock-logistics-warehouse", "installable": True, "maintainers": ["CarlosRoca13"], }
38
570
1,373
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestStockLotFilterAvailable(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.StockProductionLot = cls.env["stock.production.lot"] cls.company = cls.env.ref("base.main_company") cls.loc = cls.env.ref("stock.stock_location_stock") cls.product = cls.env["product.product"].create( {"name": "Test product", "detailed_type": "product", "tracking": "lot"} ) cls.lot = cls.StockProductionLot.create( { "name": "TT-LOT", "product_id": cls.product.id, "company_id": cls.company.id, } ) cls.env["stock.quant"]._update_available_quantity( cls.product, cls.loc, 100, lot_id=cls.lot ) def test_bad_operator(self): with self.assertRaises(ValueError): self.StockProductionLot._search_product_qty("in", [10, 15]) def test_good_operator(self): domain = self.StockProductionLot._search_product_qty(">", 0) self.assertTrue(self.lot.id in domain[0][2]) domain = self.StockProductionLot._search_product_qty(">", 2) self.assertTrue(self.lot.id in domain[0][2])
38.138889
1,373
1,564
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import operator as operator_lib from odoo import _, fields, models class StockProductionLot(models.Model): _inherit = "stock.production.lot" product_qty = fields.Float(search="_search_product_qty") def _search_product_qty(self, operator, value): operator_mapping = { ">": operator_lib.gt, ">=": operator_lib.ge, "<": operator_lib.lt, "<=": operator_lib.le, "=": operator_lib.eq, "!=": operator_lib.ne, } if operator not in operator_mapping: raise ValueError(_("Unsupported search")) ids = [] domain = [ ("location_id.usage", "in", ["internal", "transit"]), ("lot_id", "!=", False), ] groups = self.env["stock.quant"].read_group( domain, ["lot_id", "quantity"], ["lot_id"] ) involved_lot_ids = [group["lot_id"][0] for group in groups] if ( (operator == "=" and value == 0) or (operator == "<" and value > 0) or (operator == "<=" and value >= 0) ): ids.extend( self.env["stock.production.lot"] .search([("id", "not in", involved_lot_ids)]) .ids ) for group in groups: if operator_mapping[operator](group["quantity"], value): ids.append(group["lot_id"][0]) return [("id", "in", ids)]
34
1,564
737
py
PYTHON
15.0
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). { "name": "Stock Request Purchase", "summary": "Internal request for stock", "version": "15.0.1.0.2", "license": "LGPL-3", "website": "https://github.com/OCA/stock-logistics-warehouse", "author": "ForgeFlow, Odoo Community Association (OCA)", "category": "Warehouse Management", "depends": ["stock_request", "purchase_stock"], "data": [ "security/ir.model.access.csv", "views/stock_request_views.xml", "views/stock_request_order_views.xml", "views/purchase_order_views.xml", ], "installable": True, "auto_install": True, }
35.095238
737
10,081
py
PYTHON
15.0
# Copyright 2016-20 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2023 Tecnativa - Víctor Martínez # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl-3.0). from odoo import fields from odoo.tests import common, new_test_user class TestStockRequestPurchase(common.TransactionCase): def setUp(self): super().setUp() self.env = self.env( context=dict( self.env.context, mail_create_nolog=True, mail_create_nosubscribe=True, mail_notrack=True, no_reset_password=True, ) ) # common models self.stock_request = self.env["stock.request"] # refs self.main_company = self.env.ref("base.main_company") self.warehouse = self.env.ref("stock.warehouse0") self.categ_unit = self.env.ref("uom.product_uom_categ_unit") # common data self.company_2 = self.env["res.company"].create({"name": "Comp2"}) self.wh2 = self.env["stock.warehouse"].search( [("company_id", "=", self.company_2.id)], limit=1 ) self.stock_request_user = new_test_user( self.env, login="stock_request_user", groups="stock_request.group_stock_request_user", company_ids=[(6, 0, [self.main_company.id, self.company_2.id])], ) self.stock_request_manager = new_test_user( self.env, login="stock_request_manager", groups="stock_request.group_stock_request_manager", company_ids=[(6, 0, [self.main_company.id, self.company_2.id])], ) self.route_buy = self.warehouse.buy_pull_id.route_id self.supplier = self.env["res.partner"].create({"name": "Supplier"}) self.product = self._create_product("SH", "Shoes", False) self.uom_dozen = self.env["uom.uom"].create( { "name": "Test-DozenA", "category_id": self.categ_unit.id, "factor_inv": 12, "uom_type": "bigger", "rounding": 0.001, } ) def _create_product(self, default_code, name, company_id): return self.env["product.product"].create( { "name": name, "default_code": default_code, "uom_id": self.env.ref("uom.product_uom_unit").id, "company_id": company_id, "type": "product", "route_ids": [(6, 0, self.route_buy.ids)], "seller_ids": [(0, 0, {"name": self.supplier.id, "delay": 5})], } ) def test_create_request_01(self): """Single Stock request with buy rule""" expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } order = ( self.env["stock.request.order"] .with_user(self.stock_request_user) .create(vals) ) order.action_confirm() self.assertEqual(order.state, "open") self.assertEqual(order.stock_request_ids.state, "open") order.refresh() self.assertEqual(len(order.sudo().purchase_ids), 1) self.assertEqual(len(order.picking_ids), 0) self.assertEqual(len(order.move_ids), 0) self.assertEqual(len(order.stock_request_ids.sudo().purchase_ids), 1) self.assertEqual(len(order.stock_request_ids.picking_ids), 0) self.assertEqual(len(order.stock_request_ids.move_ids), 0) self.assertEqual(order.stock_request_ids.qty_in_progress, 0.0) purchase = order.sudo().purchase_ids[0] self.assertEqual(purchase.company_id, order.stock_request_ids[0].company_id) purchase.button_confirm() picking = purchase.picking_ids[0] picking.action_confirm() self.assertEqual(order.stock_request_ids.qty_in_progress, 5.0) self.assertEqual(order.stock_request_ids.qty_done, 0.0) picking.action_assign() packout1 = picking.move_line_ids[0] packout1.qty_done = 5 picking.button_validate() self.assertEqual(order.stock_request_ids.qty_in_progress, 0.0) self.assertEqual( order.stock_request_ids.qty_done, order.stock_request_ids.product_uom_qty ) self.assertEqual(order.stock_request_ids.state, "done") self.assertEqual(order.state, "done") def test_create_request_02(self): """Multiple Stock requests with buy rule""" vals = { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, } stock_request_1 = self.stock_request.with_user(self.stock_request_user).create( vals ) stock_request_2 = self.stock_request.with_user( self.stock_request_manager ).create(vals) stock_request_1.action_confirm() self.assertEqual( sum(stock_request_1.sudo().purchase_line_ids.mapped("product_qty")), 5 ) stock_request_2.with_user(self.stock_request_manager).sudo().action_confirm() self.assertEqual( sum(stock_request_2.sudo().purchase_line_ids.mapped("product_qty")), 10 ) stock_request_1.refresh() stock_request_2.refresh() self.assertEqual(len(stock_request_1.sudo().purchase_ids), 1) self.assertEqual(len(stock_request_2.sudo().purchase_ids), 1) self.assertEqual(len(stock_request_1.sudo().purchase_ids), 1) self.assertEqual(len(stock_request_2.sudo().purchase_line_ids), 1) self.assertEqual( stock_request_1.sudo().purchase_ids, stock_request_2.sudo().purchase_ids ) self.assertEqual( stock_request_1.sudo().purchase_line_ids, stock_request_2.sudo().purchase_line_ids, ) purchase = stock_request_1.sudo().purchase_ids[0] purchase.button_confirm() picking = purchase.picking_ids[0] picking.action_confirm() self.assertEqual(stock_request_1.qty_in_progress, 5.0) self.assertEqual(stock_request_1.qty_done, 0.0) self.assertEqual(stock_request_2.qty_in_progress, 5.0) self.assertEqual(stock_request_2.qty_done, 0.0) picking.action_assign() packout1 = picking.move_line_ids[0] packout1.qty_done = 10 picking.button_validate() self.assertEqual(stock_request_1.qty_in_progress, 0.0) self.assertEqual(stock_request_1.qty_done, stock_request_1.product_uom_qty) self.assertEqual(stock_request_2.qty_in_progress, 0.0) self.assertEqual(stock_request_2.qty_done, stock_request_2.product_uom_qty) def test_create_request_cancel_purchase(self): vals = { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, } stock_request = self.stock_request.with_user(self.stock_request_user).create( vals ) stock_request.action_confirm() self.assertEqual(stock_request.purchase_ids.state, "draft") stock_request.action_cancel() self.assertEqual(stock_request.purchase_ids.state, "cancel") def test_view_actions(self): expected_date = fields.Datetime.now() vals = { "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, "stock_request_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom_id": self.product.uom_id.id, "product_uom_qty": 5.0, "company_id": self.main_company.id, "warehouse_id": self.warehouse.id, "location_id": self.warehouse.lot_stock_id.id, "expected_date": expected_date, }, ) ], } order = self.env["stock.request.order"].sudo().create(vals) order.action_confirm() stock_request = order.stock_request_ids action = stock_request.action_view_purchase() self.assertEqual(action["domain"], "[]") self.assertEqual("views" in action.keys(), True) self.assertEqual(action["res_id"], stock_request.purchase_ids[0].id) action = stock_request.purchase_ids[0].action_view_stock_request() self.assertEqual(action["type"], "ir.actions.act_window") self.assertEqual(action["res_id"], stock_request.id) action = order.action_view_purchase() self.assertEqual(action["domain"], "[]") self.assertEqual("views" in action.keys(), True) self.assertEqual(action["res_id"], order.purchase_ids[0].id)
38.033962
10,079
1,657
py
PYTHON
15.0
# Copyright 2018 Creu Blanca # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class StockRequestOrder(models.Model): _inherit = "stock.request.order" purchase_ids = fields.One2many( "purchase.order", compute="_compute_purchase_ids", string="Purchase Orders", readonly=True, ) purchase_count = fields.Integer(compute="_compute_purchase_ids", readonly=True) purchase_line_ids = fields.Many2many( "purchase.order.line", compute="_compute_purchase_ids", string="Purchase Order Lines", readonly=True, copy=False, ) @api.depends("stock_request_ids") def _compute_purchase_ids(self): for req in self: req.purchase_ids = req.stock_request_ids.mapped("purchase_ids") req.purchase_line_ids = req.stock_request_ids.mapped("purchase_line_ids") req.purchase_count = len(req.purchase_ids) def action_view_purchase(self): action = self.env["ir.actions.act_window"]._for_xml_id("purchase.purchase_rfq") purchases = self.mapped("purchase_ids") if len(purchases) > 1: action["domain"] = [("id", "in", purchases.ids)] action["views"] = [ (self.env.ref("purchase.purchase_order_tree").id, "tree"), (self.env.ref("purchase.purchase_order_form").id, "form"), ] elif purchases: action["views"] = [ (self.env.ref("purchase.purchase_order_form").id, "form") ] action["res_id"] = purchases.id return action
36.021739
1,657
1,837
py
PYTHON
15.0
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class PurchaseOrderLine(models.Model): _inherit = "purchase.order.line" stock_request_ids = fields.Many2many( comodel_name="stock.request", string="Stock Requests", copy=False ) def _prepare_stock_moves(self, picking): res = super()._prepare_stock_moves(picking) for re in res: re["allocation_ids"] = [ ( 0, 0, { "stock_request_id": request.id, "requested_product_uom_qty": request.product_qty, }, ) for request in self.stock_request_ids ] return res @api.model def _prepare_purchase_order_line_from_procurement( self, product_id, product_qty, product_uom, company_id, values, po ): vals = super()._prepare_purchase_order_line_from_procurement( product_id, product_qty, product_uom, company_id, values, po ) if "stock_request_id" in values: vals["stock_request_ids"] = [(4, values["stock_request_id"])] return vals @api.constrains("stock_request_ids") def _check_purchase_company_constrains(self): if any( any(req.company_id != pol.company_id for req in pol.stock_request_ids) for pol in self ): raise ValidationError( _( "You cannot link a purchase order line " "to a stock request that belongs to " "another company." ) )
33.4
1,837
1,371
py
PYTHON
15.0
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import api, fields, models class PurchaseOrder(models.Model): _inherit = "purchase.order" stock_request_ids = fields.Many2many( comodel_name="stock.request", string="Stock Requests", compute="_compute_stock_request_ids", ) stock_request_count = fields.Integer( "Stock Request #", compute="_compute_stock_request_ids" ) @api.depends("order_line") def _compute_stock_request_ids(self): for rec in self: rec.stock_request_ids = rec.order_line.mapped("stock_request_ids") rec.stock_request_count = len(rec.stock_request_ids) def action_view_stock_request(self): """ :return dict: dictionary value for created view """ action = self.env["ir.actions.act_window"]._for_xml_id( "stock_request.action_stock_request_form" ) requests = self.mapped("stock_request_ids") if len(requests) > 1: action["domain"] = [("id", "in", requests.ids)] elif requests: action["views"] = [ (self.env.ref("stock_request.view_stock_request_form").id, "form") ] action["res_id"] = requests.id return action
33.439024
1,371
2,237
py
PYTHON
15.0
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com) # Copyright 2023 Tecnativa - Víctor Martínez # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class StockRequest(models.Model): _inherit = "stock.request" purchase_ids = fields.One2many( "purchase.order", compute="_compute_purchase_ids", string="Purchase Orders", readonly=True, ) purchase_count = fields.Integer(compute="_compute_purchase_ids", readonly=True) purchase_line_ids = fields.Many2many( "purchase.order.line", string="Purchase Order Lines", readonly=True, copy=False ) @api.depends("purchase_line_ids") def _compute_purchase_ids(self): for request in self: request.purchase_ids = request.purchase_line_ids.mapped("order_id") request.purchase_count = len(request.purchase_ids) @api.constrains("purchase_line_ids", "company_id") def _check_purchase_company_constrains(self): if any( any(line.company_id != req.company_id for line in req.purchase_line_ids) for req in self ): raise ValidationError( _( "You have linked to a purchase order line " "that belongs to another company." ) ) def action_cancel(self): """Propagate the cancellation to the generated purchase orders.""" res = super().action_cancel() self.sudo().purchase_ids.filtered( lambda x: x.state not in ("purchase", "done", "cancel") and x.stock_request_ids == self ).button_cancel() return res def action_view_purchase(self): action = self.env["ir.actions.act_window"]._for_xml_id("purchase.purchase_rfq") purchases = self.mapped("purchase_ids") if len(purchases) > 1: action["domain"] = [("id", "in", purchases.ids)] elif purchases: action["views"] = [ (self.env.ref("purchase.purchase_order_form").id, "form") ] action["res_id"] = purchases.id return action
36.048387
2,235
614
py
PYTHON
15.0
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com). # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _update_purchase_order_line( self, product_id, product_qty, product_uom, company_id, values, line ): vals = super()._update_purchase_order_line( product_id, product_qty, product_uom, company_id, values, line ) if "stock_request_id" in values: vals["stock_request_ids"] = [(4, values["stock_request_id"])] return vals
34.111111
614