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
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
720
py
PYTHON
15.0
# Copyright 2013-2014 Camptocamp SA - Guewen Baconnier # © 2016-20 ForgeFlow S.L. (https://www.forgeflow.com) # © 2016 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Procurement Group by Line", "summary": "Base module for multiple procurement group by Sale order", "version": "15.0.1.2.0", "author": "Camptocamp," "ForgeFlow," "Serpent Consulting Services Pvt. Ltd.," "Odoo Community Association (OCA)", "category": "Warehouse", "license": "AGPL-3", "development_status": "Production/Stable", "website": "https://github.com/OCA/sale-workflow", "depends": ["sale_stock"], "installable": True, }
35.9
718
5,675
py
PYTHON
15.0
# Copyright 2013-2014 Camptocamp SA - Guewen Baconnier # © 2016-20 ForgeFlow S.L. (https://www.forgeflow.com) # © 2016 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import Form from odoo.tests.common import TransactionCase class TestSaleProcurementGroupByLine(TransactionCase): def setUp(self): super(TestSaleProcurementGroupByLine, self).setUp() # Required Models self.product_model = self.env["product.product"] self.product_ctg_model = self.env["product.category"] self.proc_group_model = self.env["procurement.group"] self.sale_model = self.env["sale.order"] self.order_line_model = self.env["sale.order.line"] # Customer self.customer = self.env.ref("base.res_partner_2") # Warehouse self.warehouse_id = self.env.ref("stock.warehouse0") # Create product category self.product_ctg = self._create_product_category() # Create Products self.new_product1 = self._create_product("test_product1") self.new_product2 = self._create_product("test_product2") self.sale = self._create_sale_order() def _create_product_category(self): product_ctg = self.product_ctg_model.create({"name": "test_product_ctg"}) return product_ctg def _create_product(self, name): product = self.product_model.create( {"name": name, "categ_id": self.product_ctg.id, "type": "product"} ) return product def _create_sale_order(self): """Create a Sale Order.""" self.sale = self.sale_model.create( { "partner_id": self.customer.id, "warehouse_id": self.warehouse_id.id, "picking_policy": "direct", } ) self.line1 = self.order_line_model.create( { "order_id": self.sale.id, "product_id": self.new_product1.id, "product_uom_qty": 10.0, "name": "Sale Order Line Demo1", } ) self.line2 = self.order_line_model.create( { "order_id": self.sale.id, "product_id": self.new_product2.id, "product_uom_qty": 5.0, "name": "Sale Order Line Demo2", } ) return self.sale def test_01_procurement_group_by_line(self): self.sale.action_confirm() self.assertEqual( self.line2.procurement_group_id, self.line1.procurement_group_id, """Both Sale Order line should belong to Procurement Group""", ) self.picking_ids = self.env["stock.picking"].search( [("group_id", "in", self.line2.procurement_group_id.ids)] ) self.picking_ids.move_lines.write({"quantity_done": 5}) wiz_act = self.picking_ids.button_validate() wiz = Form( self.env[wiz_act["res_model"]].with_context(**wiz_act["context"]) ).save() wiz.process() self.assertTrue(self.picking_ids, "Procurement Group should have picking") def test_02_action_launch_procurement_rule_1(self): group_id = self.proc_group_model.create( {"move_type": "one", "sale_id": self.sale.id, "name": self.sale.name} ) self.line1.procurement_group_id = group_id self.line2.procurement_group_id = group_id self.sale.action_confirm() self.assertEqual(self.sale.state, "sale") self.assertEqual(len(self.line1.move_ids), 1) self.assertEqual(self.line1.move_ids.name, self.line1.display_name) self.assertEqual(len(self.line2.move_ids), 1) self.assertEqual(self.line2.move_ids.name, self.line2.display_name) def test_03_action_launch_procurement_rule_2(self): group_id = self.proc_group_model.create( {"move_type": "one", "sale_id": self.sale.id, "name": self.sale.name} ) self.line1.procurement_group_id = group_id self.line2.procurement_group_id = False self.sale.action_confirm() self.assertEqual(self.line2.procurement_group_id, group_id) def test_04_action_launch_procurement_rule_3(self): group_id = self.proc_group_model.create( {"move_type": "one", "sale_id": self.sale.id, "name": self.sale.name} ) self.line1.procurement_group_id = False self.line2.procurement_group_id = False self.sale.action_confirm() self.assertNotEqual(self.line1.procurement_group_id, group_id) self.assertEqual( self.line1.procurement_group_id, self.line2.procurement_group_id ) def test_05_merged_stock_moves_from_same_procurement(self): """ Reduce the qty in the sale order and check no extra picking is created """ self.sale.action_confirm() self.sale.order_line[1].product_uom_qty = 0.0 self.assertEqual( len(self.sale.picking_ids), 1, "Negative stock move should me merged" ) def test_06_update_sale_order_line_respect_procurement_group(self): """ When launching the stock rule again, use maintain same procurement group in lines """ self.sale.action_confirm() proc_group = self.sale.order_line[1].procurement_group_id self.assertEqual(len(self.line1.move_ids), 1) self.sale.order_line[1].product_uom_qty += 1 self.assertEqual(self.sale.order_line[1].procurement_group_id, proc_group) self.assertEqual(len(self.line1.move_ids), 1)
40.81295
5,673
644
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). from odoo import models class StockMove(models.Model): _inherit = "stock.move" def _update_candidate_moves_list(self, candidate_moves_list): """ We want to merge stock moves within the procurement group only """ res = super()._update_candidate_moves_list(candidate_moves_list) if self.env.context.get("sale_group_by_line"): candidate_moves_list.append( self.sale_line_id.procurement_group_id.stock_move_ids ) return res
33.894737
644
4,885
py
PYTHON
15.0
# Copyright 2013-2014 Camptocamp SA - Guewen Baconnier # © 2016-20 ForgeFlow S.L. (https://www.forgeflow.com) # © 2016 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models from odoo.tools.float_utils import float_compare class SaleOrderLine(models.Model): _inherit = "sale.order.line" procurement_group_id = fields.Many2one( "procurement.group", "Procurement group", copy=False ) def _get_procurement_group(self): super()._get_procurement_group() return self.procurement_group_id or False def _get_procurement_group_key(self): """Return a key with priority to be used to regroup lines in multiple procurement groups """ return 8, self.order_id.id def _action_launch_stock_rule(self, previous_product_uom_qty=False): """ Launch procurement group run method. """ if self._context.get("skip_procurement"): return True precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) procurements = [] groups = {} if not previous_product_uom_qty: previous_product_uom_qty = {} for line in self: line = line.with_company(line.company_id) if line.state != "sale" or line.product_id.type not in ("consu", "product"): continue qty = line._get_qty_procurement(previous_product_uom_qty) if ( float_compare(qty, line.product_uom_qty, precision_digits=precision) == 0 ): continue group_id = line._get_procurement_group() # Group the sales order lines with same procurement group # according to the group key for order_line in line.order_id.order_line: g_id = order_line.procurement_group_id or False if g_id: groups[order_line._get_procurement_group_key()] = g_id if not group_id: group_id = groups.get(line._get_procurement_group_key()) if not group_id: vals = line._prepare_procurement_group_vals() group_id = self.env["procurement.group"].create(vals) else: # In case the procurement group is already created and the # order was cancelled, we need to update certain values # of the group. updated_vals = {} if group_id.partner_id != line.order_id.partner_shipping_id: updated_vals.update( {"partner_id": line.order_id.partner_shipping_id.id} ) if group_id.move_type != line.order_id.picking_policy: updated_vals.update({"move_type": line.order_id.picking_policy}) if updated_vals: group_id.write(updated_vals) line.procurement_group_id = group_id values = line._prepare_procurement_values(group_id=group_id) product_qty = line.product_uom_qty - qty line_uom = line.product_uom quant_uom = line.product_id.uom_id product_qty, procurement_uom = line_uom._adjust_uom_quantities( product_qty, quant_uom ) procurements.append( self.env["procurement.group"].Procurement( line.product_id, product_qty, procurement_uom, line.order_id.partner_shipping_id.property_stock_customer, line.display_name, line.order_id.name, line.order_id.company_id, values, ) ) # We store the procured quantity in the UoM of the line to avoid # duplicated procurements, specially for dropshipping and kits. previous_product_uom_qty[line.id] = line.product_uom_qty if procurements: self.env["procurement.group"].run(procurements) # This next block is currently needed only because the scheduler trigger is done # by picking confirmation rather than stock.move confirmation orders = self.mapped("order_id") for order in orders: pickings_to_confirm = order.picking_ids.filtered( lambda p: p.state not in ["cancel", "done"] ) if pickings_to_confirm: # Trigger the Scheduler for Pickings pickings_to_confirm.action_confirm() return super( SaleOrderLine, self.with_context(sale_group_by_line=True) )._action_launch_stock_rule(previous_product_uom_qty=previous_product_uom_qty)
41.033613
4,883
646
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl) { "name": "Sale Order Product Assortment", "summary": "Module that allows to use the assortments on sale orders", "version": "15.0.2.0.0", "development_status": "Beta", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "maintainers": ["CarlosRoca13"], "license": "AGPL-3", "installable": True, "depends": ["sale", "product_assortment", "base_view_inheritance_extension"], "data": ["views/sale_order_view.xml"], }
38
646
2,557
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestProductAssortment(TransactionCase): def setUp(self): super().setUp() self.filter_obj = self.env["ir.filters"] self.product_obj = self.env["product.product"] self.sale_order_obj = self.env["sale.order"] self.partner_1 = self.env["res.partner"].create({"name": "Test partner 1"}) self.partner_2 = self.env["res.partner"].create({"name": "Test partner 2"}) def test_sale_order_product_assortment(self): product_1 = self.product_obj.create({"name": "Test product 1"}) product_2 = self.product_obj.create({"name": "Test product 2"}) product_3 = self.product_obj.create({"name": "Test product 3"}) assortment_with_whitelist = self.filter_obj.create( { "name": "Test Assortment 1", "model_id": "product.product", "domain": [], "is_assortment": True, "partner_ids": [(4, self.partner_1.id)], "whitelist_product_ids": [(4, product_1.id)], } ) sale_order_1 = self.sale_order_obj.create({"partner_id": self.partner_1.id}) self.assertEqual( sale_order_1.allowed_product_ids, assortment_with_whitelist.whitelist_product_ids, ) self.assertTrue(sale_order_1.has_allowed_products) self.filter_obj.create( { "name": "Test Assortment 2", "model_id": "product.product", "domain": [], "is_assortment": True, "partner_ids": [(4, self.partner_1.id)], "blacklist_product_ids": [(4, product_2.id)], "partner_domain": "[('id', '=', %s)]" % self.partner_2.id, "apply_black_list_product_domain": True, "black_list_product_domain": [("id", "=", product_3.id)], } ) sale_order_2 = self.sale_order_obj.create({"partner_id": self.partner_1.id}) self.assertNotIn(product_2, sale_order_2.allowed_product_ids) self.assertTrue(sale_order_2.has_allowed_products) sale_order_3 = self.sale_order_obj.create({"partner_id": self.partner_2.id}) self.assertTrue(sale_order_3.has_allowed_products) self.assertNotIn(product_2, sale_order_3.allowed_product_ids) self.assertNotIn(product_3, sale_order_3.allowed_product_ids)
46.490909
2,557
1,425
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Roca # Copyright 2023 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.osv import expression class SaleOrder(models.Model): _inherit = "sale.order" allowed_product_ids = fields.Many2many( comodel_name="product.product", string="Allowed Products", compute="_compute_product_assortment_ids", ) has_allowed_products = fields.Boolean(compute="_compute_product_assortment_ids") @api.depends("partner_id", "partner_shipping_id", "partner_invoice_id") def _compute_product_assortment_ids(self): self.allowed_product_ids = False self.has_allowed_products = False partner_field = ( self.env["ir.config_parameter"] .sudo() .get_param("sale_order_product_assortment.partner_field", "partner_id") ) partner = self[partner_field] product_domain = [] if partner: for ir_filter in partner.applied_assortment_ids: product_domain = expression.AND( [product_domain, ir_filter._get_eval_domain()] ) if product_domain: self.allowed_product_ids = self.env["product.product"].search( product_domain ) self.has_allowed_products = True
37.5
1,425
1,001
py
PYTHON
15.0
# Copyright 2014-2021 Akretion France (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Rental", "version": "15.0.1.0.1", "category": "Sales", "license": "AGPL-3", "summary": "Manage Rental of Products", "author": "Akretion, Sodexis, Odoo Community Association (OCA)", "maintainers": ["alexis-via"], "website": "https://github.com/OCA/sale-workflow", "depends": ["sale_start_end_dates", "sale_stock", "sales_team"], "data": [ "security/ir.model.access.csv", "security/sale_rental_security.xml", "data/rental_data.xml", "views/sale_order.xml", "views/stock_warehouse.xml", "views/sale_rental.xml", "wizard/create_rental_product_view.xml", "views/product.xml", ], "demo": ["demo/rental_demo.xml"], "installable": True, }
35.75
1,001
2,492
py
PYTHON
15.0
from odoo.exceptions import UserError from odoo.tests import Form from odoo.tests.common import TransactionCase class TestSaleRental(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.test_rental_prod = cls.env.ref("sale_rental.rent_product_product_25") cls.test_partner = cls.env["res.partner"].create({"name": "Foo"}) cls.rental_in_loc = cls.env.ref("stock.warehouse0").rental_in_location_id cls.rental_out_loc = cls.env.ref("stock.warehouse0").rental_out_location_id def test_main(self): # Rent a product so_form = Form(self.env["sale.order"]) so_form.partner_id = self.test_partner with so_form.order_line.new() as line: line.product_id = self.test_rental_prod line.start_date = "2022-01-01" line.end_date = "2022-01-10" line.rental_qty = 1 so = so_form.save() sol = so.order_line self.assertEqual(sol.price_subtotal, 60) so.action_confirm() self.assertEqual(len(so.picking_ids), 2) rental_out_pick = so.picking_ids.filtered( lambda p: p.location_id == self.rental_in_loc and p.location_dest_id == self.rental_out_loc ) self.assertTrue(rental_out_pick) rental_in_pick = so.picking_ids.filtered( lambda p: p.location_id == self.rental_out_loc and p.location_dest_id == self.rental_in_loc ) self.assertTrue(rental_in_pick) rental = self.env["sale.rental"].search([("start_order_line_id", "=", sol.id)]) self.assertTrue(rental) # Sell the same product/rental so_form = Form(self.env["sale.order"]) so_form.partner_id = self.test_partner with so_form.order_line.new() as line: line.product_id = self.test_rental_prod.rented_product_id line.product_uom_qty = 1 line.sell_rental_id = rental so = so_form.save() sol = so.order_line # Raises an error because rented product is not sent yet with self.assertRaises(UserError): so.action_confirm() # Confirm the rental delivery and check the return which should # be cancelled rental_out_pick.action_assign() rental_out_pick.action_set_quantities_to_reservation() rental_out_pick.button_validate() so.action_confirm() self.assertEqual(rental_in_pick.state, "cancel")
41.533333
2,492
3,418
py
PYTHON
15.0
# Copyright 2014-2021 Akretion France (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError class CreateRentalProduct(models.TransientModel): _name = "create.rental.product" _description = "Create the Rental Service Product" @api.model def default_get(self, fields_list): res = super().default_get(fields_list) if self.env.context.get("active_model") == "product.product": hw_product = self.env["product.product"].browse( self.env.context["active_id"] ) elif self.env.context.get("active_model") == "product.template": hw_product_tmpl = self.env["product.template"].browse( self.env.context["active_id"] ) assert len(hw_product_tmpl.product_variant_ids) == 1 hw_product = hw_product_tmpl.product_variant_ids else: raise UserError(_("Wrong active_model. Should never happen.")) hw_product = hw_product.with_context(display_default_code=False) res.update( { "hw_product_id": hw_product.id, "name": _("Rental of a {}").format(hw_product.display_name), } ) if hw_product.default_code: res["default_code"] = _("RENT-{}").format(hw_product.default_code) return res hw_product_id = fields.Many2one( "product.product", string="Product to Rent", readonly=True, required=True ) name = fields.Char(string="Rental Service Name", required=True) default_code = fields.Char() sale_price_per_day = fields.Float( string="Rental Price per Day", required=True, digits="Product Price", default=1.0, ) categ_id = fields.Many2one( "product.category", string="Product Category", required=True ) copy_image = fields.Boolean(string="Copy Product Image") @api.model def _prepare_rental_product(self): day_uom_id = self.env.ref("uom.product_uom_day").id vals = { "type": "service", "sale_ok": True, "purchase_ok": False, "uom_id": day_uom_id, "uom_po_id": day_uom_id, "list_price": self.sale_price_per_day, "name": self.name, "default_code": self.default_code, "rented_product_id": self.hw_product_id.id, "must_have_dates": True, "categ_id": self.categ_id.id, "invoice_policy": "order", } if self.copy_image: vals["image_1920"] = self.hw_product_id.image_1920 return vals def create_rental_product(self): self.ensure_one() pp_obj = self.env["product.product"] # check that a rental product doesn't already exists ? product = pp_obj.create(self._prepare_rental_product()) action = { "name": pp_obj._description, "type": "ir.actions.act_window", "res_model": pp_obj._name, "view_mode": "form,tree,kanban", "nodestroy": False, # Close the wizard pop-up "target": "current", "res_id": product.id, } return action
37.56044
3,418
10,321
py
PYTHON
15.0
# Copyright 2014-2021 Akretion France (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import _, api, fields, models from odoo.exceptions import UserError logger = logging.getLogger(__name__) class StockWarehouse(models.Model): _inherit = "stock.warehouse" rental_view_location_id = fields.Many2one( "stock.location", "Parent Rental", check_company=True, domain="[('usage', '=', 'view'), ('company_id', '=', company_id)]", ) rental_in_location_id = fields.Many2one( "stock.location", "Rental In", check_company=True, domain="[('usage', '=', 'internal'), ('company_id', '=', company_id)]", ) rental_out_location_id = fields.Many2one( "stock.location", "Rental Out", check_company=True, domain="[('usage', '=', 'internal'), ('company_id', '=', company_id)]", ) rental_allowed = fields.Boolean() rental_route_id = fields.Many2one("stock.location.route", string="Rental Route") sell_rented_product_route_id = fields.Many2one( "stock.location.route", string="Sell Rented Product Route" ) @api.onchange("rental_allowed") def _onchange_rental_allowed(self): if not self.rental_allowed: self.rental_view_location_id = False self.rental_in_location_id = False self.rental_out_location_id = False self.rental_route_id = False self.sell_rented_product_route_id = False def _get_rental_push_pull_rules(self): self.ensure_one() route_obj = self.env["stock.location.route"] try: rental_route = self.env.ref("sale_rental.route_warehouse0_rental") except Exception: rental_routes = route_obj.search([("name", "=", _("Rent"))]) rental_route = rental_routes and rental_routes[0] or False if not rental_route: raise UserError(_("Can't find any generic 'Rent' route.")) try: sell_rented_product_route = self.env.ref( "sale_rental.route_warehouse0_sell_rented_product" ) except Exception: sell_rented_product_routes = route_obj.search( [("name", "=", _("Sell Rented Product"))] ) sell_rented_product_route = ( sell_rented_product_routes and sell_rented_product_routes[0] or False ) if not sell_rented_product_route: raise UserError(_("Can't find any generic 'Sell Rented Product' route.")) if not self.rental_in_location_id: raise UserError( _( "The Rental Input stock location is not set on the " "warehouse {}" ).format(self.name) ) if not self.rental_out_location_id: raise UserError( _( "The Rental Output stock location is not set on the " "warehouse {}" ).format(self.name) ) rental_pull_rule = { "name": self._format_rulename( self.rental_in_location_id, self.rental_out_location_id, "" ), "location_src_id": self.rental_in_location_id.id, "location_id": self.rental_out_location_id.id, "route_id": rental_route.id, "action": "pull", "picking_type_id": self.out_type_id.id, "warehouse_id": self.id, "company_id": self.company_id.id, } rental_push_rule = { "name": self._format_rulename( self.rental_out_location_id, self.rental_in_location_id, "" ), "location_src_id": self.rental_out_location_id.id, "location_id": self.rental_in_location_id.id, "route_id": rental_route.id, "action": "push", "picking_type_id": self.in_type_id.id, "warehouse_id": self.id, "company_id": self.company_id.id, } customer_loc = self.env.ref("stock.stock_location_customers") sell_rented_product_pull_rule = { "name": self._format_rulename( self.rental_out_location_id, customer_loc, "" ), "location_src_id": self.rental_out_location_id.id, "location_id": customer_loc.id, "route_id": sell_rented_product_route.id, "action": "pull", "picking_type_id": self.out_type_id.id, "warehouse_id": self.id, "company_id": self.company_id.id, } res = [ rental_pull_rule, rental_push_rule, sell_rented_product_pull_rule, ] return res def _create_rental_locations(self): slo = self.env["stock.location"] for wh in self: # create stock locations if not wh.rental_view_location_id: view_loc = slo.with_context(lang="en_US").search( [ ("name", "ilike", "Rental"), ("location_id", "=", wh.view_location_id.id), ("usage", "=", "view"), ("company_id", "=", self.company_id.id), ], limit=1, ) if not view_loc: view_loc = slo.with_context(lang="en_US").create( { "name": "Rental", "location_id": wh.view_location_id.id, "usage": "view", "company_id": self.company_id.id, } ) slo.browse(view_loc.id).name = _("Rental") logger.debug( "New view rental stock location created ID %d", view_loc.id ) wh.rental_view_location_id = view_loc.id if not wh.rental_in_location_id: in_loc = slo.with_context(lang="en_US").search( [ ("name", "ilike", "Rental In"), ("location_id", "=", wh.rental_view_location_id.id), ("company_id", "=", self.company_id.id), ], limit=1, ) if not in_loc: in_loc = slo.with_context(lang="en_US").create( { "name": "Rental In", "location_id": wh.rental_view_location_id.id, "company_id": self.company_id.id, } ) slo.browse(in_loc.id).name = _("Rental In") logger.debug( "New in rental stock location created ID %d", in_loc.id ) wh.rental_in_location_id = in_loc.id if not wh.rental_out_location_id: out_loc = slo.with_context(lang="en_US").search( [ ("name", "ilike", "Rental Out"), ("location_id", "=", wh.rental_view_location_id.id), ("company_id", "=", self.company_id.id), ], limit=1, ) if not out_loc: out_loc = slo.with_context(lang="en_US").create( { "name": "Rental Out", "location_id": wh.rental_view_location_id.id, "company_id": self.company_id.id, } ) slo.browse(out_loc.id).name = _("Rental Out") logger.debug( "New out rental stock location created ID %d", out_loc.id ) wh.rental_out_location_id = out_loc.id def write(self, vals): if "rental_allowed" in vals: rental_route = self.env.ref("sale_rental.route_warehouse0_rental") sell_rented_route = self.env.ref( "sale_rental.route_warehouse0_sell_rented_product" ) if vals.get("rental_allowed"): self._create_rental_locations() self.write( { "route_ids": [(4, rental_route.id)], "rental_route_id": rental_route.id, "sell_rented_product_route_id": sell_rented_route.id, } ) rental_rules = self.env["stock.rule"].search( [ ("route_id", "in", [rental_route.id, sell_rented_route.id]), ("active", "=", False), ] ) if rental_rules: rental_rules.write({"active": True}) else: for rule_vals in self._get_rental_push_pull_rules(): self.env["stock.rule"].create(rule_vals) else: for wh in self: rules_to_archive = self.env["stock.rule"].search( [ ( "route_id", "in", ( wh.rental_route_id.id, wh.sell_rented_product_route_id.id, ), ), ("company_id", "=", wh.company_id.id), ] ) rules_to_archive.write({"active": False}) wh.write( { "route_ids": [(3, rental_route.id)], "rental_route_id": False, "sell_rented_product_route_id": False, } ) return super().write(vals)
41.119522
10,321
14,256
py
PYTHON
15.0
# Copyright 2014-2021 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools import float_compare logger = logging.getLogger(__name__) class SaleOrder(models.Model): _inherit = "sale.order" def action_cancel(self): """ When the user cancels a rental extension, Odoo writes the initial end date on the return picking """ res = super().action_cancel() for order in self: for line in order.order_line.filtered( lambda l: l.rental_type == "rental_extension" and l.extension_rental_id ): initial_end_date = line.extension_rental_id.end_date line.extension_rental_id.in_move_id.write( { "date": initial_end_date, } ) return res class SaleOrderLine(models.Model): _inherit = "sale.order.line" rental = fields.Boolean(default=False) can_sell_rental = fields.Boolean(string="Can Sell from Rental") rental_type = fields.Selection( [("new_rental", "New Rental"), ("rental_extension", "Rental Extension")], readonly=True, states={"draft": [("readonly", False)]}, ) extension_rental_id = fields.Many2one( "sale.rental", string="Rental to Extend", check_company=True, readonly=True, states={"draft": [("readonly", False)]}, ) rental_qty = fields.Float( string="Rental Quantity", digits="Product Unit of Measure", readonly=True, states={"draft": [("readonly", False)]}, help="Indicate the number of items that will be rented.", ) sell_rental_id = fields.Many2one( "sale.rental", string="Rental to Sell", check_company=True, readonly=True, states={"draft": [("readonly", False)]}, ) _sql_constraints = [ ( "rental_qty_positive", "CHECK(rental_qty >= 0)", "The rental quantity must be positive or null.", ) ] @api.constrains( "rental_type", "extension_rental_id", "start_date", "end_date", "rental_qty", "product_uom_qty", "product_id", ) def _check_sale_line_rental(self): for line in self: if line.rental_type == "rental_extension": if not line.extension_rental_id: raise ValidationError( _( "Missing 'Rental to Extend' on the sale order line " "with rental service {}" ).format(line.product_id.display_name) ) if line.rental_qty != line.extension_rental_id.rental_qty: raise ValidationError( _( "On the sale order line with rental service {}, " "you are trying to extend a rental with a rental " "quantity {} that is different from the quantity " "of the original rental {}. This is not supported." ).format( line.product_id.display_name, line.rental_qty, line.extension_rental_id.rental_qty, ) ) if line.rental_type in ("new_rental", "rental_extension"): if not line.product_id.rented_product_id: raise ValidationError( _( "On the 'new rental' sale order line with product " "'{}', we should have a rental service product !" ).format(line.product_id.display_name) ) if line.product_uom_qty != line.rental_qty * line.number_of_days: raise ValidationError( _( "On the sale order line with product '{}' " "the Product Quantity ({}) should be the " "number of days ({}) " "multiplied by the Rental Quantity ({})." ).format( line.product_id.display_name, line.product_uom_qty, line.number_of_days, line.rental_qty, ) ) # the module sale_start_end_dates checks that, when we have # must_have_dates, we have start + end dates elif line.sell_rental_id: if line.product_uom_qty != line.sell_rental_id.rental_qty: raise ValidationError( _( "On the sale order line with product {} " "you are trying to sell a rented product with a " "quantity ({}) that is different from the rented " "quantity ({}). This is not supported." ).format( line.product_id.display_name, line.product_uom_qty, line.sell_rental_id.rental_qty, ) ) def _prepare_rental(self): self.ensure_one() return {"start_order_line_id": self.id} def _prepare_new_rental_procurement_values(self, group=False): vals = { "company_id": self.order_id.company_id, "group_id": group, "sale_line_id": self.id, "date_planned": self.start_date, "route_ids": self.route_id or self.order_id.warehouse_id.rental_route_id, "warehouse_id": self.order_id.warehouse_id or False, "partner_id": self.order_id.partner_shipping_id.id, } return vals def _run_rental_procurement(self, vals): self.ensure_one() procurements = [ self.env["procurement.group"].Procurement( self.product_id.rented_product_id, self.rental_qty, self.product_id.rented_product_id.uom_id, self.order_id.warehouse_id.rental_out_location_id, self.name, self.order_id.name, self.order_id.company_id, vals, ) ] self.env["procurement.group"].run(procurements) def _action_launch_stock_rule(self, previous_product_uom_qty=False): errors = [] for line in self: if line.rental_type == "new_rental" and line.product_id.rented_product_id: group = line.order_id.procurement_group_id if not group: group = self.env["procurement.group"].create( { "name": line.order_id.name, "move_type": line.order_id.picking_policy, "sale_id": line.order_id.id, "partner_id": line.order_id.partner_shipping_id.id, } ) line.order_id.procurement_group_id = group vals = line._prepare_new_rental_procurement_values(group) try: line._run_rental_procurement(vals) except UserError as error: errors.append(error.name) self.env["sale.rental"].create(line._prepare_rental()) elif ( line.rental_type == "rental_extension" and line.product_id.rented_product_id and line.extension_rental_id and line.extension_rental_id.in_move_id ): end_datetime = fields.Datetime.to_datetime(line.end_date) line.extension_rental_id.in_move_id.write( { "date": end_datetime, } ) elif line.sell_rental_id: if line.sell_rental_id.out_move_id.state != "done": raise UserError( _( "Cannot sell the rental {} because it has " "not been delivered" ).format(line.sell_rental_id.display_name) ) line.sell_rental_id.in_move_id._action_cancel() if errors: raise UserError("\n".join(errors)) # call super() at the end, to make procurement_jit work res = super()._action_launch_stock_rule( previous_product_uom_qty=previous_product_uom_qty ) return res def _prepare_procurement_values(self, group_id=False): """ Overriding this function to changethe route on selling rental product """ vals = super()._prepare_procurement_values(group_id=group_id) if self.sell_rental_id: vals.update( {"route_ids": self.order_id.warehouse_id.sell_rented_product_route_id} ) return vals @api.onchange("product_id", "rental_qty") def rental_product_id_change(self): res = {} if self.product_id: if self.product_id.rented_product_id: self.rental = True self.can_sell_rental = False self.sell_rental_id = False if not self.rental_type: self.rental_type = "new_rental" elif ( self.rental_type == "new_rental" and self.rental_qty and self.order_id.warehouse_id ): product_uom = self.product_id.rented_product_id.uom_id warehouse = self.order_id.warehouse_id rental_in_location = warehouse.rental_in_location_id rented_product_ctx = self.with_context( location=rental_in_location.id ).product_id.rented_product_id in_location_available_qty = ( rented_product_ctx.qty_available - rented_product_ctx.outgoing_qty ) compare_qty = float_compare( in_location_available_qty, self.rental_qty, precision_rounding=product_uom.rounding, ) if compare_qty == -1: res["warning"] = { "title": _("Not enough stock !"), "message": _( "You want to rent {:.2f} {} but you only " "have {:.2f} {} currently available on the " "stock location '{}' ! Make sure that you " "get some units back in the mean time or " "re-supply the stock location '{}'." ).format( self.rental_qty, product_uom.name, in_location_available_qty, product_uom.name, rental_in_location.name, rental_in_location.name, ), } elif self.product_id.rental_service_ids: self.can_sell_rental = True self.rental = False self.rental_type = False self.rental_qty = 0 self.extension_rental_id = False else: self.rental_type = False self.rental = False self.rental_qty = 0 self.extension_rental_id = False self.can_sell_rental = False self.sell_rental_id = False else: self.rental_type = False self.rental = False self.rental_qty = 0 self.extension_rental_id = False self.can_sell_rental = False self.sell_rental_id = False return res @api.onchange("extension_rental_id") def extension_rental_id_change(self): if ( self.product_id and self.rental_type == "rental_extension" and self.extension_rental_id ): if self.extension_rental_id.rental_product_id != self.product_id: raise UserError( _( "The Rental Service of the Rental Extension you just " "selected is '{}' and it's not the same as the " "Product currently selected in this Sale Order Line." ).format(self.extension_rental_id.rental_product_id.display_name) ) initial_end_date = self.extension_rental_id.end_date self.start_date = initial_end_date + relativedelta(days=1) self.rental_qty = self.extension_rental_id.rental_qty @api.onchange("sell_rental_id") def sell_rental_id_change(self): if self.sell_rental_id: self.product_uom_qty = self.sell_rental_id.rental_qty @api.onchange("rental_qty", "number_of_days", "product_id") def rental_qty_number_of_days_change(self): if self.product_id.rented_product_id: qty = self.rental_qty * self.number_of_days self.product_uom_qty = qty @api.onchange("rental_type") def rental_type_change(self): if self.rental_type == "new_rental": self.extension_rental_id = False
40.385269
14,256
1,018
py
PYTHON
15.0
# Copyright 2014-2021 Akretion France (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class StockInventory(models.Model): _inherit = "stock.quant" @api.model def create_demo_and_validate(self): rental_in_loc = self.env.ref("stock.warehouse0").rental_in_location_id products = [ ("product.consu_delivery_01", 56), ("product.product_product_20", 46), ("product.product_product_25", 2), ] for (product_xmlid, qty) in products: product = self.env.ref(product_xmlid) self.with_context(inventory_mode=True).create( { "product_id": product.id, "inventory_quantity": qty, "location_id": rental_in_loc.id, } ).action_apply_inventory()
36.357143
1,018
7,411
py
PYTHON
15.0
# Copyright 2014-2021 Akretion France (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import api, fields, models logger = logging.getLogger(__name__) class SaleRental(models.Model): _name = "sale.rental" _description = "Rental" _order = "id desc" @api.depends( "start_order_line_id", "extension_order_line_ids.end_date", "extension_order_line_ids.state", "start_order_line_id.end_date", ) def name_get(self): res = [] for rental in self: name = "[{}] {} - {} > {} ({})".format( rental.partner_id.display_name, rental.rented_product_id.display_name, rental.start_date, rental.end_date, rental._fields["state"].convert_to_export(rental.state, rental), ) res.append((rental.id, name)) return res @api.depends( "sell_order_line_ids.move_ids.state", "start_order_line_id.order_id.state", "start_order_line_id.move_ids.state", "start_order_line_id.move_ids.move_dest_ids.state", ) def _compute_move_and_state(self): for rental in self: in_move = False out_move = False sell_move = False state = False if rental.start_order_line_id: for move in rental.start_order_line_id.move_ids: if move.state != "cancel" and move.picking_code == "outgoing": out_move = move if move.move_dest_ids: out_move = move in_move = move.move_dest_ids[0] if ( rental.sell_order_line_ids and rental.sell_order_line_ids[0].move_ids ): sell_move = rental.sell_order_line_ids[0].move_ids[-1] state = "ordered" if out_move and out_move.state == "done": state = "out" if in_move: if in_move.state == "done": state = "in" elif in_move.state == "cancel" and sell_move: state = "sell_progress" if sell_move.state == "done": state = "sold" elif sell_move: state = "sell_progress" if sell_move.state == "done": state = "sold" elif sell_move.state == "cancel": state = "out" if rental.start_order_line_id.state == "cancel": state = "cancel" rental.in_move_id = in_move rental.out_move_id = out_move rental.state = state rental.sell_move_id = sell_move @api.depends( "extension_order_line_ids.end_date", "extension_order_line_ids.state", "start_order_line_id.end_date", ) def _compute_end_date(self): for rental in self: end_date = False if rental.start_order_line_id: end_date = rental.start_order_line_id.end_date for extension in rental.extension_order_line_ids: if ( extension.state in ("sale", "done") and end_date and extension.end_date and extension.end_date > end_date ): end_date = extension.end_date rental.end_date = end_date start_order_line_id = fields.Many2one( "sale.order.line", string="Rental SO Line", readonly=True ) start_date = fields.Date( related="start_order_line_id.start_date", readonly=True, store=True ) rental_product_id = fields.Many2one( "product.product", related="start_order_line_id.product_id", string="Rental Service", readonly=True, store=True, ) rented_product_id = fields.Many2one( "product.product", related="start_order_line_id.product_id.rented_product_id", string="Rented Product", readonly=True, store=True, ) rental_qty = fields.Float( related="start_order_line_id.rental_qty", readonly=True, store=True ) start_order_id = fields.Many2one( "sale.order", related="start_order_line_id.order_id", string="Rental SO", readonly=True, store=True, ) company_id = fields.Many2one( "res.company", related="start_order_line_id.company_id", string="Company", readonly=True, store=True, ) partner_id = fields.Many2one( "res.partner", related="start_order_line_id.order_id.partner_id", string="Customer", readonly=True, store=True, ) out_move_id = fields.Many2one( "stock.move", compute="_compute_move_and_state", string="Outgoing Move", readonly=True, store=True, ) in_move_id = fields.Many2one( "stock.move", compute="_compute_move_and_state", string="Incoming Move", readonly=True, store=True, ) out_state = fields.Selection( related="out_move_id.state", string="Out Move State", readonly=True ) in_state = fields.Selection( related="in_move_id.state", string="In Move State", readonly=True ) out_picking_id = fields.Many2one( "stock.picking", related="out_move_id.picking_id", string="Delivery Order", readonly=True, ) in_picking_id = fields.Many2one( "stock.picking", related="in_move_id.picking_id", string="Receipt", readonly=True, ) extension_order_line_ids = fields.One2many( "sale.order.line", "extension_rental_id", string="Rental Extensions", readonly=True, ) sell_order_line_ids = fields.One2many( "sale.order.line", "sell_rental_id", string="Sell Rented Product", readonly=True ) sell_move_id = fields.Many2one( "stock.move", compute="_compute_move_and_state", string="Selling Move", readonly=True, store=True, ) sell_state = fields.Selection( related="sell_move_id.state", string="Sell Move State", readonly=True ) sell_picking_id = fields.Many2one( "stock.picking", related="sell_move_id.picking_id", string="Sell Delivery Order", readonly=True, ) end_date = fields.Date( compute="_compute_end_date", store=True, help="End Date of the Rental (extensions included), \ taking into account all the extensions sold to the customer.", ) state = fields.Selection( [ ("ordered", "Ordered"), ("out", "Out"), ("sell_progress", "Sell in progress"), ("sold", "Sold"), ("in", "Back In"), ("cancel", "Cancelled"), ], compute="_compute_move_and_state", readonly=True, store=True, )
33.084821
7,411
3,349
py
PYTHON
15.0
# Copyright 2014-2021 Akretion France (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ProductProduct(models.Model): _inherit = "product.product" # Link rental service -> rented HW product rented_product_id = fields.Many2one( "product.product", string="Related Rented Product", domain=[("type", "in", ("product", "consu"))], ) # Link rented HW product -> rental service rental_service_ids = fields.One2many( "product.product", "rented_product_id", string="Related Rental Services" ) @api.constrains("rented_product_id", "must_have_dates", "type", "uom_id") def _check_rental(self): day_uom = self.env.ref("uom.product_uom_day") for product in self: if product.rented_product_id: if product.type != "service": raise ValidationError( _("The rental product '{}' must be of type 'Service'.").format( product.name ) ) if not product.must_have_dates: raise ValidationError( _( "The rental product '{}' must have the option " "'Must Have Start and End Dates' checked." ).format(product.name) ) # In the future, we would like to support all time UoMs # but it is more complex and requires additionnal developments if product.uom_id != day_uom: raise ValidationError( _( "The unit of measure of the rental product '{}' must " "be 'Day'." ).format(product.name) ) class ProductTemplate(models.Model): _inherit = "product.template" rented_product_tmpl_id = fields.Many2one( "product.template", compute="_compute_rented_product_tmpl_id", string="Rented Product", inverse="_inverse_rented_product_tmpl_id", store=True, ) rental_service_tmpl_ids = fields.One2many( "product.template", "rented_product_tmpl_id", string="Rental Services" ) @api.depends("product_variant_ids", "product_variant_ids.rented_product_id") def _compute_rented_product_tmpl_id(self): unique_variants = self.filtered( lambda template: len(template.product_variant_ids) == 1 ) for template in unique_variants: template.rented_product_tmpl_id = ( template.product_variant_ids.rented_product_id.product_tmpl_id.id ) for template in self - unique_variants: template.rented_product_tmpl_id = False def _inverse_rented_product_tmpl_id(self): for template in self: if len(template.product_variant_ids) == 1: template.product_variant_ids.rented_product_id = ( template.rented_product_tmpl_id.product_variant_ids[0].id )
39.869048
3,349
1,006
py
PYTHON
15.0
# Copyright 2014-2021 Akretion France (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2016-2021 Sodexis (http://sodexis.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class StockRule(models.Model): _inherit = "stock.rule" def _push_prepare_move_copy_values(self, move_to_copy, new_date): """Inherit to write the end date of the rental on the return move""" res = super()._push_prepare_move_copy_values(move_to_copy, new_date) location_id = res.get("location_id", False) if ( location_id and location_id == move_to_copy.warehouse_id.rental_out_location_id.id and move_to_copy.sale_line_id and move_to_copy.sale_line_id.rental_type == "new_rental" ): rental_end_date = move_to_copy.sale_line_id.end_date res["date"] = fields.Datetime.to_datetime(rental_end_date) return res
41.916667
1,006
704
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Product Supplierinfo for Customers Elaboration", "summary": "Allows to define default elaborations and elaboration notes on product" " customerinfos", "version": "15.0.2.0.1", "development_status": "Beta", "author": "Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "category": "Sales Management", "license": "AGPL-3", "depends": ["product_supplierinfo_for_customer_sale", "sale_elaboration"], "data": ["security/ir.model.access.csv", "views/product_views.xml"], "installable": True, }
44
704
308
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): openupgrade.rename_columns( env.cr, {"product_customerinfo": [("elaboration_id", None)]} )
28
308
403
py
PYTHON
15.0
# Copyright 2023 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): openupgrade.m2o_to_x2m( env.cr, env["product.customerinfo"], "product_customerinfo", "elaboration_ids", openupgrade.get_legacy_name("elaboration_id"), )
25.1875
403
2,963
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo.tests.common import Form, TransactionCase class TestCustomerinfoElaboration(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.customer0 = cls.env["res.partner"].create({"name": "Test partner 0"}) cls.customer1 = cls.env["res.partner"].create( {"name": "Test partner 1", "parent_id": cls.customer0.id} ) cls.customer2 = cls.env["res.partner"].create({"name": "Test partner 2"}) cls.product = cls.env["product.product"].create({"name": "Product test"}) cls.product_elab = cls.env["product.product"].create( {"name": "Elaboration prod. test", "type": "service"} ) cls.elaboration = cls.env["product.elaboration"].create( {"name": "Test elaboration", "product_id": cls.product_elab.id} ) cls.customer_info = cls.env["product.customerinfo"].create( { "name": cls.customer0.id, "product_tmpl_id": cls.product.product_tmpl_id.id, "elaboration_ids": [(4, cls.elaboration.id)], "elaboration_note": "Test elaboration note", } ) def _create_sale(self, partner): so_form = Form(self.env["sale.order"]) so_form.partner_id = partner with so_form.order_line.new() as ol_form: ol_form.product_id = self.product return so_form.save() def test_sale_without_elaboration(self): so = self._create_sale(self.customer2) line = so.order_line self.assertFalse(line.elaboration_ids) self.assertFalse(line.elaboration_note) def test_sale_direct_customerinfo_with_elaboration(self): so = self._create_sale(self.customer0) line = so.order_line self.assertEqual(line.elaboration_ids, self.elaboration) self.assertEqual(line.elaboration_note, "Test elaboration note") def test_sale_parent_customerinfo_with_elaboration(self): so = self._create_sale(self.customer1) line = so.order_line self.assertEqual(line.elaboration_ids, self.elaboration) self.assertEqual(line.elaboration_note, "Test elaboration note") def test_multiple_elaboration_per_customer(self): product_elab_2 = self.env["product.product"].create( {"name": "Elaboration prod. test 2", "type": "service"} ) elaboration_2 = self.env["product.elaboration"].create( {"name": "Test elaboration 2", "product_id": product_elab_2.id} ) self.customer_info.elaboration_ids += elaboration_2 so = self._create_sale(self.customer0) line = so.order_line self.assertEqual(line.elaboration_ids, self.elaboration | elaboration_2) self.assertEqual(line.elaboration_note, "Test elaboration, Test elaboration 2")
43.573529
2,963
623
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ProductCustomerInfo(models.Model): _inherit = "product.customerinfo" elaboration_ids = fields.Many2many(comodel_name="product.elaboration") elaboration_note = fields.Char( store=True, compute="_compute_elaboration_note", readonly=False, ) @api.depends("elaboration_ids") def _compute_elaboration_note(self): for line in self: line.elaboration_note = ", ".join(line.elaboration_ids.mapped("name"))
32.789474
623
1,823
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Carlos Roca # Copyright 2023 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" elaboration_ids = fields.Many2many( comodel_name="product.elaboration", compute="_compute_elaboration_ids", store=True, readonly=False, string="Elaborations", ) @api.depends("product_id") def _compute_elaboration_ids(self): for line in self: customer_info = line._get_product_customer_info() if customer_info: line.elaboration_ids = customer_info.elaboration_ids def _compute_elaboration_note(self): res = super()._compute_elaboration_note() for line in self: customer_info = line._get_product_customer_info() if ( customer_info and line.elaboration_ids and ( # Comparing with ids because comparison with newId doesn't work line.elaboration_ids.ids == customer_info.elaboration_ids.ids or not line.elaboration_ids ) ): line.elaboration_note = customer_info.elaboration_note return res def _get_product_customer_info(self): customerinfo = self.product_id.customer_ids.filtered( lambda pc: pc.elaboration_ids and pc.name == self.order_id.partner_id )[:1] if not customerinfo: customerinfo = self.product_id.customer_ids.filtered( lambda pc: pc.elaboration_ids and pc.name == self.order_id.partner_id.commercial_partner_id )[:1] return customerinfo
35.745098
1,823
612
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Sale Credit Points", "version": "15.0.1.0.1", "category": "Sales", "license": "AGPL-3", "author": "Camptocamp, Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "depends": [ "sale", ], "data": [ "security/groups.xml", "security/ir.model.access.csv", "data/res_currency.xml", "views/partner.xml", "views/point_history.xml", "wizards/manage_credit_point.xml", ], }
27.818182
612
2,326
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import exceptions from odoo.tests.common import TransactionCase class TestWizard(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = ( cls.env["res.partner"] .with_context(tracking_disable=True) .create({"name": "John Wizard"}) ) cls.wiz_model = cls.env["wiz.manage.credit.point"] def _get_wiz(self, need_write=True, **kw): vals = {"partner_ids": [(6, 0, self.partner.ids)]} vals.update(**kw) if need_write: method = self.wiz_model.create else: method = self.wiz_model.new return method(vals) def _test_message(self, msg): self.assertIn(msg, self.partner.message_ids[0].body) def test_defaults(self): wiz = self._get_wiz(need_write=False) self.assertIn(self.partner.id, wiz.partner_ids.ids) def test_no_comment(self): wiz = self._get_wiz( need_write=False, operation="replace", credit_point=0, ) with self.assertRaises(exceptions.UserError): wiz.action_update_credit() def test_credit_replace(self): msg = "I have money dude!" wiz = self._get_wiz( operation="replace", credit_point=100, comment=msg, ) wiz.action_update_credit() self.assertEqual(self.partner.credit_point, 100) self._test_message(msg) def test_credit_increase(self): self.partner.credit_point = 10 msg = "I have more money dude!" wiz = self._get_wiz( operation="increase", credit_point=10, comment=msg, ) wiz.action_update_credit() self.assertEqual(self.partner.credit_point, 20) self._test_message(msg) def test_credit_decrease(self): self.partner.credit_point = 10 msg = "I have less money dude!" wiz = self._get_wiz( operation="decrease", credit_point=10, comment=msg, ) wiz.action_update_credit() self.assertEqual(self.partner.credit_point, 0) self._test_message(msg)
30.207792
2,326
2,228
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestHistory(TransactionCase): def setUp(self): super().setUp() self.history_model = self.env["credit.point.history"] self.partner = ( self.env["res.partner"] .with_context(tracking_disable=True) .create({"name": "John Wizard"}) ) self.wiz_model = self.env["wiz.manage.credit.point"] self.wiz_vals = [ {"operation": "increase", "credit_point": 15, "comment": "test"}, {"operation": "increase", "credit_point": 25, "comment": "test"}, {"operation": "replace", "credit_point": 15, "comment": "test"}, {"operation": "decrease", "credit_point": 5, "comment": "test"}, { "operation": "decrease", "credit_point": 5, "comment": "test", }, ] def _run_wiz(self): for vals in self.wiz_vals: vals.update({"partner_ids": [(6, 0, self.partner.ids)]}) wiz = self.wiz_model.create(vals) wiz.action_update_credit() def test_history_creation(self): self._run_wiz() history = self.history_model.sudo().search([]) self.assertEqual(len(history), len(self.wiz_vals)) def test_yearly_credit_increase(self): self._run_wiz() history = self.history_model.sudo().search([]) history = history.filtered( lambda x: x.operation == "increase" and x.partner_id == self.partner ) self.assertEqual(len(history), 2) self.assertEqual( self.partner.yearly_point_increase, sum(history.mapped("amount")) ) self.env.cr.execute( "update credit_point_history set " "create_date='1994-10-03 10:00:00' where id=%s", (history[0].id,), ) self.partner._compute_yearly_point_increase() self.assertNotEqual( self.partner.yearly_point_increase, sum(history.mapped("amount")) ) self.assertEqual(self.partner.yearly_point_increase, history[1].amount)
37.762712
2,228
2,907
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import exceptions from odoo.tests.common import TransactionCase class TestCredit(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = ( cls.env["res.partner"] .with_context(tracking_disable=True) .create({"name": "John Wizard"}) ) cls.currency = cls.env.ref("sale_credit_point.res_currency_pt") def test_default_currency(self): self.assertEqual(self.partner.credit_point_currency_id, self.currency) def test_default_credit(self): self.assertEqual(self.partner.credit_point, 0) def test_credit_replace(self): self.partner.credit_point = 10 self.partner.credit_point_replace(100) self.assertEqual(self.partner.credit_point, 100) def test_credit_increase(self): self.partner.credit_point = 10 self.partner.credit_point_increase(25) self.assertEqual(self.partner.credit_point, 35) def test_credit_decrease(self): self.partner.credit_point = 10 self.partner.credit_point_decrease(5) self.assertEqual(self.partner.credit_point, 5) def _test_message(self, msg): self.assertIn(msg, self.partner.message_ids[0].body) def test_credit_replace_with_message(self): self.partner.credit_point = 10 msg = "Wrong amount dude!" self.partner.credit_point_replace(100, comment=msg) self.assertEqual(self.partner.credit_point, 100) self._test_message(msg) def test_credit_increase_with_message(self): self.partner.credit_point = 10 msg = "I have money dude!" self.partner.credit_point_increase(25, comment=msg) self.assertEqual(self.partner.credit_point, 35) self._test_message(msg) def test_credit_decrease_with_message(self): self.partner.credit_point = 10 msg = "I less money dude!" self.partner.credit_point_decrease(5, comment=msg) self.assertEqual(self.partner.credit_point, 5) self._test_message(msg) def test_credit_cannot_be_negative(self): self.partner.credit_point = 10 with self.assertRaises(exceptions.ValidationError): self.partner.credit_point_decrease(20) def test_credit_negative_bypass_flag(self): self.partner.credit_point = 10 self.partner.with_context(skip_credit_check=True).credit_point_decrease(20) self.assertEqual(self.partner.credit_point, -10) def test_credit_negative_bypass_group(self): self.env.user.groups_id |= self.env.ref( "sale_credit_point.group_manage_credit_point" ) self.partner.credit_point = 10 self.partner.credit_point_decrease(20) self.assertEqual(self.partner.credit_point, -10)
36.3375
2,907
4,161
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import exceptions from odoo.tests.common import tagged from odoo.addons.sale.tests.common import TestSaleCommon @tagged("post_install", "-at_install") class TestSaleOrder(TestSaleCommon): def setUp(self): super().setUp() self.product = self.product_a self.product.list_price = 10 self.product.currency_id = self.env[ "res.partner" ]._default_credit_point_currency_id() self.portal_user = self.env.ref("base.demo_user0").sudo() self.portal_user.partner_id.credit_point = 0 def _create_so(self): self.product = self.product_a self.product.taxes_id = False vals = { "partner_id": self.partner_a.id, "order_line": [ ( 0, 0, { "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 1, "product_uom": self.product.uom_id.id, "price_unit": self.product.list_price, }, ) ], } so = self.env["sale.order"].create(vals) return so.with_context(test_sale_credit_point=True) def test_so_confirm_ok(self): so = self._create_so() so.partner_id.credit_point = 100 self.assertEqual(so.state, "draft") so.action_confirm() self.assertNotEqual(so.state, "draft") self.assertEqual(so.partner_id.credit_point, 90) def test_so_confirm_not_enough_credit(self): so = self._create_so() so.partner_id.credit_point = 0 self.assertEqual(so.state, "draft") with self.assertRaises(exceptions.UserError): so.action_confirm() def test_so_confirm_not_enough_credit_bypass_flag(self): so = self._create_so() so.partner_id.credit_point = 0 self.assertEqual(so.state, "draft") so.with_context(skip_credit_check=True).action_confirm() self.assertNotEqual(so.state, "draft") self.assertEqual(so.partner_id.credit_point, -10) def test_so_confirm_not_enough_credit_bypass_group(self): so = self._create_so() so.partner_id.credit_point = 0 self.assertEqual(so.state, "draft") self.env.user.groups_id |= self.env.ref( "sale_credit_point.group_manage_credit_point" ) so.action_confirm() self.assertNotEqual(so.state, "draft") self.assertEqual(so.partner_id.credit_point, -10) def test_so_cancel_ok(self): so = self._create_so() so.partner_id.credit_point = 100 so.action_confirm() self.assertEqual(so.state, "sale") self.assertEqual(so.partner_id.credit_point, 90) so.action_cancel() self.assertEqual(so.state, "cancel") self.assertEqual(so.partner_id.credit_point, 100) # Test if SO is still in draft so2 = self._create_so() so2.partner_id.credit_point = 100 self.assertEqual(so2.state, "draft") self.assertEqual(so2.partner_id.credit_point, 100) so2.action_cancel() self.assertEqual(so2.state, "cancel") self.assertEqual(so2.partner_id.credit_point, 100) def test_so_credit_check_user(self): so = self._create_so() self.env.user.groups_id = [ (4, self.env.ref("sale_credit_point.group_manage_credit_point").id) ] so.partner_id.credit_point = 0 with self.assertRaises(exceptions.AccessError): # portal user doesn't have the rights # this is handled by record rules so.with_user(self.portal_user.id).credit_point_check() with self.assertRaises(exceptions.UserError): # nor can handle it via sudo with passing of the user so.sudo().credit_point_check(self.portal_user) # admin still can confirm it without check self.assertTrue(so.sudo().credit_point_check() is None)
37.827273
4,161
2,331
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, models, tools from odoo.exceptions import UserError class SaleOrder(models.Model): _inherit = "sale.order" def credit_point_check(self, user=None): """Verify order amount against credit point budget.""" # Introduced this check as from website sale_orders are created # from admin. If admin is in manage_credits group - all users will # bypass check. This way, we can check specific user from request if not user: user = self.env.user self.ensure_one() if not self.partner_id.with_user(user.id).credit_point_bypass_check(): if self.amount_total > self.partner_id.credit_point: raise UserError(self.credit_point_check_failed_msg) @property def credit_point_check_failed_msg(self): msg = _( "Sale Order amount total ({amount}) is higher" " than your available credit ({points})." ) return msg.format(amount=self.amount_total, points=self.partner_id.credit_point) @property def credit_point_decrease_msg(self): return _("SO %s") % self.name def action_confirm(self): """Check credit before confirmation, update credit if check passed.""" install_module = tools.config.get("init") # At installation, odoo core demo data is calling on SO. # It was leading to an error related to this module, as the demo # partner didn't had any credit point is_running = ( not tools.config.get("test_enable") and "sale_credit_point" not in install_module ) if is_running or self._context.get("test_sale_credit_point"): for sale in self: sale.credit_point_check() sale.partner_id.credit_point_decrease( sale.amount_total, comment=self.credit_point_decrease_msg ) return super().action_confirm() def action_cancel(self): for sale in self: if sale.state == "sale": sale.partner_id.credit_point_increase( sale.amount_total, _("Sale Order canceled") ) return super().action_cancel()
38.85
2,331
3,535
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, exceptions, fields, models class ResPartner(models.Model): _inherit = "res.partner" credit_point = fields.Monetary( string="Points Attribution", currency_field="credit_point_currency_id", readonly=True, default=0, ) yearly_point_increase = fields.Monetary( string="Yearly points increase", currency_field="credit_point_currency_id", readonly=True, compute="_compute_yearly_point_increase", ) credit_history_ids = fields.One2many( comodel_name="credit.point.history", inverse_name="partner_id", ) credit_point_currency_id = fields.Many2one( comodel_name="res.currency", default=lambda self: self._default_credit_point_currency_id(), ) def _default_credit_point_currency_id(self): curr = self.env.ref( "sale_credit_point.res_currency_pt", raise_if_not_found=False ) return curr.id if curr else None def credit_point_bypass_check(self): group = "sale_credit_point.group_manage_credit_point" return self.user_has_groups(group) or self.env.context.get("skip_credit_check") @api.constrains("credit_point") def _check_credit_point(self): for partner in self: if partner.credit_point < 0 and not partner.credit_point_bypass_check(): raise exceptions.ValidationError( _("You can't set a credit point lower than 0") ) def action_update_credit_point(self): """Open update credit point wizard.""" self.ensure_one() return { "type": "ir.actions.act_window", "res_model": "wiz.manage.credit.point", "src_model": "res.partner", "view_mode": "form", "target": "new", "context": {"default_partner_ids": self.ids}, } def _credit_point_update(self, amount, comment=""): self.credit_point = amount if comment: msg = _("Credit updated to {points}. Reason: {comment}") self.message_post( body=msg.format(points=self.credit_point, comment=comment) ) def credit_point_replace(self, amount, comment=""): self._credit_point_update(amount, comment=comment) def credit_point_increase(self, amount, comment=""): self._credit_point_update(self.credit_point + amount, comment=comment) def credit_point_decrease(self, amount, comment=""): self._credit_point_update(self.credit_point - amount, comment=comment) def update_history(self, amount, operation, comment): history_model = self.env["credit.point.history"] vals = { "partner_id": self.id, "operation": operation, "amount": amount, "comment": comment, } return history_model.create(vals) def _compute_yearly_point_increase(self): self.env.cr.execute( """select partner_id, sum(amount) from credit_point_history where operation='increase' and partner_id in %s and date_part('year', create_date)=date_part('year', CURRENT_DATE) group by partner_id""", (tuple(self.ids),), ) amounts = dict(self.env.cr.fetchall()) for record in self: record.yearly_point_increase = amounts.get(record.id, 0)
36.071429
3,535
963
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models POINT_OPERATIONS = [ ("replace", "Replace"), ("increase", "Increase"), ("decrease", "Decrease"), ] class PointHistory(models.Model): _name = "credit.point.history" _description = "CreditPointHistory" _rec_name = "partner_id" partner_id = fields.Many2one( comodel_name="res.partner", string="Partner", required=True, ) operation = fields.Selection( selection=POINT_OPERATIONS, required=True, ) amount = fields.Monetary( currency_field="credit_point_currency_id", readonly=True, default=0, required=True, ) credit_point_currency_id = fields.Many2one( related="partner_id.credit_point_currency_id", readonly=True, ) create_date = fields.Datetime() comment = fields.Char()
25.342105
963
1,179
py
PYTHON
15.0
# Copyright 2018-2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, exceptions, fields, models from ..models.point_history import POINT_OPERATIONS class ManageCreditPoint(models.TransientModel): _name = "wiz.manage.credit.point" _description = "Wizard to Manage Credit Points" credit_point = fields.Integer( string="Points", required=True, ) partner_ids = fields.Many2many( "res.partner", string="Partners", required=True, ) comment = fields.Text( required=True, ) operation = fields.Selection( string="Type of operation", selection=POINT_OPERATIONS, required=True, ) def action_update_credit(self): self.ensure_one() if not self.comment: raise exceptions.UserError(_("A comment is needed to the update credit")) for partner in self.partner_ids: handler = getattr(partner, "credit_point_" + self.operation) handler(self.credit_point, comment=self.comment) partner.update_history(self.credit_point, self.operation, self.comment)
31.026316
1,179
537
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Partner Sale Pivot", "summary": "Sales analysis from customer form view", "version": "15.0.1.0.0", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "maintainers": ["ernestotejeda"], "license": "AGPL-3", "depends": ["sale"], "data": ["views/sale_report_views.xml", "views/res_partner_views.xml"], }
38.357143
537
734
py
PYTHON
15.0
# Copyright 2013-2014 Camptocamp SA - Guewen Baconnier # © 2016-17 Eficent Business and IT Consulting Services S.L. # © 2016 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Sale Sourced by Line", "summary": "Multiple warehouse source locations for Sale order", "version": "15.0.1.1.0", "author": "Camptocamp," "Eficent," "SerpentCS," "Info a tout prix," "Odoo Community Association (OCA)", "category": "Warehouse", "license": "AGPL-3", "website": "https://github.com/OCA/sale-workflow", "depends": [ "sale_procurement_group_by_line", ], "data": ["view/sale_view.xml"], "installable": True, }
31.826087
732
4,879
py
PYTHON
15.0
# Copyright 2013-2014 Camptocamp SA - Guewen Baconnier # © 2016 Eficent Business and IT Consulting Services S.L. # © 2016 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestSaleSourcedByLine(TransactionCase): def setUp(self): super(TestSaleSourcedByLine, self).setUp() self.sale_order_model = self.env["sale.order"] self.sale_order_line_model = self.env["sale.order.line"] self.stock_move_model = self.env["stock.move"] self.stock_warehouse_model = self.env["stock.warehouse"] # Refs self.customer = self.env.ref("base.res_partner_2") self.product_1 = self.env.ref("product.product_product_27") self.product_2 = self.env.ref("product.product_product_24") self.warehouse0 = self.env.ref("stock.warehouse0") self.warehouse1 = self.stock_warehouse_model.create( {"name": "Test Warehouse", "code": "TWH"} ) def test_sales_order_multi_source(self): so = self.sale_order_model.create( { "partner_id": self.customer.id, } ) self.sale_order_line_model.create( { "product_id": self.product_1.id, "product_uom_qty": 8, "warehouse_id": self.warehouse1.id, "order_id": so.id, } ) self.sale_order_line_model.create( { "product_id": self.product_2.id, "product_uom_qty": 8, "warehouse_id": self.warehouse0.id, "order_id": so.id, } ) # confirm quotation so.action_confirm() self.assertEqual( len(so.picking_ids), 2, "2 delivery orders expected. Got %s instead" % len(so.picking_ids), ) for line in so.order_line: self.assertEqual( line.procurement_group_id.name, line.order_id.name + "/" + line.warehouse_id.name, "The name of the procurement group is not " "correct.", ) moves = self.stock_move_model.search( [("group_id", "=", line.procurement_group_id.id)] ) for move in moves: self.assertEqual( move.group_id, line.procurement_group_id, "The group in the stock move does not " "match with the procurement group in " "the sales order line.", ) self.assertEqual( move.picking_id.group_id, line.procurement_group_id, "The group in the stock picking does " "not match with the procurement group " "in the sales order line.", ) def test_sales_order_no_source(self): so = self.sale_order_model.create( { "partner_id": self.customer.id, "warehouse_id": self.warehouse1.id, } ) self.sale_order_line_model.create( {"product_id": self.product_1.id, "product_uom_qty": 8, "order_id": so.id} ) self.sale_order_line_model.create( {"product_id": self.product_2.id, "product_uom_qty": 8, "order_id": so.id} ) # confirm quotation so.action_confirm() self.assertEqual( len(so.picking_ids), 1, "1 delivery order expected. Got %s instead" % len(so.picking_ids), ) def test_sale_order_source(self): so = self.sale_order_model.create( { "partner_id": self.customer.id, } ) self.sale_order_line_model.create( { "product_id": self.product_1.id, "product_uom_qty": 8, "warehouse_id": self.warehouse1.id, "order_id": so.id, } ) self.sale_order_line_model.create( { "product_id": self.product_2.id, "product_uom_qty": 8, "warehouse_id": self.warehouse0.id, "order_id": so.id, } ) # confirm quotation so.action_confirm() for line in so.order_line: moves = self.stock_move_model.search( [("group_id", "=", line.procurement_group_id.id)] ) for move in moves: self.assertEqual( move.warehouse_id, line.warehouse_id, "The warehouse in the stock move does not " "match with the Sales order line.", )
36.125926
4,877
2,496
py
PYTHON
15.0
# Copyright 2013-2014 Camptocamp SA - Guewen Baconnier # © 2016 Eficent Business and IT Consulting Services S.L. # © 2016 Serpent Consulting Services Pvt. Ltd. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class SaleOrder(models.Model): _inherit = "sale.order" warehouse_id = fields.Many2one( "stock.warehouse", string="Default Warehouse", readonly=True, states={"draft": [("readonly", False)], "sent": [("readonly", False)]}, help="If no source warehouse is selected on line, " "this warehouse is used as default. ", ) class SaleOrderLine(models.Model): _inherit = "sale.order.line" warehouse_id = fields.Many2one( "stock.warehouse", "Source Warehouse", readonly=True, related="", states={"draft": [("readonly", False)], "sent": [("readonly", False)]}, help="If a source warehouse is selected, " "it will be used to define the route. " "Otherwise, it will get the warehouse of " "the sale order", ) def _prepare_procurement_group_vals(self): vals = super(SaleOrderLine, self)._prepare_procurement_group_vals() # for compatibility with sale_quotation_sourcing if self._get_procurement_group_key()[0] == 10: if self.warehouse_id: vals["name"] += "/" + self.warehouse_id.name return vals def _prepare_procurement_values(self, group_id=False): """Prepare specific key for moves or other components that will be created from a stock rule comming from a sale order line. This method could be override in order to add other custom key that could be used in move/po creation. """ values = super(SaleOrderLine, self)._prepare_procurement_values(group_id) self.ensure_one() if self.warehouse_id: values["warehouse_id"] = self.warehouse_id return values def _get_procurement_group_key(self): """Return a key with priority to be used to regroup lines in multiple procurement groups """ priority = 10 key = super(SaleOrderLine, self)._get_procurement_group_key() # Check priority if key[0] >= priority: return key wh_id = ( self.warehouse_id.id if self.warehouse_id else self.order_id.warehouse_id.id ) return priority, wh_id
34.638889
2,494
574
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Stock Return Request", "version": "15.0.1.0.0", "category": "Stock", "website": "https://github.com/OCA/sale-workflow", "development_status": "Beta", "author": "Tecnativa, Odoo Community Association (OCA)", "maintainers": ["chienandalu"], "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale_stock", "stock_return_request"], "data": ["views/sale_return_request_views.xml"], }
35.875
574
7,870
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.addons.stock_return_request.tests.test_stock_return_request_common import ( StockReturnRequestCase, ) class SaleReturnRequestCase(StockReturnRequestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner_customer_2 = cls.env["res.partner"].create( { "name": "Mr. Sale", "property_stock_supplier": cls.supplier_loc.id, "property_stock_customer": cls.customer_loc.id, } ) cls.wh1.delivery_route_id.rule_ids.location_id = cls.customer_loc.id cls.so_1 = cls.env["sale.order"].create( { "partner_id": cls.partner_customer_2.id, "warehouse_id": cls.wh1.id, "picking_policy": "direct", "order_line": [ ( 0, False, { "product_id": cls.prod_3.id, "name": cls.prod_3.name, "product_uom_qty": 14.0, "price_unit": 10.0, "product_uom": cls.prod_3.uom_id.id, }, ), ], } ) cls.so_2 = cls.so_1.copy() cls.sale_orders = cls.so_1 | cls.so_2 # Confirm all the sale orders for order in cls.sale_orders: order.action_confirm() # Adjust quants to avoid reservation quircks quant_lot_1 = cls.env["stock.quant"].search( [ ("product_id", "=", cls.prod_3.id), ("lot_id", "=", cls.prod_3_lot1.id), ("location_id", "=", cls.wh1.lot_stock_id.id), ] ) quant_lot_2 = cls.env["stock.quant"].search( [ ("product_id", "=", cls.prod_3.id), ("lot_id", "=", cls.prod_3_lot2.id), ("location_id", "=", cls.wh1.lot_stock_id.id), ] ) quant_lot_1.reserved_quantity = 90.0 quant_lot_2.reserved_quantity = 10.0 # Deliver products. For each picking: # 10 units of TSTPROD3LOT0001 -> -20 units of 90 already existing # 2 units of TSTPROD3LOT0002 -> -4 units of 10 already existing for picking in cls.sale_orders.mapped("picking_ids"): for ml in picking.move_line_ids: ml.write( { "lot_id": cls.prod_3_lot1.id, "product_uom_qty": 0.0, "qty_done": 10.0, } ) ml.create( { "move_id": ml.move_id.id, "picking_id": ml.picking_id.id, "location_id": ml.location_id.id, "location_dest_id": ml.location_dest_id.id, "product_uom_id": ml.product_uom_id.id, "product_id": cls.prod_3.id, "product_uom_qty": 0.0, "lot_id": cls.prod_3_lot2.id, "qty_done": 4.0, } ) picking.button_validate() quant_lot_1.reserved_quantity = quant_lot_2.reserved_quantity = 0.0 def test_01_return_sale_stock_from_customer(self): """Return stock from customer and the corresponding sales will be ready for refund""" self.return_request_customer.write( { "partner_id": self.partner_customer_2.id, "to_refund": True, "line_ids": [ ( 0, 0, { "product_id": self.prod_3.id, "lot_id": self.prod_3_lot1.id, "quantity": 12.0, }, ), ( 0, 0, { "product_id": self.prod_3.id, "lot_id": self.prod_3_lot2.id, "quantity": 4.0, }, ), ], } ) self.return_request_customer.action_confirm() sale_orders = self.return_request_customer.sale_order_ids pickings = self.return_request_customer.returned_picking_ids moves = self.return_request_customer.returned_picking_ids.mapped("move_lines") # For lot TSTPROD3LOT0001 we'll be returning: # ==> 10 units from SO01 # ==> 2 units from SO02 # For lot TSTPROD3LOT0002 we'll be returning: # ==> 4 units from SO01 self.assertEqual(len(sale_orders), 2) self.assertEqual(len(pickings), 2) # Two moves with two move lines each self.assertEqual(len(moves), 2) self.assertAlmostEqual(sum(moves.mapped("product_uom_qty")), 16.0) # Process the return to validate all the pickings self.return_request_customer.action_validate() self.assertTrue( all([True if x == "done" else False for x in pickings.mapped("state")]) ) # For lot TSTPROD3LOT0001 we had 70 units prod_3_qty_lot_1 = self.prod_3.with_context( location=self.wh1.lot_stock_id.id, lot_id=self.prod_3_lot1.id ).qty_available # For lot TSTPROD3LOT0002 we had 2 units prod_3_qty_lot_2 = self.prod_3.with_context( location=self.wh1.lot_stock_id.id, lot_id=self.prod_3_lot2.id ).qty_available self.assertAlmostEqual(prod_3_qty_lot_1, 82.0) self.assertAlmostEqual(prod_3_qty_lot_2, 6.0) # There were 28 units in the sale orders. self.assertAlmostEqual( sum(sale_orders.mapped("order_line.qty_delivered")), 12.0 ) # Test the view action res = self.return_request_customer.action_view_sales() expected_res = { "type": "ir.actions.act_window", "res_model": "sale.order", "domain": "[('id', 'in', %s)]" % (sorted(sale_orders.ids)), } # The intention is to check if a dictionary is a subset of other. # As assertDictContainsSubset() is no longer supported, # this is an alternative way of checking. self.assertEqual(res, {**res, **expected_res}) def test_02_return_sale_stock_from_customer_single_sale(self): """Return stock from customer with a single result""" self.return_request_customer.write( { "partner_id": self.partner_customer_2.id, "to_refund": True, "line_ids": [ ( 0, 0, { "product_id": self.prod_3.id, "lot_id": self.prod_3_lot1.id, "quantity": 1.0, }, ), ], } ) self.return_request_customer.action_confirm() sale_order = self.return_request_customer.sale_order_ids self.assertEqual(len(sale_order), 1) # Test the view action res = self.return_request_customer.action_view_sales() expedcted_res = { "type": "ir.actions.act_window", "res_model": "sale.order", "views": [(self.env.ref("sale.view_order_form").id, "form")], "res_id": sale_order.id, } self.assertEqual(res, {**res, **expedcted_res})
40.56701
7,870
1,488
py
PYTHON
15.0
# Copyright 2019 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class StockReturnRequest(models.Model): _inherit = "stock.return.request" sale_order_ids = fields.Many2many( comodel_name="sale.order", string="Involved Sales", readonly=True, copy=False, ) def _prepare_move_default_values(self, line, qty, move): """Extend this method to add values to return move""" vals = super()._prepare_move_default_values(line, qty, move) vals.update({"sale_line_id": move.sale_line_id.id}) return vals def _action_confirm(self): res = super()._action_confirm() if self.state == "confirmed": self.sale_order_ids = self.returned_picking_ids.mapped("sale_id") return res def action_view_sales(self): """Display returned sales""" action = self.env.ref("sale.action_orders") result = action.read()[0] result["context"] = {} sales = self.mapped("sale_order_ids") if not sales or len(sales) > 1: # Sort ids so we can confidently test the string result["domain"] = "[('id', 'in', %s)]" % (sorted(sales.ids)) elif len(sales) == 1: res = self.env.ref("sale.view_order_form", False) result["views"] = [(res and res.id or False, "form")] result["res_id"] = sales.id return result
36.292683
1,488
766
py
PYTHON
15.0
# Copyright 2018-2020 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Order Secondary Unit", "summary": "Sale product in a secondary unit", "version": "15.0.2.0.0", "development_status": "Production/Stable", "category": "Sale", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "auto_install": True, "depends": ["sale", "product_secondary_unit"], "data": [ "views/product_secondary_unit_views.xml", "views/product_views.xml", "views/sale_order_views.xml", "report/sale_report_templates.xml", ], }
34.818182
766
4,805
py
PYTHON
15.0
# Copyright 2018-2020 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests import Form, TransactionCase, tagged @tagged("post_install", "-at_install") class TestSaleOrderSecondaryUnit(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product_uom_kg = cls.env.ref("uom.product_uom_kgm") cls.product_uom_gram = cls.env.ref("uom.product_uom_gram") cls.product_uom_unit = cls.env.ref("uom.product_uom_unit") cls.price_list = cls.env["product.pricelist"].create( {"name": "price list for test"} ) cls.product = cls.env["product.product"].create( { "name": "test", "uom_id": cls.product_uom_kg.id, "uom_po_id": cls.product_uom_kg.id, } ) # Set secondary uom on product template cls.product.product_tmpl_id.write( { "secondary_uom_ids": [ ( 0, 0, { "name": "unit-500", "uom_id": cls.product_uom_unit.id, "factor": 0.5, }, ) ], } ) cls.secondary_unit = cls.env["product.secondary.unit"].search( [("product_tmpl_id", "=", cls.product.product_tmpl_id.id)] ) cls.product.sale_secondary_uom_id = cls.secondary_unit.id cls.partner = cls.env["res.partner"].create({"name": "test - partner"}) with Form(cls.env["sale.order"]) as order_form: order_form.partner_id = cls.partner order_form.pricelist_id = cls.price_list with order_form.order_line.new() as line_form: line_form.product_id = cls.product line_form.product_uom_qty = 1 line_form.price_unit = 1000.00 cls.order = order_form.save() def test_onchange_secondary_uom(self): self.order.order_line.write( {"secondary_uom_id": self.secondary_unit.id, "secondary_uom_qty": 5} ) self.order.order_line._compute_product_uom_qty() self.assertEqual(self.order.order_line.product_uom_qty, 2.5) def test_onchange_secondary_unit_product_uom_qty(self): self.order.order_line.update( {"secondary_uom_id": self.secondary_unit.id, "product_uom_qty": 3.5} ) self.assertEqual(self.order.order_line.secondary_uom_qty, 7.0) def test_default_secondary_unit(self): self.order.order_line.product_id_change() self.assertEqual(self.order.order_line.secondary_uom_id, self.secondary_unit) def test_onchange_order_product_uom(self): self.order.order_line.update( { "secondary_uom_id": self.secondary_unit.id, "product_uom": self.product_uom_gram.id, "product_uom_qty": 3500.00, } ) self.assertEqual(self.order.order_line.secondary_uom_qty, 7.0) def test_independent_type(self): # dependent type is already tested as dependency_type by default self.order.order_line.secondary_uom_id = self.secondary_unit.id self.order.order_line.secondary_uom_id.write({"dependency_type": "independent"}) # Remember previous UoM quantity for avoiding interactions with other modules previous_uom_qty = self.order.order_line.product_uom_qty self.order.order_line.write({"secondary_uom_qty": 2}) self.assertEqual(self.order.order_line.product_uom_qty, previous_uom_qty) self.assertEqual(self.order.order_line.secondary_uom_qty, 2) self.order.order_line.write({"product_uom_qty": 17}) self.assertEqual(self.order.order_line.secondary_uom_qty, 2) self.assertEqual(self.order.order_line.product_uom_qty, 17) def test_secondary_uom_unit_price(self): # Remove secondary uom in sale line to do a complete test of secondary price self.order.order_line.secondary_uom_id = False self.assertEqual(self.order.order_line.secondary_uom_unit_price, 0) self.order.order_line.update( {"secondary_uom_id": self.secondary_unit.id, "product_uom_qty": 2} ) self.assertEqual(self.order.order_line.secondary_uom_qty, 4) self.assertEqual(self.order.order_line.secondary_uom_unit_price, 500) self.order.order_line.write({"product_uom_qty": 8}) self.assertEqual(self.order.order_line.secondary_uom_qty, 16) self.assertEqual(self.order.order_line.secondary_uom_unit_price, 500) self.assertEqual(self.order.order_line.price_subtotal, 8000)
43.681818
4,805
2,284
py
PYTHON
15.0
# Copyright 2018-2020 Tecnativa - Carlos Dauden # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrderLine(models.Model): _inherit = ["sale.order.line", "product.secondary.unit.mixin"] _name = "sale.order.line" _secondary_unit_fields = { "qty_field": "product_uom_qty", "uom_field": "product_uom", } secondary_uom_unit_price = fields.Float( string="2nd unit price", digits="Product Price", compute="_compute_secondary_uom_unit_price", ) product_uom_qty = fields.Float( store=True, readonly=False, compute="_compute_product_uom_qty", copy=True ) @api.depends("secondary_uom_qty", "secondary_uom_id", "product_uom_qty") def _compute_product_uom_qty(self): self._compute_helper_target_field_qty() @api.onchange("product_uom") def onchange_product_uom_for_secondary(self): self._onchange_helper_product_uom_for_secondary() @api.onchange("product_id") def product_id_change(self): """ If default sales secondary unit set on product, put on secondary quantity 1 for being the default quantity. We override this method, that is the one that sets by default 1 on the other quantity with that purpose. """ res = super().product_id_change() line_uom_qty = self.product_uom_qty self.secondary_uom_id = self.product_id.sale_secondary_uom_id if self.product_id.sale_secondary_uom_id: if line_uom_qty == 1.0: self.secondary_uom_qty = 1.0 self.onchange_product_uom_for_secondary() else: self.product_uom_qty = line_uom_qty return res @api.depends("secondary_uom_qty", "product_uom_qty", "price_unit") def _compute_secondary_uom_unit_price(self): for line in self: if line.secondary_uom_id: try: line.secondary_uom_unit_price = ( line.price_subtotal / line.secondary_uom_qty ) except ZeroDivisionError: line.secondary_uom_unit_price = 0 else: line.secondary_uom_unit_price = 0
36.83871
2,284
3,003
py
PYTHON
15.0
# Copyright 2018-2020 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" sale_secondary_uom_id = fields.Many2one( comodel_name="product.secondary.unit", string="Default secondary unit for sales", compute="_compute_sale_secondary_uom_id", inverse="_inverse_sale_secondary_uom_id", help="In order to set a value, please first add at least one record" " in 'Secondary Unit of Measure'", domain="[('product_tmpl_id', '=', id), ('product_id', '=', False)]", store=True, ) @api.depends("product_variant_ids", "product_variant_ids.sale_secondary_uom_id") def _compute_sale_secondary_uom_id(self): unique_variants = self.filtered(lambda tmpl: tmpl.product_variant_count == 1) for template in unique_variants: template.sale_secondary_uom_id = ( template.product_variant_ids.sale_secondary_uom_id ) for template in self - unique_variants: if len(template.product_variant_ids.sale_secondary_uom_id) == 1: template.sale_secondary_uom_id = ( template.product_variant_ids.sale_secondary_uom_id ) else: template.sale_secondary_uom_id = False def _inverse_sale_secondary_uom_id(self): for template in self: # if template.product_variant_count == 1: template.product_variant_ids.sale_secondary_uom_id = ( template.sale_secondary_uom_id ) @api.onchange("sale_secondary_uom_id") def onchange_sale_secondary_uom_id(self): if len(self.product_variant_ids.sale_secondary_uom_id) > 1: return { "warning": { "title": _("Warning"), "message": _( "Product variants have distinct sale secondary uom:" "\n{secondary_uom}\n" "All variants will be written with new secondary uom" ).format( secondary_uom="\n".join( self.product_variant_ids.mapped( "sale_secondary_uom_id.name" ) ) ), } } @api.model_create_multi def create(self, vals_list): templates = super(ProductTemplate, self).create(vals_list) # This is needed to set given values to first variant after creation for template, vals in zip(templates, vals_list): related_vals = {} if vals.get("sale_secondary_uom_id"): related_vals["sale_secondary_uom_id"] = vals["sale_secondary_uom_id"] if related_vals: template.write(related_vals) return templates
41.708333
3,003
631
py
PYTHON
15.0
# Copyright 2022 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductProduct(models.Model): _inherit = "product.product" sale_secondary_uom_id = fields.Many2one( comodel_name="product.secondary.unit", string="Default secondary unit for sales", help="In order to set a value, please first add at least one record" " in 'Secondary Unit of Measure'", domain="['|', ('product_id', '=', id)," "'&', ('product_tmpl_id', '=', product_tmpl_id)," " ('product_id', '=', False)]", )
37.117647
631
1,029
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Dauden # Copyright 2020 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale payment sheet", "summary": "Allow to create invoice payments to commercial users without " "accounting permissions", "version": "15.0.1.1.2", "development_status": "Beta", "category": "Account", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "maintainers": ["sergio-teruel"], "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale", "account"], "data": [ "security/ir.model.access.csv", "security/security.xml", "report/report_sale_payment_sheet_summary.xml", "report/sale_payment_sheet_report.xml", "views/res_users_views.xml", "views/sale_payment_sheet_views.xml", "views/sale_payment_sheet_menu.xml", "wizards/sale_invoice_payment_view.xml", ], }
36.75
1,029
6,451
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Dauden # Copyright 2020 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from freezegun import freeze_time from odoo.exceptions import UserError, ValidationError from odoo.tests import Form, TransactionCase @freeze_time("2021-01-01 09:30:00") class TestSaleInvoicePayment(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Remove time zone from user to avoid to time local representation cls.env.user.partner_id.tz = False cls.wizard_obj = cls.env["sale.invoice.payment.wiz"] cls.SalePaymentSheet = cls.env["sale.payment.sheet"] cls.partner = cls.env["res.partner"].create({"name": "Test partner"}) cls.bank_journal = cls.env["account.journal"].create( {"name": "Bank journal", "type": "bank", "code": "test"} ) account_type_income = cls.env.ref("account.data_account_type_revenue") cls.account_invoice = cls.env["account.account"].create( { "code": "test", "name": "Test account", "user_type_id": account_type_income.id, } ) cls.invoice1 = cls._create_invoice(cls) cls.invoice2 = cls._create_invoice(cls) (cls.invoice1 + cls.invoice2).action_post() def _create_invoice(self): with Form( self.env["account.move"].with_context(default_move_type="out_invoice") ) as invoice_form: invoice_form.partner_id = self.partner with invoice_form.invoice_line_ids.new() as line_form: line_form.name = "invoice test" line_form.account_id = self.account_invoice line_form.quantity = 1.0 line_form.price_unit = 100.00 return invoice_form.save() def test_payment_wizard(self): PaymentWiz = self.env["sale.invoice.payment.wiz"].with_context( active_model="account.move", active_ids=(self.invoice1 + self.invoice2).ids, ) with Form(PaymentWiz) as wiz_form: wiz_form.journal_id = self.bank_journal wiz_form.amount = 150.00 wiz = wiz_form.save() action = wiz.create_sale_invoice_payment_sheet() sheet = self.SalePaymentSheet.browse(action["res_id"]) self.assertEqual(len(sheet.line_ids), 2) line_partial_payment = sheet.line_ids.filtered( lambda ln: ln.transaction_type == "partial" ) self.assertTrue(line_partial_payment) self.assertEqual(line_partial_payment.invoice_id, self.invoice2) line_full_payment = sheet.line_ids.filtered( lambda ln: ln.transaction_type == "full" ) self.assertTrue(line_full_payment) self.assertEqual(line_full_payment.invoice_id, self.invoice1) self.assertEqual(sheet.amount_total, 150.00) def _create_payment_sheet(self): with Form(self.SalePaymentSheet) as sheet_form: sheet_form.journal_id = self.bank_journal for index, invoice in enumerate(self.invoice1 + self.invoice2): with sheet_form.line_ids.new() as line_sheet: line_sheet.partner_id = self.partner line_sheet.invoice_id = invoice line_sheet.ref = "REF{}".format(line_sheet.id) # Only write for partial amount payed, by default the # amount line is total amount residual if index > 0: line_sheet.amount = 50.0 return sheet_form.save() def test_manual_payment_sheet(self): sheet = self._create_payment_sheet() self.assertEqual(len(sheet.line_ids), 2) line_partial_payment = sheet.line_ids.filtered( lambda ln: ln.transaction_type == "partial" ) self.assertTrue(line_partial_payment) self.assertEqual(line_partial_payment.invoice_id, self.invoice2) line_full_payment = sheet.line_ids.filtered( lambda ln: ln.transaction_type == "full" ) self.assertTrue(line_full_payment) self.assertEqual(line_full_payment.invoice_id, self.invoice1) self.assertEqual( sheet.name, "{} - {} - {}".format( sheet.date.strftime("%Y.%m.%d"), sheet.journal_id.name, sheet.user_id.name, ), ) self.assertEqual( line_partial_payment.name, "[{}] - {} - {} - ({})".format( "09:30", line_partial_payment.sheet_id.user_id.name, line_partial_payment.invoice_id.name, dict( line_partial_payment._fields[ "transaction_type" ]._description_selection(line_partial_payment.env) ).get(line_partial_payment.transaction_type), ), ) def test_payment_sheet_confirm(self): sheet = self._create_payment_sheet() sheet.button_confirm_sheet() self.assertTrue(sheet.statement_id) self.assertEqual(len(sheet.line_ids.mapped("statement_line_id")), 2) def test_payment_sheet_reopen(self): sheet = self._create_payment_sheet() sheet.button_confirm_sheet() sheet.button_reopen() self.assertFalse(sheet.statement_id) def test_payment_sheet_unlink(self): sheet = self._create_payment_sheet() sheet.button_confirm_sheet() with self.assertRaises(UserError): sheet.unlink() def test_payment_sheet_line_unlink(self): sheet = self._create_payment_sheet() sheet.button_confirm_sheet() with self.assertRaises(UserError): sheet.line_ids.unlink() def test_button_bank_statement(self): sheet = self._create_payment_sheet() sheet.button_bank_statement() def test_payment_sheet_invoice_constraint(self): # You can not add full invoice payed more than one time. sheet = self._create_payment_sheet() with self.assertRaises(ValidationError): with Form(sheet) as sheet_form: with sheet_form.line_ids.new() as line_sheet: line_sheet.partner_id = self.partner line_sheet.invoice_id = self.invoice1 sheet_form.save()
41.089172
6,451
12,334
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Dauden # Copyright 2020 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools import float_compare class SalePaymentSheet(models.Model): _name = "sale.payment.sheet" _description = "Sale Payment Sheet" _order = "date desc, id desc" _inherit = ["mail.thread"] _check_company_auto = True name = fields.Char( string="Reference", states={"open": [("readonly", False)]}, copy=False, compute="_compute_name", readonly=True, store=True, ) reference = fields.Char( string="External Reference", states={"open": [("readonly", False)]}, copy=False, readonly=True, ) date = fields.Date( required=True, states={"confirm": [("readonly", True)]}, index=True, copy=False, default=fields.Date.context_today, ) state = fields.Selection( [("open", "New"), ("confirm", "Validated")], string="Status", required=True, readonly=True, copy=False, default="open", ) currency_id = fields.Many2one( "res.currency", compute="_compute_currency", string="Currency" ) journal_id = fields.Many2one( "account.journal", string="Journal", required=True, states={"confirm": [("readonly", True)]}, default=lambda self: self._default_journal(), ) commercial_journal_ids = fields.Many2many(related="user_id.commercial_journal_ids") company_id = fields.Many2one( "res.company", related="journal_id.company_id", string="Company", store=True, readonly=True, ) line_ids = fields.One2many( "sale.payment.sheet.line", "sheet_id", string="Sheet lines", states={"confirm": [("readonly", True)]}, copy=True, ) user_id = fields.Many2one( "res.users", string="Responsible", required=False, default=lambda self: self.env.user, ) statement_id = fields.Many2one( comodel_name="account.bank.statement", string="Bank statement" ) amount_total = fields.Monetary( string="Total", store=True, readonly=True, compute="_compute_amount_total" ) group_lines = fields.Selection( selection=[("ref", "Reference")], string="Group statement lines by" ) @api.depends("line_ids.amount") def _compute_amount_total(self): """Summarize total amount lines, this field already is signed depending on invoice type. """ for sheet in self: sheet.amount_total = sum(sheet.line_ids.mapped("amount")) @api.model def _default_journal(self): return self.env.user.commercial_journal_ids[:1] @api.depends("journal_id.currency_id") def _compute_currency(self): for sheet in self: sheet.currency_id = ( sheet.journal_id.currency_id or sheet.company_id.currency_id ) @api.depends("journal_id", "user_id", "date") def _compute_name(self): for sheet in self: sheet.name = "{} - {} - {}".format( sheet.date and sheet.date.strftime("%Y.%m.%d"), sheet.journal_id.name, sheet.user_id.name, ) def unlink(self): for sheet in self: if sheet.state != "open": raise UserError( _("You can not delete a sheet if has related journal items.") ) return super().unlink() @api.model def _statement_line_key(self, line): if self.group_lines == "ref": return (line.partner_id.id, line.ref) else: return (line.id,) def button_confirm_sheet(self): sheets = self.filtered(lambda r: r.state == "open") BankStatement = self.env["account.bank.statement"].sudo() BankStatementLine = self.env["account.bank.statement.line"].sudo() for sheet in sheets: statement = BankStatement.create( { "name": sheet.name, "date": sheet.date, "journal_id": sheet.journal_id.id, "user_id": sheet.user_id.id, } ) vals_dic = {} for line in sheet.line_ids: key = self._statement_line_key(line) if line.invoice_id.move_type == "out_refund" and line.amount > 0.0: # convert to negative amounts if user pays a refund out # invoice with a positive amount. amount_line = -line.amount else: amount_line = line.amount if key not in vals_dic: vals_dic[key] = { "name": line.name, "date": line.date, "amount": amount_line, "partner_id": line.partner_id.id, "payment_ref": line.ref or line.invoice_id.name, "sequence": line.sequence, "statement_id": statement.id, "payment_sheet_line_ids": line, } else: vals_dic[key]["amount"] += amount_line vals_dic[key]["name"] += " {}".format(line.invoice_id.name) vals_dic[key]["payment_sheet_line_ids"] += line for vals in vals_dic.values(): payment_sheet_line_ids = vals.pop("payment_sheet_line_ids", None) statement_line = BankStatementLine.create(vals) payment_sheet_line_ids.statement_line_id = statement_line sheet.message_post( body=_("Sheet %s confirmed, bank statement were created.") % (statement.name,) ) sheet.write({"state": "confirm", "statement_id": statement.id}) def button_reopen(self): self.ensure_one() self_sudo = self.sudo() if self_sudo.statement_id.line_ids.filtered("is_reconciled"): raise UserError( _("You can not reopen a sheet that has any reconciled line.") ) self_sudo.statement_id.button_reopen() self_sudo.statement_id.unlink() self.state = "open" def button_bank_statement(self): """ Action to open bank statement linked """ self.ensure_one() return self.statement_id.get_formview_action() class SalePaymentSheetLine(models.Model): _name = "sale.payment.sheet.line" _description = "Sale Payment Sheet Line" _order = "sheet_id desc, date, sequence, id desc" name = fields.Char( string="Label", compute="_compute_name", store=True, readonly=False ) date = fields.Date( required=True, default=lambda self: self.env.context.get( "date", fields.Date.context_today(self) ), ) sheet_id = fields.Many2one( "sale.payment.sheet", string="Sheet", index=True, required=True, ondelete="cascade", ) statement_line_id = fields.Many2one( "account.bank.statement.line", string="Statement Line", index=True ) amount = fields.Monetary( compute="_compute_amount", inverse="_inverse_amount", currency_field="journal_currency_id", store=True, readonly=False, ) journal_currency_id = fields.Many2one( "res.currency", string="Journal's Currency", related="sheet_id.currency_id", help="Utility field to express amount currency", readonly=True, ) partner_id = fields.Many2one("res.partner", string="Partner") ref = fields.Char(string="Reference") note = fields.Text(string="Notes") sequence = fields.Integer( index=True, help="Gives the sequence order when displaying a list of payment sheet lines.", default=1, ) company_id = fields.Many2one( "res.company", related="sheet_id.company_id", string="Company", store=True, readonly=True, ) state = fields.Selection(related="sheet_id.state", string="Status", readonly=True) invoice_id = fields.Many2one( comodel_name="account.move", string="Invoice", index=True ) transaction_type = fields.Selection( [("partial", "Partial payment"), ("full", "Full payment")], compute="_compute_transaction_type", ) @api.depends("amount", "invoice_id") def _compute_transaction_type(self): for line in self: amount = ( line.amount if line.invoice_id.move_type == "out_invoice" else -line.amount ) if float_compare( amount, line.invoice_id.amount_total, precision_digits=line.sheet_id.currency_id.decimal_places, ): line.transaction_type = "partial" else: line.transaction_type = "full" @api.depends("sheet_id.user_id", "invoice_id", "transaction_type") def _compute_name(self): for line in self: if not line.create_date: line.create_date = fields.Datetime.now() line.name = "[{}] - {} - {} - ({})".format( fields.Datetime.context_timestamp(line, line.create_date).strftime( "%H:%M" ), line.sheet_id.user_id.name, line.invoice_id.name, dict( line._fields["transaction_type"]._description_selection(line.env) ).get(line.transaction_type), ) @api.depends("invoice_id") def _compute_amount(self): for line in self: amount = line.invoice_id.amount_residual line.amount = ( amount if line.invoice_id.move_type == "out_invoice" else -amount ) def _inverse_amount(self): for line in self: if line.invoice_id.move_type == "out_refund" and line.amount > 0.0: line.amount = -line.amount @api.constrains("invoice_id", "amount") def _check_invoice(self): for line in self: # Allow to enter sheet line with an amount of 0, if line.journal_currency_id.is_zero(line.amount): raise ValidationError( _("The amount of a cash transaction cannot be 0.") ) # Do not allow to enter a invoice totally payed more than one time payment_lines = self.search( [ ("invoice_id", "=", line.invoice_id.id), ("sheet_id.state", "=", "open"), ] ) amount_payed = sum(payment_lines.mapped("amount")) if ( float_compare( amount_payed, line.invoice_id.amount_residual, precision_rounding=line.invoice_id.currency_id.rounding, ) == 1 ): raise ValidationError( _( "This invoice already has been included in other payment sheet" " or the amount payed is greather than residual invoice amount." "\n Invoice: %(invoice_name)s\n Amount payed: " "%(amount_payed)s\n Payment sheets:" " %(payment_lines_name)s" ) % { "invoice_name": line.invoice_id.name, "amount_payed": amount_payed, "payment_lines_name": payment_lines.mapped("sheet_id.name"), } ) def unlink(self): if self.filtered("statement_line_id"): raise UserError( _("You can not delete payment lines if have related statement lines.") ) return super().unlink()
35.24
12,334
387
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Dauden # Copyright 2020 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ResUsers(models.Model): _inherit = "res.users" commercial_journal_ids = fields.Many2many( comodel_name="account.journal", string="Allowed journals for commercial", )
27.642857
387
5,092
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Carlos Dauden # Copyright 2020 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class SaleInvoicePaymentWiz(models.TransientModel): _name = "sale.invoice.payment.wiz" _description = "Sale invoice payment wizard" user_id = fields.Many2one( "res.users", string="Responsible", required=False, default=lambda self: self.env.user, ) commercial_journal_ids = fields.Many2many(related="user_id.commercial_journal_ids") currency_id = fields.Many2one( "res.currency", compute="_compute_currency", string="Currency" ) journal_id = fields.Many2one( comodel_name="account.journal", string="Journal", required=True, ) amount = fields.Monetary( currency_field="currency_id", required=True, compute="_compute_amount", readonly=False, store=True, ) ref = fields.Char(string="Reference") invoice_ids = fields.Many2many( comodel_name="account.move", ) partner_id = fields.Many2one(comodel_name="res.partner") @api.depends("invoice_ids") def _compute_amount(self): for wiz in self: amount = 0.0 for invoice in wiz.invoice_ids: if invoice.move_type == "out_refund": amount -= invoice.amount_residual else: amount += invoice.amount_residual wiz.amount = amount @api.model def default_get(self, fields_list): res = super(SaleInvoicePaymentWiz, self).default_get(fields_list) res["journal_id"] = self.env.user.commercial_journal_ids[:1].id if self.env.context.get("active_model", False) != "account.move": return res invoices = self.env["account.move"].browse(self.env.context.get("active_ids")) res["invoice_ids"] = [(6, 0, invoices.ids)] res["partner_id"] = invoices[:1].partner_id.id return res @api.depends("journal_id") def _compute_currency(self): for wiz in self: wiz.currency_id = wiz.journal_id.currency_id def create_sale_invoice_payment_sheet(self): invoices = ( self.invoice_ids or self.env["account.move"].browse(self.env.context.get("active_ids")) ).filtered(lambda inv: inv.state == "posted" and inv.payment_state != "paid") if not invoices: return # Search an open payment sheet or create one if not exists SalePaymentSheet = self.env["sale.payment.sheet"] sheet = SalePaymentSheet.search( [ ("state", "=", "open"), ("user_id", "=", self.env.user.id), ("journal_id", "=", self.journal_id.id), ("date", "=", fields.Date.today()), ] ) if not sheet: sheet = SalePaymentSheet.create( { "user_id": self.env.user.id, "journal_id": self.journal_id.id, "date": fields.Date.today(), } ) # First process refund invoices su summarize negative amounts for invoice in invoices.filtered(lambda inv: inv.move_type == "out_refund"): self._process_invoice(sheet, invoice) for invoice in invoices.filtered( lambda inv: inv.move_type == "out_invoice" ).sorted(key=lambda x: (x.date, x.id)): self._process_invoice(sheet, invoice) return sheet.get_formview_action() def _process_invoice(self, sheet, invoice): all_sheet_lines = sheet.line_ids.filtered(lambda ln: ln.invoice_id == invoice) sheet_line = all_sheet_lines.filtered(lambda ln: ln.ref == self.ref) other_lines = all_sheet_lines - sheet_line invoice_amount_residual = ( invoice.amount_residual if invoice.move_type == "out_invoice" else -invoice.amount_residual ) invoice_amount_residual -= sum(other_lines.mapped("amount")) amount_pay = 0.0 if self.amount > 0: amount_pay = ( invoice_amount_residual if self.amount >= invoice_amount_residual else self.amount ) elif invoice.move_type == "out_refund": amount_pay = invoice_amount_residual if amount_pay: if sheet_line: sheet_line.amount = amount_pay else: sheet.line_ids = [ ( 0, 0, self._prepare_sheet_line_values(invoice, amount_pay), ) ] self.amount -= amount_pay def _prepare_sheet_line_values(self, invoice, amount_pay): return { "amount": amount_pay, "partner_id": invoice.partner_id.id, "invoice_id": invoice.id, "ref": self.ref, }
36.371429
5,092
779
py
PYTHON
15.0
# Copyright 2017 Jairo Llopis <jairo.llopis@tecnativa.com> # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Order Product Recommendation", "summary": "Recommend products to sell to customer based on history", "version": "15.0.1.1.0", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": [ "sale", ], "data": [ "security/ir.model.access.csv", "wizards/sale_order_recommendation_view.xml", "views/res_config_settings_views.xml", "views/sale_order_view.xml", ], }
33.869565
779
7,655
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Jairo Llopis # Copyright 2020 Tecnativa - Pedro M. Baeza # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from freezegun import freeze_time from odoo.exceptions import UserError from .test_recommendation_common import RecommendationCase @freeze_time("2021-10-02 15:30:00") class RecommendationCaseTests(RecommendationCase): def test_recommendations(self): """Recommendations are OK.""" self.new_so.order_line = [ ( 0, 0, { "product_id": self.prod_1.id, "product_uom_qty": 3, "qty_delivered_method": "manual", }, ) ] self.new_so.order_line.product_id_change() wizard = self.wizard() # Order came in from context self.assertEqual(wizard.order_id, self.new_so) self.assertEqual(len(wizard.line_ids), 3) self.assertEqual(wizard.line_ids[0].product_id, self.prod_2) self.assertEqual(wizard.line_ids[1].product_id, self.prod_1) self.assertEqual(wizard.line_ids[2].product_id, self.prod_3) # Product 2 is first wiz_line_prod2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(wiz_line_prod2.times_delivered, 2) self.assertEqual(wiz_line_prod2.units_delivered, 100) self.assertEqual(wiz_line_prod2.units_included, 0) # Product 1 appears second wiz_line_prod1 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_1) self.assertEqual(wiz_line_prod1.times_delivered, 1) self.assertEqual(wiz_line_prod1.units_delivered, 25) self.assertEqual(wiz_line_prod1.units_included, 3) # Product 3 appears third wiz_line_prod3 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_3) self.assertEqual(wiz_line_prod3.times_delivered, 1) self.assertEqual(wiz_line_prod3.units_delivered, 100) self.assertEqual(wiz_line_prod3.units_included, 0) # Only 1 product if limited as such wizard.line_amount = 1 wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 2) def test_recommendations_archived_product(self): self.env["sale.order"].create( { "partner_id": self.partner.id, } ) self.prod_1.active = False self.prod_2.sale_ok = False wizard = self.wizard() wizard._generate_recommendations() self.assertNotIn(self.prod_1, wizard.line_ids.mapped("product_id")) self.assertNotIn(self.prod_2, wizard.line_ids.mapped("product_id")) def test_transfer(self): """Products get transferred to SO.""" qty = 10 wizard = self.wizard() wiz_line_prod1 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_1) wiz_line_prod1.units_included = qty wizard.action_accept() self.assertEqual(len(self.new_so.order_line), 1) self.assertEqual(self.new_so.order_line.product_id, self.prod_1) self.assertEqual(self.new_so.order_line.product_uom_qty, qty) # No we confirm the SO self.new_so.action_confirm() wizard = self.wizard() wiz_line = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_1) wiz_line.units_included = 0 # The confirmed line can't be deleted with self.assertRaises(UserError): wizard.action_accept() # Deliver items and invoice the order self.new_so.order_line.qty_delivered = qty adv_wiz = ( self.env["sale.advance.payment.inv"] .with_context(active_ids=[self.new_so.id]) .create( { "advance_payment_method": "delivered", } ) ) adv_wiz.with_context(open_invoices=True).create_invoices() self.new_so.invoice_ids.action_post() # Open the wizard and add more product qty wizard = self.wizard() wiz_line = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_1) wiz_line.units_included = qty + 2 wizard.action_accept() # Deliver extra qty and make a new invoice self.new_so.order_line.qty_delivered = qty + 2 adv_wiz = ( self.env["sale.advance.payment.inv"] .with_context(active_ids=[self.new_so.id]) .create( { "advance_payment_method": "delivered", } ) ) adv_wiz.with_context(open_invoices=True).create_invoices() self.assertEqual(2, len(self.new_so.invoice_ids)) self.assertEqual(2, self.new_so.invoice_ids[-1].invoice_line_ids.quantity) def test_recommendations_price_origin(self): # Display product price from pricelist wizard = self.wizard() wizard.sale_recommendation_price_origin = "pricelist" wiz_line_prod1 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_1) self.assertEqual(wiz_line_prod1.price_unit, 25.00) wiz_line_prod2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(wiz_line_prod2.price_unit, 50.00) wiz_line_prod3 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_3) self.assertEqual(wiz_line_prod3.price_unit, 75.00) # Display product price from last sale order price wizard.sale_recommendation_price_origin = "last_sale_price" wiz_line_prod1 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_1) self.assertEqual(wiz_line_prod1.price_unit, 24.50) wiz_line_prod2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(wiz_line_prod2.price_unit, 49.50) wiz_line_prod3 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_3) self.assertEqual(wiz_line_prod3.price_unit, 74.50) # Change confirmation date in order2 self.order2.date_order = "2021-05-07" wizard.sale_recommendation_price_origin = "pricelist" wizard.sale_recommendation_price_origin = "last_sale_price" wiz_line_prod2 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_2) self.assertEqual(wiz_line_prod2.price_unit, 89.00) def test_recommendations_last_sale_price_to_sale_order(self): # Display product price from last sale order price wizard = self.wizard() wizard.sale_recommendation_price_origin = "last_sale_price" wiz_line_prod1 = wizard.line_ids.filtered(lambda x: x.product_id == self.prod_1) wiz_line_prod1.units_included = 1.0 wizard.action_accept() so_line_prod1 = wizard.order_id.order_line.filtered( lambda x: x.product_id == self.prod_1 ) self.assertEqual(so_line_prod1.price_unit, 24.50) # If I update sale order line price unit this price can not bw updated # by wizard so_line_prod1.price_unit = 60.0 wiz_line_prod1.units_included = 3 wizard.action_accept() self.assertEqual(so_line_prod1.price_unit, 60.0) def test_recommendation_delivery_address(self): self.new_so.partner_shipping_id = self.partner_delivery wizard = self.wizard() wizard.use_delivery_address = True wizard._generate_recommendations() self.assertEqual(len(wizard.line_ids), 1) self.assertEqual(wizard.line_ids[0].product_id, self.prod_2)
44.754386
7,653
4,679
py
PYTHON
15.0
# Copyright 2017 Tecnativa - Jairo Llopis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from freezegun import freeze_time from odoo.tests.common import TransactionCase @freeze_time("2021-10-02 15:30:00") class RecommendationCase(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Make sure user has UoM activated for Forms to work cls.env.user.groups_id = [(4, cls.env.ref("uom.group_uom").id)] cls.pricelist = cls.env["product.pricelist"].create( { "name": "Pricelist for test", } ) cls.partner = cls.env["res.partner"].create( {"name": "Mr. Odoo", "property_product_pricelist": cls.pricelist.id} ) cls.partner_delivery = cls.env["res.partner"].create( { "name": "Mr. Odoo Delivery", "property_product_pricelist": cls.pricelist.id, } ) cls.product_obj = cls.env["product.product"] cls.prod_1 = cls.product_obj.create( { "name": "Test Product 1", "type": "service", "list_price": 25.00, } ) cls.prod_2 = cls.product_obj.create( { "name": "Test Product 2", "type": "service", "list_price": 50.00, } ) cls.prod_3 = cls.product_obj.create( { "name": "Test Product 3", "type": "service", "list_price": 75.00, } ) # Create old sale orders to have searchable history # (Remember to change the dates if the tests fail) cls.order1 = cls.env["sale.order"].create( { "partner_id": cls.partner.id, "state": "done", "date_order": "2021-05-05", "order_line": [ ( 0, 0, { "product_id": cls.prod_1.id, "name": cls.prod_1.name, "product_uom_qty": 25, "qty_delivered_method": "manual", "qty_delivered": 25, "price_unit": 24.50, }, ), ( 0, 0, { "product_id": cls.prod_2.id, "name": cls.prod_2.name, "product_uom_qty": 50, "qty_delivered_method": "manual", "qty_delivered": 50, "price_unit": 49.50, }, ), ( 0, 0, { "product_id": cls.prod_3.id, "name": cls.prod_3.name, "product_uom_qty": 100, "qty_delivered_method": "manual", "qty_delivered": 100, "price_unit": 74.50, }, ), ], } ) cls.order2 = cls.env["sale.order"].create( { "partner_id": cls.partner.id, "partner_shipping_id": cls.partner_delivery.id, "state": "done", "date_order": "2021-05-03", "order_line": [ ( 0, 0, { "product_id": cls.prod_2.id, "name": cls.prod_2.name, "product_uom_qty": 50, "qty_delivered_method": "manual", "qty_delivered": 50, "price_unit": 89.00, }, ), ], } ) # Create a new sale order for the same customer cls.new_so = cls.env["sale.order"].create( { "partner_id": cls.partner.id, } ) def wizard(self): """Get a wizard.""" wizard = ( self.env["sale.order.recommendation"] .with_context(active_id=self.new_so.id) .create({}) ) wizard._generate_recommendations() return wizard
34.659259
4,679
323
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" # Add database index to get last sale price query performance product_id = fields.Many2one(index=True)
29.363636
323
926
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Sergio Teruel from odoo import fields, models class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" default_sale_recommendation_price_origin = fields.Selection( [("pricelist", "Pricelist"), ("last_sale_price", "Last sale price")], string="Price origin", default="pricelist", default_model="sale.order.recommendation", required=True, ) default_use_delivery_address = fields.Boolean( string="Use delivery address", default_model="sale.order.recommendation" ) default_months = fields.Float( string="Default sale recommendation months", default_model="sale.order.recommendation", default=6, ) default_line_amount = fields.Integer( string="Default sale number of recommendations", default_model="sale.order.recommendation", default=15, )
31.931034
926
11,068
py
PYTHON
15.0
# Copyright 2017 Jairo Llopis <jairo.llopis@tecnativa.com> # Copyright 2018 Carlos Dauden <carlos.dauden@tecnativa.com> # Copyright 2020 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from datetime import datetime, timedelta from odoo import api, fields, models from odoo.tests import Form _logger = logging.getLogger(__name__) class SaleOrderRecommendation(models.TransientModel): _name = "sale.order.recommendation" _description = "Recommended products for current sale order" order_id = fields.Many2one( "sale.order", "Sale Order", default=lambda self: self._default_order_id(), required=True, readonly=True, ondelete="cascade", ) months = fields.Float( default=6, required=True, help="Consider these months backwards to generate recommendations.", ) line_ids = fields.One2many( "sale.order.recommendation.line", "wizard_id", "Products" ) line_amount = fields.Integer( "Number of recommendations", default=15, required=True, help="The less, the faster they will be found.", ) last_compute = fields.Char() # Get default value from config settings sale_recommendation_price_origin = fields.Selection( [("pricelist", "Pricelist"), ("last_sale_price", "Last sale price")], string="Product price origin", default="pricelist", ) use_delivery_address = fields.Boolean(string="Use delivery address") @api.model def _default_order_id(self): return self.env.context.get("active_id", False) def _recomendable_sale_order_lines_domain(self): """Domain to find recent SO lines.""" start = datetime.now() - timedelta(days=self.months * 30) start = fields.Datetime.to_string(start) partner = ( self.order_id.partner_shipping_id if self.use_delivery_address else self.order_id.partner_id.commercial_partner_id ) sale_order_partner_field = ( "partner_shipping_id" if self.use_delivery_address else "partner_id" ) # Search with sudo for get sale order from other commercials users other_sales = ( self.env["sale.order"] .sudo() .search( [ ("company_id", "=", self.order_id.company_id.id), (sale_order_partner_field, "child_of", partner.id), ("date_order", ">=", start), ] ) ) domain = [ ("order_id", "in", (other_sales - self.order_id).ids), ("product_id.active", "=", True), ("product_id.sale_ok", "=", True), ("qty_delivered", "!=", 0.0), ] # Exclude delivery products # We can not use the method _is_delivery() from sale module because we are # doing a domain for a readgroup query if "is_delivery" in self.env["sale.order.line"]._fields: domain.append(("is_delivery", "=", False)) return domain def _prepare_recommendation_line_vals(self, group_line, so_line=False): """Return the vals dictionary for creating a new recommendation line. @param group_line: Dictionary returned by the read_group operation. @param so_line: Optional sales order line """ vals = { "product_id": group_line["product_id"][0], "times_delivered": group_line.get("product_id_count", 0), "units_delivered": group_line.get("qty_delivered", 0), } if so_line: vals["units_included"] = so_line.product_uom_qty vals["sale_line_id"] = so_line.id return vals @api.onchange("order_id", "months", "line_amount", "use_delivery_address") def _generate_recommendations(self): """Generate lines according to context sale order.""" last_compute = "{}-{}-{}-{}".format( self.id, self.months, self.line_amount, self.use_delivery_address ) # Avoid execute onchange as times as fields in api.onchange # ORM must control this? if self.last_compute == last_compute: return self.last_compute = last_compute # Search delivered products in previous months # Search with sudo for get sale order from other commercials users found_lines = ( self.env["sale.order.line"] .sudo() .read_group( self._recomendable_sale_order_lines_domain(), ["product_id", "qty_delivered"], ["product_id"], ) ) # Manual ordering that circumvents ORM limitations found_lines = sorted( found_lines, key=lambda res: (res["product_id_count"], res["qty_delivered"]), reverse=True, ) found_dict = {product["product_id"][0]: product for product in found_lines} recommendation_lines = self.env["sale.order.recommendation.line"] existing_product_ids = set() # Always recommend all products already present in the linked SO except delivery # carrier products for line in self.order_id.order_line.filtered(lambda ln: not ln._is_delivery()): found_line = found_dict.get( line.product_id.id, { "product_id": (line.product_id.id, False), }, ) new_line = recommendation_lines.new( self._prepare_recommendation_line_vals(found_line, line) ) recommendation_lines += new_line existing_product_ids.add(line.product_id.id) # Add recent SO recommendations too i = 0 for line in found_lines: if line["product_id"][0] in existing_product_ids: continue new_line = recommendation_lines.new( self._prepare_recommendation_line_vals(line) ) recommendation_lines += new_line # limit number of results. It has to be done here, as we need to # populate all results first, for being able to select best matches i += 1 if i >= self.line_amount: break self.line_ids = recommendation_lines.sorted( key=lambda x: x.times_delivered, reverse=True ) def action_accept(self): """Propagate recommendations to sale order.""" sequence = max(self.order_id.mapped("order_line.sequence") or [0]) order_form = Form(self.order_id.sudo()) to_remove = [] for wiz_line in self.line_ids.filtered( lambda x: x.sale_line_id or x.units_included ): if wiz_line.sale_line_id: index = self.order_id.order_line.ids.index(wiz_line.sale_line_id.id) if wiz_line.units_included: with order_form.order_line.edit(index) as line_form: wiz_line._prepare_update_so_line(line_form) else: to_remove.append(index) else: sequence += 1 with order_form.order_line.new() as line_form: wiz_line._prepare_new_so_line(line_form, sequence) # Remove at the end and in reverse order for not having problems to_remove.reverse() for index in to_remove: order_form.order_line.remove(index) order_form.save() class SaleOrderRecommendationLine(models.TransientModel): _name = "sale.order.recommendation.line" _description = "Recommended product for current sale order" _order = "id" currency_id = fields.Many2one(related="product_id.currency_id") partner_id = fields.Many2one(related="wizard_id.order_id.partner_id") product_id = fields.Many2one("product.product", string="Product") price_unit = fields.Monetary(compute="_compute_price_unit") pricelist_id = fields.Many2one(related="wizard_id.order_id.pricelist_id") times_delivered = fields.Integer(readonly=True) units_delivered = fields.Float(readonly=True) units_included = fields.Float() wizard_id = fields.Many2one( "sale.order.recommendation", "Wizard", ondelete="cascade", required=True, readonly=True, ) sale_line_id = fields.Many2one(comodel_name="sale.order.line") sale_uom_id = fields.Many2one(related="sale_line_id.product_uom") @api.depends( "partner_id", "product_id", "pricelist_id", "units_included", "wizard_id.sale_recommendation_price_origin", ) def _compute_price_unit(self): """ Get product price unit from product list price or from last sale price """ price_origin = ( fields.first(self).wizard_id.sale_recommendation_price_origin or "pricelist" ) for one in self: if price_origin == "pricelist": one.price_unit = one.product_id.with_context( partner=one.partner_id.id, pricelist=one.pricelist_id.id, quantity=one.units_included, ).price else: one.price_unit = one._get_last_sale_price_product() def _prepare_update_so_line(self, line_form): """So we can extend SO update""" line_form.product_uom_qty = self.units_included def _prepare_new_so_line(self, line_form, sequence): """So we can extend SO create""" line_form.product_id = self.product_id line_form.sequence = sequence line_form.product_uom_qty = self.units_included if self.wizard_id.sale_recommendation_price_origin == "last_sale_price": line_form.price_unit = self.price_unit def _get_last_sale_price_product(self): """ Get last price from last order. Use sudo to read sale order from other users like as other commercials. """ self.ensure_one() so = ( self.env["sale.order"] .sudo() .search( [ ("company_id", "=", self.wizard_id.order_id.company_id.id), ("partner_id", "=", self.partner_id.id), ("date_order", "!=", False), ("state", "not in", ("draft", "sent", "cancel")), ("order_line.product_id", "=", self.product_id.id), ], limit=1, order="date_order DESC, id DESC", ) ) so_line = ( self.env["sale.order.line"] .sudo() .search( [("order_id", "=", so.id), ("product_id", "=", self.product_id.id)], limit=1, order="id DESC", ) .with_context(prefetch_fields=False) ) return so_line.price_unit or 0.0
38.835088
11,068
799
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) { "name": "Sales Invoice Plan", "summary": "Add to sales order, ability to manage future invoice plan", "version": "15.0.1.3.2", "author": "Ecosoft,Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/sale-workflow", "category": "Sales", "depends": ["account", "sale_management"], "data": [ "security/ir.model.access.csv", "data/sale_data.xml", "wizard/sale_create_invoice_plan_view.xml", "wizard/sale_make_planned_invoice_view.xml", "views/sale_view.xml", ], "installable": True, "development_status": "Alpha", "maintainers": ["kittiu"], }
34.73913
799
12,802
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) import logging from odoo import _, fields from odoo.exceptions import UserError, ValidationError from odoo.tests import Form, tagged from odoo.addons.sale.tests import common _logger = logging.getLogger(__name__) @tagged("post_install", "-at_install") class TestSaleInvoicePlan(common.TestSaleCommon): @classmethod def setUpClass(cls): super(TestSaleInvoicePlan, cls).setUpClass() context_no_mail = { "no_reset_password": True, "mail_create_nosubscribe": True, "mail_create_nolog": True, } # Create base account to simulate a chart of account user_type_payable = cls.env.ref("account.data_account_type_payable") cls.account_payable = cls.env["account.account"].create( { "code": "NC1110", "name": "Test Payable Account", "user_type_id": user_type_payable.id, "reconcile": True, } ) user_type_receivable = cls.env.ref("account.data_account_type_receivable") cls.account_receivable = cls.env["account.account"].create( { "code": "NC1111", "name": "Test Receivable Account", "user_type_id": user_type_receivable.id, "reconcile": True, } ) Partner = cls.env["res.partner"].with_context(**context_no_mail) cls.partner_customer_usd = Partner.create( { "name": "Customer from the North", "email": "customer.usd@north.com", "property_account_payable_id": cls.account_payable.id, "property_account_receivable_id": cls.account_receivable.id, } ) cls.sale_journal0 = cls.env["account.journal"].create( { "name": "Sale Journal", "type": "sale", "code": "SJT0", } ) cls.setUpClassicProducts() sale_obj = cls.env["sale.order"] # Create an SO for Service cls.so_service = sale_obj.with_user( cls.company_data["default_user_salesman"] ).create( { "partner_id": cls.partner_customer_usd.id, "partner_invoice_id": cls.partner_customer_usd.id, "partner_shipping_id": cls.partner_customer_usd.id, "use_invoice_plan": True, "order_line": [ ( 0, 0, { "name": cls.product_order.name, "product_id": cls.product_order.id, "product_uom_qty": 1, "product_uom": cls.product_order.uom_id.id, "price_unit": cls.product_order.list_price, }, ) ], "pricelist_id": cls.env.ref("product.list0").id, } ) @classmethod def setUpClassicProducts(cls): # Create an expense journal user_type_income = cls.env.ref("account.data_account_type_direct_costs") cls.account_income_product = cls.env["account.account"].create( { "code": "INCOME_PROD111", "name": "Icome - Test Account", "user_type_id": user_type_income.id, } ) # Create category cls.product_category = cls.env["product.category"].create( { "name": "Product Category with Income account", "property_account_income_categ_id": cls.account_income_product.id, } ) # Products uom_unit = cls.env.ref("uom.product_uom_unit") cls.product_order = cls.env["product.product"].create( { "name": "Zed+ Antivirus", "standard_price": 235.0, "list_price": 280.0, "type": "consu", "uom_id": uom_unit.id, "uom_po_id": uom_unit.id, "invoice_policy": "order", "expense_policy": "no", "default_code": "PROD_ORDER", "service_type": "manual", "taxes_id": False, "categ_id": cls.product_category.id, } ) def test_00_invoice_plan(self): # To create next invoice from SO ctx = { "active_id": self.so_service.id, "active_ids": [self.so_service.id], "all_remain_invoices": False, } f = Form(self.env["sale.create.invoice.plan"]) try: # UserError if no installment plan = f.save() except ValidationError as e: _logger.info(_("No installment raises following error : %s"), e.args[0]) # Create Invoice Plan 3 installment num_installment = 5 f.num_installment = num_installment # Test 3 types of interval for interval_type in ["month", "year", "day"]: f.interval_type = interval_type plan = f.save() # SO confirmed without invoice plan being created if not self.so_service.invoice_plan_ids: with self.assertRaises(UserError): self.so_service.action_confirm() # Create Invocie Plan Installment plan.with_context(**ctx).sale_create_invoice_plan() self.assertEqual( len(self.so_service.invoice_plan_ids), num_installment, "Wrong number of installment created", ) # Change plan, so that the 1st installment is 1000 and 5th is 3000 self.assertEqual(len(self.so_service.invoice_plan_ids), 5) self.so_service.invoice_plan_ids[0].amount = 280.0 self.so_service.invoice_plan_ids[4].amount = 840.0 # Confirm the SO self.so_service.action_confirm() # Create one invoice make_wizard = self.env["sale.make.planned.invoice"].create({}) make_wizard.with_context(**ctx).create_invoices_by_plan() self.assertEqual( self.so_service.amount_total, sum(self.so_service.invoice_ids.mapped("amount_total")), ) invoices = self.so_service.invoice_ids self.assertEqual(len(invoices), 1, "Only 1 invoice should be created") def test_01_invoice_plan(self): # To create all remaining invoice from SO ctx = { "active_id": self.so_service.id, "active_ids": [self.so_service.id], "advance_payment_method": "delivered", "all_remain_invoices": True, } f = Form(self.env["sale.create.invoice.plan"]) # Create Invoice Plan 3 installment num_installment = 3 # Test 3 types of interval for interval_type in ["month", "year", "day"]: f.interval_type = interval_type f.num_installment = num_installment plan = f.save() plan.with_context(**ctx).sale_create_invoice_plan() # Confirm the SO self.so_service.action_confirm() # Create all invoices make_wizard = self.env["sale.make.planned.invoice"].create({}) make_wizard.with_context(**ctx).create_invoices_by_plan() # Valid number of invoices invoices = self.so_service.invoice_ids self.assertEqual( len(invoices), num_installment, "Wrong number of invoice created" ) # Valid total quantity of invoices quantity = sum(invoices.mapped("invoice_line_ids").mapped("quantity")) self.assertEqual(quantity, 1, "Wrong number of total invoice quantity") def test_02_invoice_plan_with_advance(self): # To create all remaining invoice from SO ctx = { "active_id": self.so_service.id, "active_ids": [self.so_service.id], "all_remain_invoices": True, } # Create Invoice Plan 3 installment with Advance num_installment = 3 f = Form(self.env["sale.create.invoice.plan"]) f.num_installment = num_installment f.advance = True # Advance plan = f.save() plan.with_context(**ctx).sale_create_invoice_plan() self.assertEqual( len(self.so_service.invoice_plan_ids), num_installment + 1, "Wrong number of installment created", ) # If advance percent is not filled, show error with self.assertRaises(ValidationError): self.so_service.action_confirm() advance_line = self.so_service.invoice_plan_ids.filtered( lambda l: l.invoice_type == "advance" ) self.assertEqual(len(advance_line), 1, "No one advance line") # Add 10% to advance advance_line.percent = 10 # Can confirm the SO after advance is filled self.so_service.action_confirm() # Create all invoice plan wizard = self.env["sale.make.planned.invoice"].create({}) wizard.with_context(**ctx).create_invoices_by_plan() # Valid number of invoices, including advance invoices = self.so_service.invoice_ids self.assertEqual( len(invoices), num_installment + 1, "Wrong number of invoice created" ) # Valid total quantity of invoices (exclude Advance line) quantity = sum( invoices.mapped("invoice_line_ids") .filtered(lambda l: l.product_id == self.product_order) .mapped("quantity") ) self.assertEqual(quantity, 1, "Wrong number of total invoice quantity") def test_03_unlink_invoice_plan(self): ctx = {"active_id": self.so_service.id, "active_ids": [self.so_service.id]} f = Form(self.env["sale.create.invoice.plan"]) # Create Invoice Plan 3 installment num_installment = 3 f.num_installment = num_installment plan = f.save() plan.with_context(**ctx).sale_create_invoice_plan() # Remove it self.so_service.remove_invoice_plan() self.assertFalse(self.so_service.invoice_plan_ids) def test_invoice_plan_so_edit(self): """Case when some installment already invoiced, but then, the SO line added. Test to ensure that the invoiced amount of the done installment is fixed""" ctx = { "active_id": self.so_service.id, "active_ids": [self.so_service.id], "all_remain_invoices": False, } first_order_line = fields.first(self.so_service.order_line) first_order_line.product_uom_qty = 10 f = Form(self.env["sale.create.invoice.plan"]) # Create Invoice Plan 5 installment num_installment = 5 f.num_installment = num_installment plan = f.save() plan.with_context(**ctx).sale_create_invoice_plan() # Change plan, so that the 1st installment is 280 and 5th is 840 self.assertEqual(len(self.so_service.invoice_plan_ids), 5) first_install = self.so_service.invoice_plan_ids[0] first_install.amount = 280.0 self.so_service.invoice_plan_ids[4].amount = 840.0 self.so_service.action_confirm() self.assertEqual(self.so_service.state, "sale") sale_create = self.env["sale.make.planned.invoice"].create({}) # Create only the 1st invoice, amount should be 280, and percent is 10 sale_create.with_context(**ctx).create_invoices_by_plan() self.assertEqual(first_install.amount, 280.0) self.assertEqual(first_install.percent, 10) # Add new SO line with amount = 280, check that only percent is changed self.so_service.write( { "order_line": [ ( 0, 0, { "name": "SO-Product-NEW", "product_id": self.product_order.id, "product_uom_qty": 1, "product_uom": self.product_order.uom_id.id, "price_unit": 280.0, }, ) ], } ) # Overall amount changed to 3080, install amount not changed, only percent changed. self.assertEqual(self.so_service.amount_total, 3080.0) self.so_service.invoice_plan_ids._compute_amount() self.assertEqual(first_install.amount, 280.0) self.assertEqual(first_install.percent, 9.090909)
40.64127
12,802
601
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import models class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" def _create_invoice(self, order, so_line, amount): invoice = super()._create_invoice(order, so_line, amount) invoice_plan_id = self._context.get("invoice_plan_id") if invoice_plan_id: plan = self.env["sale.invoice.plan"].browse(invoice_plan_id) plan.invoice_move_ids += invoice return invoice
40.066667
601
1,552
py
PYTHON
15.0
# Copyright 2019 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 from odoo.exceptions import ValidationError class SaleCreateInvoicePlan(models.TransientModel): _name = "sale.create.invoice.plan" _description = "Fillig invoice planning criteria" advance = fields.Boolean( string="Advance on 1st Invoice", default=False, ) num_installment = fields.Integer( string="Number of Installment", default=0, required=True, ) installment_date = fields.Date( default=fields.Date.context_today, required=True, ) interval = fields.Integer( default=1, required=True, ) interval_type = fields.Selection( [("day", "Day"), ("month", "Month"), ("year", "Year")], default="month", required=True, ) @api.constrains("num_installment") def _check_num_installment(self): for rec in self: if rec.num_installment <= 1: raise ValidationError(_("Number Installment must greater than 1")) def sale_create_invoice_plan(self): sale = self.env["sale.order"].browse(self._context.get("active_id")) self.ensure_one() sale.create_invoice_plan( self.num_installment, self.installment_date, self.interval, self.interval_type, self.advance, ) return {"type": "ir.actions.act_window_close"}
31.04
1,552
1,229
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import models class SaleAdvancePaymentInv(models.TransientModel): _name = "sale.make.planned.invoice" _description = "Wizard when create invoice by plan" def create_invoices_by_plan(self): sale = self.env["sale.order"].browse(self._context.get("active_id")) sale.ensure_one() MakeInvoice = self.env["sale.advance.payment.inv"] invoice_plans = ( self._context.get("all_remain_invoices") and sale.invoice_plan_ids.filtered(lambda l: not l.invoiced) or sale.invoice_plan_ids.filtered("to_invoice") ) for plan in invoice_plans.sorted("installment"): makeinv_wizard = {"advance_payment_method": "delivered"} if plan.invoice_type == "advance": makeinv_wizard["advance_payment_method"] = "percentage" makeinv_wizard["amount"] = plan.percent makeinvoice = MakeInvoice.create(makeinv_wizard) makeinvoice.sudo().with_context(invoice_plan_id=plan.id).create_invoices() return {"type": "ir.actions.act_window_close"}
47.269231
1,229
7,285
py
PYTHON
15.0
from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools.float_utils import float_compare, float_round class SaleInvoicePlan(models.Model): _name = "sale.invoice.plan" _description = "Invoice Planning Detail" _order = "installment" sale_id = fields.Many2one( comodel_name="sale.order", string="Sales Order", index=True, readonly=True, ondelete="cascade", ) analytic_account_id = fields.Many2one(related="sale_id.analytic_account_id") partner_id = fields.Many2one( comodel_name="res.partner", string="Customer", related="sale_id.partner_id", store=True, index=True, ) state = fields.Selection( string="Status", related="sale_id.state", store=True, index=True, ) installment = fields.Integer() plan_date = fields.Date(required=True) invoice_type = fields.Selection( [("advance", "Advance"), ("installment", "Installment")], string="Type", required=True, default="installment", ) last = fields.Boolean( string="Last Installment", compute="_compute_last", help="Last installment will create invoice use remaining amount", ) percent = fields.Float( digits="Sales Invoice Plan Percent", help="This percent will be used to calculate new quantity", ) amount = fields.Float( digits="Product Price", compute="_compute_amount", inverse="_inverse_amount", help="This amount will be used to calculate the percent", ) invoice_move_ids = fields.Many2many( "account.move", relation="sale_invoice_plan_invoice_rel", column1="plan_id", column2="move_id", string="Invoices", readonly=True, ) amount_invoiced = fields.Float(compute="_compute_invoiced") to_invoice = fields.Boolean( string="Next Invoice", compute="_compute_to_invoice", help="If this line is ready to create new invoice", ) invoiced = fields.Boolean( string="Invoice Created", compute="_compute_invoiced", help="If this line already invoiced", ) no_edit = fields.Boolean( compute="_compute_no_edit", ) _sql_constraint = [ ( "unique_instalment", "UNIQUE (sale_id, installment)", "Installment must be unique on invoice plan", ) ] def _no_edit(self): self.ensure_one() return self.invoiced def _compute_no_edit(self): for rec in self: rec.no_edit = rec._no_edit() @api.depends("percent") def _compute_amount(self): for rec in self: # With invoice already created, no recompute if rec.invoiced: rec.amount = rec.amount_invoiced rec.percent = rec.amount / rec.sale_id.amount_untaxed * 100 continue # For last line, amount is the left over if rec.last: installments = rec.sale_id.invoice_plan_ids.filtered( lambda l: l.invoice_type == "installment" ) prev_amount = sum((installments - rec).mapped("amount")) rec.amount = rec.sale_id.amount_untaxed - prev_amount continue rec.amount = rec.percent * rec.sale_id.amount_untaxed / 100 @api.onchange("amount", "percent") def _inverse_amount(self): for rec in self: if rec.sale_id.amount_untaxed != 0: if rec.last: installments = rec.sale_id.invoice_plan_ids.filtered( lambda l: l.invoice_type == "installment" ) prev_percent = sum((installments - rec).mapped("percent")) rec.percent = 100 - prev_percent continue rec.percent = rec.amount / rec.sale_id.amount_untaxed * 100 continue rec.percent = 0 def _compute_to_invoice(self): """If any invoice is in draft/open/paid do not allow to create inv. Only if previous to_invoice is False, it is eligible to_invoice. """ for rec in self: rec.to_invoice = False for rec in self.sorted("installment"): if rec.state != "sale": # Not confirmed, no to_invoice continue if not rec.invoiced: rec.to_invoice = True break def _compute_invoiced(self): for rec in self: invoiced = rec.invoice_move_ids.filtered( lambda l: l.state in ("draft", "posted") ) rec.invoiced = invoiced and True or False rec.amount_invoiced = invoiced[:1].amount_untaxed def _compute_last(self): for rec in self: last = max(rec.sale_id.invoice_plan_ids.mapped("installment")) rec.last = rec.installment == last def _compute_new_invoice_quantity(self, invoice_move): self.ensure_one() if self.last: # For last install, let the system do the calc. return percent = self.percent move = invoice_move.with_context(check_move_validity=False) for line in move.invoice_line_ids: self._update_new_quantity(line, percent) move.line_ids.filtered("exclude_from_invoice_tab").unlink() move._move_autocomplete_invoice_lines_values() # recompute dr/cr def _update_new_quantity(self, line, percent): """Hook function""" if not len(line.sale_line_ids) >= 0: raise UserError(_("No matched order line for invoice line")) order_line = fields.first(line.sale_line_ids) if order_line.is_downpayment: # based on 1 unit line.write({"quantity": -percent / 100}) else: plan_qty = self._get_plan_qty(order_line, percent) prec = order_line.product_uom.rounding if plan_qty: plan_qty = float_round(plan_qty, precision_rounding=prec) if float_compare(abs(plan_qty), abs(line.quantity), prec) == 1: raise ValidationError( _( "Plan quantity: %(plan_qty)s, exceed invoiceable quantity: " "%(invoiceable_qty)s" "\nProduct should be delivered before invoice" ) % {"plan_qty": plan_qty, "invoiceable_qty": line.quantity} ) line.write({"quantity": plan_qty}) @api.model def _get_plan_qty(self, order_line, percent): plan_qty = order_line.product_uom_qty * (percent / 100) return plan_qty def unlink(self): lines = self.filtered("no_edit") if lines: installments = [str(x) for x in lines.mapped("installment")] raise UserError( _( "Installment %s: already used and not allowed to delete.\n" "Please discard changes." ) % ", ".join(installments) ) return super().unlink()
35.8867
7,285
5,796
py
PYTHON
15.0
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from dateutil.relativedelta import relativedelta from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError from odoo.tools.float_utils import float_round class SaleOrder(models.Model): _inherit = "sale.order" invoice_plan_ids = fields.One2many( comodel_name="sale.invoice.plan", inverse_name="sale_id", string="Inovice Plan", copy=False, ) use_invoice_plan = fields.Boolean( default=False, copy=False, ) invoice_plan_process = fields.Boolean( string="Invoice Plan In Process", compute="_compute_invoice_plan_process", help="At least one invoice plan line pending to create invoice", ) invoice_plan_total_percent = fields.Float( compute="_compute_invoice_plan_total", string="Percent", ) invoice_plan_total_amount = fields.Monetary( compute="_compute_invoice_plan_total", string="Total Amount", ) @api.depends("invoice_plan_ids") def _compute_invoice_plan_total(self): for rec in self: installments = rec.invoice_plan_ids.filtered("installment") rec.invoice_plan_total_percent = sum(installments.mapped("percent")) rec.invoice_plan_total_amount = sum(installments.mapped("amount")) def _compute_invoice_plan_process(self): for rec in self: has_invoice_plan = rec.use_invoice_plan and rec.invoice_plan_ids to_invoice = rec.invoice_plan_ids.filtered(lambda l: not l.invoiced) if rec.state == "sale" and has_invoice_plan and to_invoice: if rec.invoice_status == "to invoice" or ( rec.invoice_status == "no" and "advance" in to_invoice.mapped("invoice_type") ): rec.invoice_plan_process = True continue rec.invoice_plan_process = False @api.constrains("invoice_plan_ids") def _check_invoice_plan_total_percent(self): for rec in self: installments = rec.invoice_plan_ids.filtered("installment") invoice_plan_total_percent = sum(installments.mapped("percent")) if float_round(invoice_plan_total_percent, 0) > 100: raise UserError(_("Invoice plan total percentage must not exceed 100%")) @api.constrains("state") def _check_invoice_plan(self): for rec in self: if rec.state != "draft": if rec.invoice_plan_ids.filtered(lambda l: not l.percent): raise ValidationError( _("Please fill percentage for all invoice plan lines") ) def action_confirm(self): if self.filtered(lambda r: r.use_invoice_plan and not r.invoice_plan_ids): raise UserError(_("Use Invoice Plan selected, but no plan created")) return super().action_confirm() def create_invoice_plan( self, num_installment, installment_date, interval, interval_type, advance ): self.ensure_one() self.invoice_plan_ids.unlink() invoice_plans = [] Decimal = self.env["decimal.precision"] prec = Decimal.precision_get("Sales Invoice Plan Percent") percent = float_round(1.0 / num_installment * 100, prec) percent_last = 100 - (percent * (num_installment - 1)) # Advance if advance: vals = { "installment": 0, "plan_date": installment_date, "invoice_type": "advance", "percent": 0.0, } invoice_plans.append((0, 0, vals)) installment_date = self._next_date( installment_date, interval, interval_type ) # Normal for i in range(num_installment): this_installment = i + 1 if num_installment == this_installment: percent = percent_last vals = { "installment": this_installment, "plan_date": installment_date, "invoice_type": "installment", "percent": percent, } invoice_plans.append((0, 0, vals)) installment_date = self._next_date( installment_date, interval, interval_type ) self.write({"invoice_plan_ids": invoice_plans}) return True def remove_invoice_plan(self): self.ensure_one() self.invoice_plan_ids.unlink() return True @api.model def _next_date(self, installment_date, interval, interval_type): installment_date = fields.Date.from_string(installment_date) if interval_type == "month": next_date = installment_date + relativedelta(months=+interval) elif interval_type == "year": next_date = installment_date + relativedelta(years=+interval) else: next_date = installment_date + relativedelta(days=+interval) next_date = fields.Date.to_string(next_date) return next_date def _create_invoices(self, grouped=False, final=False, date=None): moves = super()._create_invoices(grouped=grouped, final=final, date=date) invoice_plan_id = self._context.get("invoice_plan_id") if invoice_plan_id: plan = self.env["sale.invoice.plan"].browse(invoice_plan_id) for move in moves: plan._compute_new_invoice_quantity(move) move.invoice_date = plan.plan_date move._onchange_invoice_date() plan.invoice_move_ids += moves return moves
39.69863
5,796
688
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Sale Invoice Blocking", "summary": "Allow you to block the creation of invoices from a sale order.", "version": "15.0.1.0.0", "author": "Camptocamp, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "category": "Sales", "depends": ["sale", "sales_team"], "data": [ "security/ir.model.access.csv", "views/sale_invoice_blocking_reason_view.xml", "views/sale_order.xml", "views/menus.xml", ], "license": "AGPL-3", "installable": True, "application": False, }
32.761905
688
502
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class InvoiceBlockingReason(models.Model): _name = "invoice.blocking.reason" _description = "Sale invoice blocking reason" name = fields.Char(string="Reason", required=True) _sql_constraints = [ ( "name_uniq", "unique (name)", "You cannot have two invoice blocking reasons with the same name.", ) ]
27.888889
502
1,338
py
PYTHON
15.0
# Copyright 2021 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError class SaleOrder(models.Model): _inherit = "sale.order" invoice_blocking_reason_id = fields.Many2one( "invoice.blocking.reason", string="Blocking for invoicing", ) @api.depends("invoice_blocking_reason_id", "state", "order_line.invoice_status") def _get_invoice_status(self): res = super()._get_invoice_status() for order in self.filtered( lambda order: order.invoice_blocking_reason_id and order.state in ("sale", "done") ): order.invoice_status = "no" return res def _get_invoiceable_lines(self, final=False): """Return the invoiceable lines for order `self`.""" if self.invoice_blocking_reason_id: return self.env["sale.order.line"] return super()._get_invoiceable_lines(final=final) @api.model def _nothing_to_invoice_error(self): error = super()._nothing_to_invoice_error() msg = [x for x in error.args] msg.append( _( """ - You may have an invoice blocking reason on the sale order """ ) ) return UserError(msg)
30.409091
1,338
453
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Sale Force Whole Invoiceability", "version": "15.0.1.0.0", "category": "Sales", "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "license": "AGPL-3", "depends": ["sale"], "data": ["views/sale_order_views.xml"], "installable": True, }
34.846154
453
3,965
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.exceptions import UserError from odoo.tests import Form, common, new_test_user, users class SaleOrderForceInvoiceability(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.products = cls.env["product.product"].create( {"name": "test product 1", "invoice_policy": "order"} ) cls.products |= cls.env["product.product"].create( {"name": "test product 2", "invoice_policy": "delivery"} ) new_test_user( cls.env, login="test-sale-user", groups="sales_team.group_sale_salesman_all_leads", ) new_test_user( cls.env, login="test-sale-manager", groups="sales_team.group_sale_manager", ) sale = Form(cls.env["sale.order"]) sale.partner_id = cls.env["res.partner"].create({"name": "Mr. Odoo"}) for product in cls.products: with sale.order_line.new() as order_line: order_line.product_id = product order_line.product_uom_qty = 5 cls.sale_order = sale.save() @users("admin", "test-sale-manager") def test_01_force_invoiceability_draft(self): """Try to force invoiceability""" # The order is still not in `sale` mode so we can't force it self.sale_order = self.env["sale.order"].browse(self.sale_order.id) with self.assertRaises(UserError) as cm: self.sale_order.force_lines_to_invoice_policy_order() self.assertEqual( "You can't perform this action over a sale order in this state", cm.exception.args[0], ) @users("test-sale-user") def test_02_force_invoiceability_no_permissions(self): # Only users with sales manager permission can force the lines self.sale_order = self.env["sale.order"].browse(self.sale_order.id) self.sale_order.action_confirm() with self.assertRaises(UserError) as cm: self.sale_order.force_lines_to_invoice_policy_order() self.assertEqual( "Only Sales Managers are allowed to force the lines to invoice", cm.exception.args[0], ) def test_03_force_invoiceable_lines(self): self.sale_order = self.env["sale.order"].browse(self.sale_order.id) self.sale_order.action_confirm() # Only the product with *Ordered quantities* policy has its line # quantities `to invoice` self.assertAlmostEqual( 5, sum(self.sale_order.mapped("order_line.qty_to_invoice")) ) self.sale_order.force_lines_to_invoice_policy_order() # Now the whole order qty is `to invoice` self.assertAlmostEqual( 10, sum(self.sale_order.mapped("order_line.qty_to_invoice")) ) # Although no quantities are delivered yet self.assertTrue(not any(self.sale_order.mapped("order_line.qty_delivered"))) # Let's make the invoice adv_wiz = ( self.env["sale.advance.payment.inv"] .with_context(active_ids=[self.sale_order.id]) .create({"advance_payment_method": "delivered"}) ) adv_wiz.with_context(open_invoices=True).create_invoices() self.assertEqual(10, sum(self.sale_order.mapped("order_line.qty_invoiced"))) # We can't use the force action anymore once there's an invoice linked with self.assertRaises(UserError) as cm: self.sale_order.force_lines_to_invoice_policy_order() self.assertEqual( "You can't perform this action once the order has been invoiced " "once already", cm.exception.args[0], ) @users("test-sale-manager") def test_03_force_invoiceable_lines_extra(self): self.test_03_force_invoiceable_lines()
42.634409
3,965
987
py
PYTHON
15.0
# Copyright 2021 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, models from odoo.exceptions import UserError class SaleOrder(models.Model): _inherit = "sale.order" def force_lines_to_invoice_policy_order(self): """Wrapper to launch the private method from UI""" if not self.user_has_groups("sales_team.group_sale_manager"): raise UserError( _("Only Sales Managers are allowed to force the lines to invoice") ) if self.state != "sale": raise UserError( _("You can't perform this action over a sale order in this state") ) if self.invoice_count: raise UserError( _( "You can't perform this action once the order has been " "invoiced once already" ) ) self._force_lines_to_invoice_policy_order()
36.555556
987
812
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Product Last Price Info - Sale", "version": "15.0.1.0.1", "author": "AvanzOSC, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "category": "Sales", "license": "AGPL-3", "contributors": [ "Alfredo de la Fuente <alfredodelafuente@avanzosc.es>", "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", "Serpent Consulting Services Pvt. Ltd. <support@serpentcs.com>", "Ruchir Shukla <ruchir@bizzappdev.com>", ], "depends": ["sale_management"], "data": ["views/product_view.xml"], "installable": True, }
36.909091
812
1,202
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common class TestSaleLastPriceInfo(common.TransactionCase): def setUp(self): super(TestSaleLastPriceInfo, self).setUp() self.sale_order_model = self.env["sale.order"] self.sale_line_model = self.env["sale.order.line"] self.sale_order = self.env.ref("sale.sale_order_4") self.sale_line = self.env.ref("sale.sale_order_line_9") self.partner = self.env.ref("base.res_partner_3") self.product = self.env.ref("product.product_delivery_02") self.price_unit = 100.0 def test_sale_last_price_info_demo(self): sale_line = self.sale_line_model.search( [("product_id", "=", self.product.id), ("state", "in", ["sale", "done"])], limit=1, order="date_order_sale_last_price_info desc", ) self.assertEqual( sale_line.date_order_sale_last_price_info.date(), self.product.last_sale_date, ) self.assertEqual(sale_line.price_unit, self.product.last_sale_price) self.assertEqual(sale_line.order_id.partner_id, self.product.last_customer_id)
42.928571
1,202
1,094
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProductProduct(models.Model): _inherit = "product.product" def _compute_last_sale(self): """Get last sale price, last sale date and last customer""" so_line_obj = self.env["sale.order.line"] for product in self: line = so_line_obj.search( [("product_id", "=", product.id), ("state", "in", ["sale", "done"])], limit=1, order="date_order_sale_last_price_info desc", ) product.last_sale_date = fields.Datetime.to_string( line.date_order_sale_last_price_info ) product.last_sale_price = line.price_unit product.last_customer_id = line.order_id.partner_id last_sale_price = fields.Float(compute="_compute_last_sale") last_sale_date = fields.Date(compute="_compute_last_sale") last_customer_id = fields.Many2one( comodel_name="res.partner", string="Last Customer", compute="_compute_last_sale" )
39.071429
1,094
317
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" date_order_sale_last_price_info = fields.Datetime( string="Order date", related="order_id.date_order", store=True, index=True )
28.818182
317
521
py
PYTHON
15.0
# Copyright 2021 Akretion - Florian Mounier { "name": "Sale Order Report Without Price", "summary": "Allow you to generate quotation and order reports without price.", "version": "15.0.1.0.0", "author": "Akretion, Open Source Integrators, Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "category": "Sales", "depends": ["sale"], "data": [ "report/sale_report.xml", "report/sale_report_templates.xml", ], "license": "LGPL-3", }
34.733333
521
602
py
PYTHON
15.0
# Copyright 2022 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Attached products in sales", "summary": "Define products that will be added automatically when adding another " "in a sales order", "version": "15.0.1.0.0", "development_status": "Beta", "category": "Sale", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "maintainers": ["chienandalu"], "license": "AGPL-3", "depends": ["sale"], "data": ["views/product_template_views.xml"], }
37.625
602
7,218
py
PYTHON
15.0
# Copyright 2022 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests import Form, TransactionCase class TestSaleAttachedProduct(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # No need for tracking and we scratch some seconds cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.pricelist = cls.env["product.pricelist"].create( { "name": "Test pricelist", "item_ids": [ ( 0, 0, { "applied_on": "3_global", "compute_price": "formula", "base": "list_price", }, ) ], } ) cls.partner = cls.env["res.partner"].create( {"name": "Mr. Odoo", "property_product_pricelist": cls.pricelist.id} ) cls.product_1 = cls.env["product.product"].create( {"name": "Test 1", "sale_ok": True, "list_price": 50} ) cls.product_2 = cls.env["product.product"].create( {"name": "Test 2", "sale_ok": False, "list_price": 60} ) cls.product_3 = cls.env["product.product"].create( {"name": "Test 3", "sale_ok": False, "list_price": 70} ) cls.product_4 = cls.env["product.product"].create( {"name": "Test 4", "sale_ok": False, "list_price": 80} ) cls.product_5 = cls.env["product.product"].create( {"name": "Test 4", "sale_ok": False, "list_price": 80} ) cls.product_1.product_tmpl_id.attached_product_ids = ( cls.product_2 + cls.product_3 ) # We'll be using this sale order sale_form = Form(cls.env["sale.order"]) sale_form.partner_id = cls.partner cls.sale = sale_form.save() def _add_product(self, sale, product, qty=1): """Auxiliar method to quickly add products to a sale order""" sale_form = Form(sale) with sale_form.order_line.new() as line_form: line_form.product_id = product line_form.product_uom_qty = qty sale_form.save() def _get_attached_lines(self, sale): return sale.order_line.filtered("is_attached_line") def test_01_attach_product_modifiable(self): """Every time we add a product with attached products we'll adding extra lines automatically""" # When we add a product with attached products defined on it the module will add # as many lines as attached products self._add_product(self.sale, self.product_1) product_1_line = self.sale.order_line.filtered( lambda x: x.product_id == self.product_1 ) self.assertEqual( len(self.sale.order_line), 3, "Two extra lines should have been added automatically", ) self.assertEqual( self._get_attached_lines(self.sale).product_id, self.product_1.product_tmpl_id.attached_product_ids, "The attached lines products should correspond with those defined in the " "product", ) # Once added, we can edit the lines independetly product_1_line.product_uom_qty = 3 self.assertTrue( all(x.product_uom_qty == 1 for x in self._get_attached_lines(self.sale)) ) # We can delete attached lines in this mode self.sale.order_line.filtered(lambda x: x.product_id == self.product_2).unlink() self.assertEqual( len(self.sale.order_line), 2, "The line should stay removed", ) # Removing the main line will kill the optional ones anyway product_1_line.unlink() self.assertFalse( self._get_attached_lines(self.sale), "There should be no attached lines" ) def test_02_attach_product_auto_update(self): """Every time we add a product with attached products we'll adding extra lines automatically. Those lines will be persistent""" self.env["ir.config_parameter"].sudo().set_param( "sale_attached_product.auto_update_attached_lines", True ) # When we add a product with attached products defined on it the module will add # as many lines as attached products self._add_product(self.sale, self.product_1) product_1_line = self.sale.order_line.filtered( lambda x: x.product_id == self.product_1 ) self.assertEqual( len(self.sale.order_line), 3, "Two extra lines should have been added automatically", ) self.assertEqual( self._get_attached_lines(self.sale).product_id, self.product_1.product_tmpl_id.attached_product_ids, "The attached lines products should correspond with those defined in the " "product", ) # When we change the line quantity, the lines change theirs as well product_1_line.product_uom_qty = 3 self.assertTrue( all( x.product_uom_qty == product_1_line.product_uom_qty for x in self._get_attached_lines(self.sale) ) ) # When we delete an attached line, the module will recreate it to keep the # attached lines consitency self.sale.order_line.filtered(lambda x: x.product_id == self.product_2).unlink() self.assertEqual( len(self.sale.order_line), 3, "The removed line should be recreated", ) # Adding another product doesn't have any effect on the rest self._add_product(self.sale, self.product_4) self.assertEqual( len(self.sale.order_line), 4, "Product 4 doesn't have any attached products", ) # Changing the main line product will invalidate the attached lines product_1_line.product_id = self.product_5 self.assertEqual( len(self.sale.order_line), 2, "The new product doesn't have any attached products", ) self.assertFalse( self._get_attached_lines(self.sale), "There should be no attached lines" ) # If we change it back, the attached lines will be added back as well product_1_line.product_id = self.product_1 self.assertEqual( len(self.sale.order_line), 4, "The attached lines should be added again", ) self.assertEqual( self._get_attached_lines(self.sale).product_id, self.product_1.product_tmpl_id.attached_product_ids, "The attached lines products should correspond with those defined in the " "product", ) # Removing the main line, removes the attached lines product_1_line.unlink() self.assertFalse( self._get_attached_lines(self.sale), "There should be no attached lines" )
41.011364
7,218
9,386
py
PYTHON
15.0
# Copyright 2022 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleOrder(models.Model): _name = "sale.order" _inherit = ["sale.order", "sale.attached.product.mixin"] @api.model def _get_auto_refresh_attached_product_triggers(self) -> set: """Normally, we won't be needing any field from sale.order but order lines but it's configurable anyway.""" triggers = super()._get_auto_refresh_attached_product_triggers() order_line_triggers = ( self.order_line._get_auto_refresh_attached_product_triggers() ) for trigger in order_line_triggers: triggers.update({"order_line.{}".format(trigger)}) return triggers def _get_attached_line_values_product(self, line, product): """Prepare the values for the attached line. This is used for creating or updating.""" def _execute_onchanges(records, field_name): """Helper methods that executes all onchanges associated to a field.""" for onchange in records._onchange_methods.get(field_name, []): for record in records: onchange(record) # We prepare a new line and trigger the proper onchanges to ensure we get the # right line values (price unit according to the customer pricelist, taxes, ect) order_line = self.order_line.new( {"order_id": self.id, "product_id": product.id} ) _execute_onchanges(order_line, "product_id") order_line.update({"product_uom_qty": line.product_uom_qty}) _execute_onchanges(order_line, "product_uom_qty") vals = order_line._convert_to_write(order_line._cache) vals.update({"is_attached_line": True, "attached_from_line_id": line.id}) return vals def _create_attached_line(self, lines): """We create all the lines at once. This should be more performant""" vals_list = [] for line in lines: for product in line._get_attached_products(): vals_list.append(self._get_attached_line_values_product(line, product)) if vals_list: self.with_context(skip_auto_refresh_attached_product=True).write( {"order_line": [(0, False, value) for value in vals_list]} ) def _cleanup_attached_lines(self): """Remove those line which main line is already removed or wich main line product attachment won't match its lines.""" self.ensure_one() auto_update_attached_lines = ( self.env["ir.config_parameter"] .sudo() .get_param("sale_attached_product.auto_update_attached_lines") ) lines = self.order_line.filtered("is_attached_line") lines.filtered(lambda x: not x.attached_from_line_id).unlink() if not auto_update_attached_lines: return # We also want to remove those lines which main product doesn't match anymore # but only when auto update is on lines_with_attachements = self.order_line.filtered("attached_line_ids") for line in lines_with_attachements: attached_products = line._get_attached_products() line.attached_line_ids.with_context( skip_auto_refresh_attached_product=True ).filtered(lambda x: x.product_id not in attached_products).unlink() def _create_attached_lines(self): """New attached lines. After this, they'll be updated if there are changes in the main line.""" self.ensure_one() self._create_attached_line( self.order_line.filtered( lambda x: not x.attached_line_ids and x._get_attached_products() ) ) def _update_attached_lines(self): """Update attached lines values related to their main line.""" self.ensure_one() lines_with_attachements = self.order_line.filtered("attached_line_ids") lines_to_remove = self.env["sale.order.line"] missing_list = [] for line in lines_with_attachements: # Lines with no qty can be considered to be removed. if not line.product_uom_qty: lines_to_remove += line.attached_line_ids continue # For every unit of the main line there will another of the attached one attached_line_qtys = set(line.attached_line_ids.mapped("product_uom_qty")) if any(q != line.product_uom_qty for q in attached_line_qtys): line.attached_line_ids.update({"product_uom_qty": line.product_uom_qty}) # Trigger possible pricelist changes for attached_line in line.attached_line_ids: attached_line.product_uom_change() attached_products = line._get_attached_products() # Create missing products, for example in the case of a deleted attached # line. missing_products = { p for p in attached_products if p not in line.attached_line_ids.product_id } for product in missing_products: missing_list.append( self._get_attached_line_values_product(line, product) ) lines_to_remove.with_context(skip_auto_refresh_attached_product=True).unlink() self.with_context(skip_auto_refresh_attached_product=True).write( {"order_line": [(0, False, value) for value in missing_list]} ) def recompute_attached_products(self): """Recurrent method for recomputing attached lines. Always done in these three steps: 1. A cleanup of orphaned attached lines or attached lines that doesn't match their parent attached products anymore. 2. Creating new attached lines from lines which don't have them. 3. Updating existing attached lines. Mainly for quantity""" auto_update_attached_lines = ( self.env["ir.config_parameter"] .sudo() .get_param("sale_attached_product.auto_update_attached_lines") ) for order in self.filtered(lambda x: x.state not in {"done", "cancel"}): order._cleanup_attached_lines() order._create_attached_lines() auto_update_attached_lines and order._update_attached_lines() @api.model_create_multi def create(self, vals_list): if self._check_skip_attached_product_refresh(): return super().create(vals_list) orders = super().create(vals_list) orders.recompute_attached_products() return orders def write(self, vals): if self._check_skip_attached_product_refresh(): return super().write(vals) old_data = self._get_recs_data() self_ctx = self.with_context(skip_auto_refresh_attached_product=True) res = super(SaleOrder, self_ctx).write(vals) new_data = self._get_recs_data() if old_data != new_data: self.recompute_attached_products() return res class SaleOrderLine(models.Model): _name = "sale.order.line" _inherit = ["sale.order.line", "sale.attached.product.mixin"] is_attached_line = fields.Boolean( help="Flag products that are attached to their main counterpart" ) attached_from_line_id = fields.Many2one(comodel_name="sale.order.line") attached_line_ids = fields.One2many( comodel_name="sale.order.line", inverse_name="attached_from_line_id", ) def _get_attached_products(self): return self.product_id.product_tmpl_id.attached_product_ids.filtered( lambda x: not x.company_id or x.company_id == self.company_id ) @api.model_create_multi def create(self, vals_list): if self._check_skip_attached_product_refresh(): return super().create(vals_list) self_ctx = self.with_context(skip_auto_refresh_attached_product=True) lines = super(SaleOrderLine, self_ctx).create(vals_list) lines.mapped("order_id").recompute_attached_products() return lines def write(self, vals): if self._check_skip_attached_product_refresh(): return super().write(vals) old_data = self._get_recs_data() old_orders = self.mapped("order_id") self_ctx = self.with_context(skip_auto_refresh_attached_product=True) res = super(SaleOrderLine, self_ctx).write(vals) new_data = self._get_recs_data() new_orders = self.mapped("order_id") if old_data != new_data: (old_orders | new_orders).recompute_attached_products() return res def unlink(self): if self._check_skip_attached_product_refresh(): return super().unlink() orders = self.mapped("order_id") self_ctx = self.with_context(skip_auto_refresh_attached_product=True) res = super(SaleOrderLine, self_ctx).unlink() orders.recompute_attached_products() return res @api.model def _get_auto_refresh_attached_product_triggers(self) -> set: triggers = super()._get_auto_refresh_attached_product_triggers() triggers.update({"product_id", "product_uom", "product_uom_qty"}) return triggers
44.065728
9,386
1,492
py
PYTHON
15.0
# Copyright 2022 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleAttachedProductMixin(models.AbstractModel): _name = "sale.attached.product.mixin" _description = "Mixin class for sale attached product features" @api.model def _get_auto_refresh_attached_product_triggers(self) -> set: """Returns set of fields which trigger the recomputation. The method is overriden in the proper modules to set the proper triggers though """ return set() def _get_recs_data(self) -> list: """Allows to optimize the comparison before and after the write for the minimum possible set of fields""" triggers = self._get_auto_refresh_attached_product_triggers() recs_data = [] for rec in self: data = {} for dotted_field_name in triggers: val = rec.mapped(dotted_field_name) if isinstance(val, models.AbstractModel): val = val.ids data[dotted_field_name] = val recs_data.append({rec: data}) return recs_data def _check_skip_attached_product_refresh(self): """Checks whether refresh should be skipped Hook method to be overridden if necessary :return: True if auto-refresh should be skipped """ ctx = self.env.context return ctx.get("skip_auto_refresh_attached_product")
37.3
1,492
547
py
PYTHON
15.0
# Copyright 2022 Tecnativa - David Vidal # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductTemplate(models.Model): _inherit = "product.template" attached_product_ids = fields.Many2many( comodel_name="product.product", relation="product_attached_rel", string="Attached Products", help="Similar to optional products, although they're added automatically to the" "sale order and optionally removed when the main product goes away.", )
36.466667
547