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
633
py
PYTHON
15.0
# Copyright 2019 Akretion (<http://www.akretion.com>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Sub State", "version": "15.0.1.0.0", "category": "Tools", "author": "Akretion, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "license": "AGPL-3", "depends": ["base_substate", "sale_management"], "data": [ "views/sale_views.xml", "data/sale_substate_mail_template_data.xml", "data/sale_substate_data.xml", ], "demo": [ "data/sale_substate_demo.xml", ], "installable": True, }
30.142857
633
2,645
py
PYTHON
15.0
# Copyright 2019 Akretion Mourad EL HADJ MIMOUNE # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase class TestBaseSubstate(TransactionCase): def setUp(self): super(TestBaseSubstate, self).setUp() self.substate_test_sale = self.env["sale.order"] self.substate_test_sale_line = self.env["sale.order.line"] self.substate_under_nego = self.env.ref( "sale_substate.base_substate_under_nego" ) self.substate_won = self.env.ref("sale_substate.base_substate_won") self.substate_wait_docs = self.env.ref("sale_substate.base_substate_wait_docs") self.substate_valid_docs = self.env.ref( "sale_substate.base_substate_valid_docs" ) self.substate_in_delivery = self.env.ref( "sale_substate.base_substate_in_delivery" ) self.product_1 = self.env["product.product"].create( { "name": "Test Product 1", "type": "service", } ) def test_sale_order_substate(self): partner = self.env.ref("base.res_partner_1") so_test1 = self.substate_test_sale.create( { "name": "Test base substate to basic sale", "partner_id": partner.id, "order_line": [ ( 0, 0, { "product_id": self.product_1.id, "product_uom_qty": 2, "product_uom": self.product_1.uom_id.id, "name": "line test", "price_unit": 120.0, }, ) ], } ) self.assertTrue(so_test1.state == "draft") self.assertTrue(so_test1.substate_id == self.substate_under_nego) # Block substate not corresponding to draft state with self.assertRaises(ValidationError): so_test1.substate_id = self.substate_valid_docs # Test that validation of sale order change substate_id so_test1.action_confirm() self.assertTrue(so_test1.state == "sale") self.assertTrue(so_test1.substate_id == self.substate_valid_docs) # Test that substate_id is set to false if # there is not substate corresponding to state so_test1.action_cancel() self.assertTrue(so_test1.state == "cancel") self.assertTrue(not so_test1.substate_id)
38.897059
2,645
1,961
py
PYTHON
15.0
# Copyright 2019 Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class BaseSubstateType(models.Model): _inherit = "base.substate.type" model = fields.Selection( selection_add=[("sale.order", "Sale order")], ondelete={"sale.order": "cascade"} ) class SaleOrder(models.Model): _inherit = ["sale.order", "base.substate.mixin"] _name = "sale.order" @api.constrains("substate_id", "state") def check_substate_id_value(self): sale_states = dict(self._fields["state"].selection) for order in self: target_state = order.substate_id.target_state_value_id.target_state_value if order.substate_id and order.state != target_state: raise ValidationError( _( "The substate %(name)s is not defined for the state" " %(state)s but for %(target_state)s " ) % { "name": order.substate_id.name, "state": _(sale_states[order.state]), "target_state": _(sale_states[target_state]), } ) def _track_template(self, changes): res = super(SaleOrder, self)._track_template(changes) track = self[0] if "substate_id" in changes and track.substate_id.mail_template_id: res["substate_id"] = ( track.substate_id.mail_template_id, { "composition_mode": "comment", "auto_delete_message": True, "subtype_id": self.env["ir.model.data"]._xmlid_to_res_id( "mail.mt_note" ), "email_layout_xmlid": "mail.mail_notification_light", }, ) return res
37
1,961
649
py
PYTHON
15.0
# Copyright 2020 Iván Todorovich # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "CRM documents permissions by teams", "summary": "Integrates sales_team_security with crm", "version": "15.0.1.0.0", "category": "Customer Relationship Management", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Iván Todorovich, Odoo Community Association (OCA)", "license": "AGPL-3", "development_status": "Production/Stable", "maintainers": ["ivantodorovich"], "depends": ["crm", "sales_team_security"], "data": ["security/security.xml"], "auto_install": True, }
38.058824
647
898
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import SUPERUSER_ID, api def migrate(cr, version): """Adjust record rules according new definition.""" if not version: return env = api.Environment(cr, SUPERUSER_ID, {}) record = env.ref("sales_team_security_crm.crm_lead_team_rule", False) if record: record.domain_force = ( "['|', '|', ('user_id','=',user.id), ('user_id','=',False), '|', " "('team_id', '=', user.sale_team_id.id), ('team_id', '=', False)]" ) record = env.ref("sales_team_security_crm.crm_activity_report_team", False) if record: record.domain_force = ( "['|', '|', ('user_id','=',user.id), ('user_id','=',False), '|', " "('team_id', '=', user.sale_team_id.id), ('team_id', '=', False)]" )
40.727273
896
650
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.addons.sales_team_security.tests.common import TestCommon class TestSalesTeamSecurityCrm(TestCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.record = cls.env["crm.lead"].create( { "name": "Test lead", "partner_id": cls.partner.id, "user_id": cls.user.id, "team_id": cls.team.id, } ) def test_crm_lead_permissions(self): self._check_whole_permission_set(extra_checks=False)
30.857143
648
506
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Sale Force Invoiced", "summary": "Allows to force the invoice status of the sales order to Invoiced", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "category": "sale", "license": "AGPL-3", "website": "https://github.com/OCA/sale-workflow", "depends": ["sale"], "data": ["view/sale_view.xml"], "installable": True, }
33.733333
506
3,293
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class TestSaleForceInvoiced(TransactionCase): def setUp(self): super(TestSaleForceInvoiced, self).setUp() self.sale_order_model = self.env["sale.order"] self.sale_order_line_model = self.env["sale.order.line"] # Data product_ctg = self._create_product_category() self.service_1 = self._create_product("test_product1", product_ctg) self.service_2 = self._create_product("test_product2", product_ctg) self.customer = self._create_customer("Test Customer") def _create_customer(self, name): """Create a Partner.""" return self.env["res.partner"].create( {"name": name, "email": "example@yourcompany.com", "phone": 123456} ) def _create_product_category(self): product_ctg = self.env["product.category"].create({"name": "test_product_ctg"}) return product_ctg def _create_product(self, name, product_ctg): product = self.env["product.product"].create( { "name": name, "categ_id": product_ctg.id, "type": "service", "invoice_policy": "order", } ) return product def _create_invoice_from_sale(self, sale): payment = self.env["sale.advance.payment.inv"].create( {"advance_payment_method": "delivered"} ) sale_context = { "active_id": sale.id, "active_ids": sale.ids, "active_model": "sale.order", "open_invoices": True, } res = payment.with_context(**sale_context).create_invoices() invoice_id = res["res_id"] return invoice_id def test_sales_order(self): so = self.sale_order_model.create({"partner_id": self.customer.id}) sol1 = self.sale_order_line_model.create( {"product_id": self.service_1.id, "product_uom_qty": 1, "order_id": so.id} ) sol2 = self.sale_order_line_model.create( {"product_id": self.service_2.id, "product_uom_qty": 2, "order_id": so.id} ) # confirm quotation so.action_confirm() # update quantities delivered sol1.qty_delivered = 1 sol2.qty_delivered = 2 self.assertEqual( so.invoice_status, "to invoice", "The invoice status should be To Invoice" ) self._create_invoice_from_sale(so) self.assertEqual( so.invoice_status, "invoiced", "The invoice status should be Invoiced" ) # Reduce the invoiced qty for line in sol2.invoice_lines.with_context(check_move_validity=False): line.quantity = 1 self.assertEqual( so.invoice_status, "to invoice", "The invoice status should be To Invoice" ) so.action_done() so.force_invoiced = True self.assertEqual( so.invoice_status, "invoiced", "The invoice status should be Invoiced" ) so.force_invoiced = False self.assertEqual( so.invoice_status, "to invoice", "The invoice status should be To Invoice" )
34.663158
3,293
875
py
PYTHON
15.0
# Copyright 2017 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" force_invoiced = fields.Boolean( help="When you set this field, the sales order will be considered as " "fully invoiced, even when there may be ordered or delivered " "quantities pending to invoice.", readonly=True, states={"done": [("readonly", False)], "sale": [("readonly", False)]}, copy=False, ) @api.depends("force_invoiced") def _get_invoice_status(self): res = super(SaleOrder, self)._get_invoice_status() for order in self.filtered( lambda so: so.force_invoiced and so.state in ("sale", "done") ): order.invoice_status = "invoiced" return res
33.653846
875
464
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Wishlist", "summary": """ Handle sale wishlist for partners""", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "Camptocamp SA,Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "depends": ["sale_product_set"], "data": ["views/product_set.xml", "views/partner.xml"], }
33.142857
464
2,151
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests import common class TestWishlist(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.sale_order = cls.env["sale.order"] cls.product_set = cls.env["product.set"] cls.partner1 = cls.env.ref("base.res_partner_1") cls.partner2 = cls.env.ref("base.res_partner_2") def test_wishlist_count_no_typology_match(self): prod_set = self.env.ref("sale_product_set.product_set_services") for __ in range(2): prod_set.copy(default={"partner_id": self.partner1.id}) for __ in range(4): prod_set.copy(default={"partner_id": self.partner2.id}) self.assertEqual(self.partner1.wishlists_count, 0) self.assertEqual(self.partner2.wishlists_count, 0) def test_wishlist_count(self): prod_set = self.env.ref("sale_product_set.product_set_services") vals = {"partner_id": self.partner1.id, "typology": "wishlist"} for __ in range(2): prod_set.copy(default=vals) vals = {"partner_id": self.partner2.id, "typology": "wishlist"} for __ in range(4): prod_set.copy(default=vals) self.assertEqual(self.partner1.wishlists_count, 2) self.assertEqual(self.partner2.wishlists_count, 4) def test_action(self): action = self.partner1.action_view_wishlists() self.assertEqual( action["context"], {"default_partner_id": self.partner1.id, "default_typology": "wishlist"}, ) self.assertEqual( action["domain"], [("partner_id", "in", [self.partner1.id]), ("typology", "=", "wishlist")], ) action = self.partner2.action_view_wishlists() self.assertEqual( action["context"], {"default_partner_id": self.partner2.id, "default_typology": "wishlist"}, ) self.assertEqual( action["domain"], [("partner_id", "in", [self.partner2.id]), ("typology", "=", "wishlist")], )
40.584906
2,151
312
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductSet(models.Model): _inherit = "product.set" typology = fields.Selection( selection=[("set", "Default"), ("wishlist", "Wishlist")], default="set" )
24
312
1,351
py
PYTHON
15.0
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, fields, models class ResPartner(models.Model): _inherit = "res.partner" wishlists_count = fields.Integer( compute="_compute_wishlists_count", string="# Wishlists" ) def _compute_wishlists_count(self): # do just one query for all records data = self.env["product.set"].read_group( self._wishlist_domain(), ["partner_id"], ["partner_id"] ) data_mapped = { count["partner_id"][0]: count["partner_id_count"] for count in data } for rec in self: rec.wishlists_count = data_mapped.get(rec.id, 0) def _wishlist_domain(self): return [("partner_id", "in", self.ids), ("typology", "=", "wishlist")] def action_view_wishlists(self): self.ensure_one() xmlid = "sale_product_set.act_open_product_set_view" action = self.env["ir.actions.act_window"]._for_xml_id(xmlid) action.update( { "name": _("Wishlists"), "domain": self._wishlist_domain(), "context": { "default_typology": "wishlist", "default_partner_id": self.id, }, } ) return action
31.418605
1,351
650
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Carlos Dauden # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Stock Picking Note", "summary": "Add picking note in sale and purchase order", "version": "15.0.1.0.1", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "depends": ["sale_stock"], "data": [ "views/sale_order_view.xml", "views/stock_picking_view.xml", "views/report_deliveryslip.xml", ], "installable": True, }
34.105263
648
1,374
py
PYTHON
15.0
# Copyright 2018 Tecnativa - David Vidal # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import common class TestSaleStockPickingNote(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create({"name": "Mr. Odoo"}) cls.product = cls.env["product.product"].create( {"name": "Test product", "type": "product"} ) cls.order = cls.env["sale.order"].create( { "partner_id": cls.partner.id, "order_line": [ (0, 0, {"product_id": cls.product.id, "product_uom_qty": 1}) ], } ) def test_01_sale_to_picking_note(self): """Pass note to picking from SO""" self.order.picking_note = "This note goes to the picking..." self.order.picking_customer_note = "Picking comment" self.order.action_confirm() self.assertEqual(self.order.picking_ids[:1].note, self.order.picking_note) self.assertEqual( self.order.picking_ids[:1].customer_note, self.order.picking_customer_note ) report = self.env.ref("stock.action_report_delivery") res = str(report._render_qweb_html(self.order.picking_ids.ids)[0]) self.assertRegex(res, "Picking comment")
39.257143
1,374
786
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Carlos Dauden # Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class SaleOrder(models.Model): _inherit = "sale.order" picking_note = fields.Html(string="Picking Internal Note") picking_customer_note = fields.Text(string="Picking Customer Comments") class StockMove(models.Model): _inherit = "stock.move" def _get_new_picking_values(self): vals = super()._get_new_picking_values() sale_order = self.group_id.sale_id sale_note = sale_order.picking_note if sale_note: vals.update({"note": sale_note}) vals.update({"customer_note": sale_order.picking_customer_note}) return vals
31.36
784
273
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class StockPicking(models.Model): _inherit = "stock.picking" customer_note = fields.Text(string="Customer Comments")
27.1
271
546
py
PYTHON
15.0
# Copyright 2015 Opener B.V. (<https://opener.am>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Default sales incoterm per partner", "version": "15.0.1.1.0", "category": "Sales Management", "license": "AGPL-3", "summary": "Set the customer preferred incoterm on each sales order", "author": "Opener B.V.,Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "depends": ["sale_stock"], "data": ["views/res_partner.xml"], "installable": True, }
36.4
546
738
py
PYTHON
15.0
# Copyright 2015 Opener B.V. (<https://opener.am>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestSalePartnerIncoterm(TransactionCase): def test_sale_partner_incoterm(self): """ Check that the customer's default incoterm is retrieved in the sales order's onchange """ customer = self.env.ref("base.res_partner_3") incoterm = self.env["account.incoterms"].search([], limit=1) customer.write({"sale_incoterm_id": incoterm.id}) sale_order = self.env["sale.order"].create({"partner_id": customer.id}) sale_order.onchange_partner_id() self.assertEqual(sale_order.incoterm, incoterm)
41
738
394
py
PYTHON
15.0
# Copyright 2015 Opener B.V. (<https://opener.am>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrder(models.Model): _inherit = "sale.order" @api.onchange("partner_id") def onchange_partner_id(self): res = super().onchange_partner_id() self.incoterm = self.partner_id.sale_incoterm_id return res
28.142857
394
415
py
PYTHON
15.0
# Copyright 2015 Opener B.V. (<https://opener.am>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class Partner(models.Model): _inherit = "res.partner" sale_incoterm_id = fields.Many2one( string="Default Sales Incoterm", comodel_name="account.incoterms", help="The default incoterm for new sales orders for this customer.", )
29.642857
415
557
py
PYTHON
15.0
# Copyright 2020 Camptocamp (https://www.camptocamp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Automatic Workflow Job", "summary": "Execute sale automatic workflows in queue jobs", "version": "15.0.1.0.0", "category": "Sales Management", "license": "AGPL-3", "author": "Camptocamp, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "depends": ["sale_automatic_workflow", "queue_job"], "data": [ "data/queue_job_data.xml", ], }
34.8125
557
5,629
py
PYTHON
15.0
# Copyright 2020 Camptocamp (https://www.camptocamp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import tagged from odoo.addons.queue_job.job import identity_exact from odoo.addons.queue_job.tests.common import mock_with_delay from odoo.addons.sale_automatic_workflow.tests.common import ( TestAutomaticWorkflowMixin, TestCommon, ) @tagged("post_install", "-at_install") class TestAutoWorkflowJob(TestCommon, TestAutomaticWorkflowMixin): def create_sale_order(self, workflow, override=None): order = super().create_sale_order(workflow, override) order.order_line.product_id.invoice_policy = "order" return order def assert_job_delayed(self, delayable_cls, delayable, method_name, args): # .with_delay() has been called once self.assertEqual(delayable_cls.call_count, 1) delay_args, delay_kwargs = delayable_cls.call_args # .with_delay() has been called on self.env["automatic.workflow.job"] self.assertEqual(delay_args, (self.env["automatic.workflow.job"],)) # .with_delay() with the following options self.assertEqual(delay_kwargs.get("identity_key"), identity_exact) # check what's passed to the job method method = getattr(delayable, method_name) self.assertEqual(method.call_count, 1) delay_args, delay_kwargs = method.call_args self.assertEqual(delay_args, args) self.assertDictEqual(delay_kwargs, {}) def test_validate_sale_order(self): workflow = self.create_full_automatic() self.sale = self.create_sale_order(workflow) with mock_with_delay() as (delayable_cls, delayable): self.run_job() # run automatic workflow cron args = ( self.sale, [ ("state", "=", "draft"), ("workflow_process_id", "=", self.sale.workflow_process_id.id), ], ) self.assert_job_delayed( delayable_cls, delayable, "_do_validate_sale_order", args ) def test_create_invoice(self): workflow = self.create_full_automatic() self.sale = self.create_sale_order(workflow) self.sale.action_confirm() # don't care about transfers in this test self.sale.picking_ids.state = "done" with mock_with_delay() as (delayable_cls, delayable): self.run_job() # run automatic workflow cron args = ( self.sale, [ ("state", "in", ["sale", "done"]), ("invoice_status", "=", "to invoice"), ("workflow_process_id", "=", self.sale.workflow_process_id.id), ], ) self.assert_job_delayed( delayable_cls, delayable, "_do_create_invoice", args ) def test_validate_invoice(self): workflow = self.create_full_automatic() self.sale = self.create_sale_order(workflow) self.sale.action_confirm() # don't care about transfers in this test self.sale.picking_ids.state = "done" self.sale._create_invoices() invoice = self.sale.invoice_ids with mock_with_delay() as (delayable_cls, delayable): self.run_job() # run automatic workflow cron args = ( invoice, [ ("state", "=", "draft"), ("posted_before", "=", False), ("workflow_process_id", "=", self.sale.workflow_process_id.id), ], ) self.assert_job_delayed( delayable_cls, delayable, "_do_validate_invoice", args ) def test_validate_picking(self): workflow = self.create_full_automatic() self.sale = self.create_sale_order(workflow) self.sale.action_confirm() picking = self.sale.picking_ids # disable invoice creation in this test self.sale.workflow_process_id.create_invoice = False with mock_with_delay() as (delayable_cls, delayable): self.run_job() # run automatic workflow cron args = ( picking, [ ("state", "in", ["draft", "confirmed", "assigned"]), ("workflow_process_id", "=", self.sale.workflow_process_id.id), ], ) self.assert_job_delayed( delayable_cls, delayable, "_do_validate_picking", args ) def test_sale_done(self): workflow = self.create_full_automatic() self.sale = self.create_sale_order(workflow) self.sale.action_confirm() # don't care about transfers in this test self.sale.picking_ids.state = "done" self.sale._create_invoices() # disable invoice validation for we don't care # in this test self.sale.workflow_process_id.validate_invoice = False # activate the 'sale done' workflow self.sale.workflow_process_id.sale_done = True with mock_with_delay() as (delayable_cls, delayable): self.run_job() # run automatic workflow cron args = ( self.sale, [ ("state", "=", "sale"), ("invoice_status", "=", "invoiced"), ("workflow_process_id", "=", self.sale.workflow_process_id.id), ], ) self.assert_job_delayed(delayable_cls, delayable, "_do_sale_done", args)
40.789855
5,629
3,342
py
PYTHON
15.0
# Copyright 2020 Camptocamp (https://www.camptocamp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.addons.queue_job.job import identity_exact class AutomaticWorkflowJob(models.Model): _inherit = "automatic.workflow.job" def _do_validate_sale_order_job_options(self, sale, domain_filter): description = _("Validate sales order {}").format(sale.display_name) return { "description": description, "identity_key": identity_exact, } def _validate_sale_orders(self, domain_filter): with_context = self.with_context(auto_delay_do_validation=True) return super(AutomaticWorkflowJob, with_context)._validate_sale_orders( domain_filter ) def _do_create_invoice_job_options(self, sale, domain_filter): description = _("Create invoices for sales order {}").format(sale.display_name) return { "description": description, "identity_key": identity_exact, } def _create_invoices(self, domain_filter): with_context = self.with_context(auto_delay_do_create_invoice=True) return super(AutomaticWorkflowJob, with_context)._create_invoices(domain_filter) def _do_validate_invoice_job_options(self, invoice, domain_filter): description = _("Validate invoice {}").format(invoice.display_name) return { "description": description, "identity_key": identity_exact, } def _validate_invoices(self, domain_filter): with_context = self.with_context(auto_delay_do_validation=True) return super(AutomaticWorkflowJob, with_context)._validate_invoices( domain_filter ) def _do_validate_picking_job_options(self, picking, domain_filter): description = _("Validate transfer {}").format(picking.display_name) return { "description": description, "identity_key": identity_exact, } def _validate_pickings(self, domain_filter): with_context = self.with_context(auto_delay_do_validation=True) return super(AutomaticWorkflowJob, with_context)._validate_pickings( domain_filter ) def _do_sale_done_job_options(self, sale, domain_filter): description = _("Mark sales order {} as done").format(sale.display_name) return { "description": description, "identity_key": identity_exact, } def _sale_done(self, domain_filter): with_context = self.with_context(auto_delay_do_sale_done=True) return super(AutomaticWorkflowJob, with_context)._sale_done(domain_filter) def _register_hook(self): mapping = { "_do_validate_sale_order": "auto_delay_do_validation", "_do_create_invoice": "auto_delay_do_create_invoice", "_do_validate_invoice": "auto_delay_do_validation", "_do_validate_picking": "auto_delay_do_validation", "_do_sale_done": "auto_delay_do_sale_done", } for method_name, context_key in mapping.items(): self._patch_method( method_name, self._patch_job_auto_delay(method_name, context_key=context_key), ) return super()._register_hook()
39.317647
3,342
575
py
PYTHON
15.0
# Copyright 2020 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, models class QueueJob(models.Model): """Job status and result""" _inherit = "queue.job" def _related_action_sale_automatic_workflow(self): obj = self.args[0] action = { "name": _("Sale Automatic Workflow Job"), "type": "ir.actions.act_window", "res_model": obj._name, "view_mode": "form", "res_id": obj.id, } return action
27.380952
575
603
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Stock Secondary Unit", "summary": "Get product quantities in a secondary unit", "version": "15.0.1.0.1", "development_status": "Production/Stable", "category": "stock", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale_order_secondary_unit", "stock_secondary_unit"], "auto_install": True, }
37.6875
603
3,069
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests import TransactionCase, tagged @tagged("post_install", "-at_install") class TestSaleStockOrderSecondaryUnit(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.warehouse = cls.env.ref("stock.warehouse0") 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.product = cls.env["product.product"].create( { "name": "test", "type": "product", "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-700", "uom_id": cls.product_uom_unit.id, "factor": 0.7, }, ) ], } ) StockQuant = cls.env["stock.quant"] StockQuant.create( { "product_id": cls.product.id, "location_id": cls.warehouse.lot_stock_id.id, "quantity": 2000, } ) 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"}) so = cls.env["sale.order"].new( { "partner_id": cls.partner.id, "order_line": [ ( 0, 0, { "name": cls.product.name, "product_id": cls.product.id, "product_uom_qty": 1, "product_uom": cls.product.uom_id.id, "price_unit": 1000.00, }, ) ], "pricelist_id": cls.env.ref("product.list0").id, } ) so.onchange_partner_id() cls.order = cls.env["sale.order"].create(so._convert_to_write(so._cache)) def test_stock_move_line_secondary_unit(self): self.order.order_line.write( {"secondary_uom_id": self.secondary_unit.id, "secondary_uom_qty": 5} ) self.order.order_line._onchange_helper_product_uom_for_secondary() self.order.action_confirm() picking = self.order.picking_ids self.assertEqual(picking.move_line_ids.secondary_uom_qty, 5.0)
37.888889
3,069
1,261
py
PYTHON
15.0
# Copyright 2019 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class StockRule(models.Model): _inherit = "stock.rule" def _get_stock_move_values( self, product_id, product_qty, product_uom, location_id, name, origin, company_id, values, ): res = super()._get_stock_move_values( product_id, product_qty, product_uom, location_id, name, origin, company_id, values, ) sale_line_id = values.get("sale_line_id", False) # Record can be a sale order line or a stock move depending of pull # and push rules if sale_line_id: record = self.env["sale.order.line"].browse(sale_line_id) else: record = values.get("move_dest_ids", self.env["stock.move"].browse())[:1] if record and record.secondary_uom_id: res.update( { "secondary_uom_id": record.secondary_uom_id.id, "secondary_uom_qty": record.secondary_uom_qty, } ) return res
28.659091
1,261
540
py
PYTHON
15.0
# Copyright 2020 Manuel Regidor <manuel.regidor@sygel.es> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Product Category Menu", "summary": "Shows 'Product Categories' menu item in Sales", "version": "15.0.1.0.0", "category": "Product", "website": "https://github.com/OCA/sale-workflow", "author": "Sygel, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale"], "data": ["views/sale_views.xml"], }
36
540
554
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl) { "name": "Sale Order Carrier Auto Assign", "summary": "Auto assign delivery carrier on sale order confirmation", "version": "15.0.1.0.1", "development_status": "Alpha", "category": "Operations/Inventory/Delivery", "website": "https://github.com/OCA/sale-workflow", "author": "Camptocamp, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["delivery"], }
36.933333
554
1,936
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl) from odoo.tests import Form, TransactionCase class TestSaleOrderCarrierAutoAssign(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() test_context = cls.env.context.copy() test_context["test_carrier_auto_assign"] = True cls.env = cls.env(context=dict(test_context, tracking_disable=True)) cls.partner = cls.env.ref("base.res_partner_2") product = cls.env.ref("product.product_product_9") cls.normal_delivery_carrier = cls.env.ref("delivery.normal_delivery_carrier") cls.normal_delivery_carrier.fixed_price = 10 sale_order_form = Form(cls.env["sale.order"]) sale_order_form.partner_id = cls.partner with sale_order_form.order_line.new() as line_form: line_form.product_id = product cls.sale_order = sale_order_form.save() def test_sale_order_carrier_auto_assign(self): self.assertEqual( self.partner.property_delivery_carrier_id, self.normal_delivery_carrier ) self.assertFalse(self.sale_order.carrier_id) self.sale_order.action_confirm() self.assertEqual(self.sale_order.state, "sale") self.assertEqual(self.sale_order.carrier_id, self.normal_delivery_carrier) delivery_line = self.sale_order.order_line.filtered(lambda l: l.is_delivery) delivery_rate = self.normal_delivery_carrier.rate_shipment(self.sale_order) self.assertEqual(delivery_line.price_unit, delivery_rate["carrier_price"]) def test_sale_order_carrier_auto_assign_no_carrier(self): self.partner.property_delivery_carrier_id = False self.assertFalse(self.sale_order.carrier_id) self.sale_order.action_confirm() self.assertEqual(self.sale_order.state, "sale") self.assertFalse(self.sale_order.carrier_id)
48.4
1,936
1,221
py
PYTHON
15.0
# Copyright 2020 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl) from odoo import models from odoo.tools import config class SaleOrder(models.Model): _inherit = "sale.order" def action_confirm(self): if config["test_enable"] and not self.env.context.get( "test_carrier_auto_assign" ): return super().action_confirm() self._add_delivery_carrier_on_confirmation() return super().action_confirm() def _add_delivery_carrier_on_confirmation(self): """Automatically add delivery.carrier on sale order confirmation""" for order in self: if order.delivery_set: continue delivery_wiz_action = order.action_open_delivery_wizard() delivery_wiz_context = delivery_wiz_action.get("context", {}) if not delivery_wiz_context.get("default_carrier_id"): continue delivery_wiz = ( self.env[delivery_wiz_action.get("res_model")] .with_context(**delivery_wiz_context) .create({}) ) delivery_wiz._get_shipment_rate() delivery_wiz.button_confirm()
35.911765
1,221
399
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Invoice No Mail", "version": "15.0.1.0.1", "category": "Sales Management", "author": "Camptocamp SA," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "license": "AGPL-3", "depends": ["sale"], "installable": True, }
30.692308
399
1,313
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestSaleInvoiceNoMail(TransactionCase): def test_00_invoice_without_mail(self): partner = self.env["res.partner"].create({"name": "Test Partner"}) product = self.env["product.product"].create( {"name": "Test Product", "invoice_policy": "order"} ) sale = self.env["sale.order"].create( { "partner_id": partner.id, "order_line": [ ( 0, 0, { "product_id": product.id, "product_uom_qty": 5, "price_unit": 10, }, ) ], } ) sale.action_confirm() old_mails = self.env["mail.mail"].sudo().search([]) wiz = self.env["sale.advance.payment.inv"] wiz = wiz.with_context(active_ids=sale.ids) wiz = wiz.create({"advance_payment_method": "delivered"}) wiz.create_invoices() new_mails = self.env["mail.mail"].sudo().search([]) - old_mails self.assertFalse(new_mails)
36.472222
1,313
550
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class SaleAdvancePaymentInv(models.TransientModel): _inherit = "sale.advance.payment.inv" def create_invoices(self): skip = self._skip_invoice_mail() wiz = self.with_context(mail_auto_subscribe_no_notify=skip) return super(SaleAdvancePaymentInv, wiz).create_invoices() def _skip_invoice_mail(self): """Hook method, can be overridden. Returns True by default""" return True
32.352941
550
575
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Product Form Sale Link", "summary": """ Adds a button on product forms to access Sale Lines""", "version": "15.0.1.0.1", "license": "AGPL-3", "category": "Sales", "author": "ACSONE SA/NV,Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "depends": ["sale"], "data": [ "views/sale_order_line.xml", "views/product_product.xml", "views/product_template.xml", ], }
30.263158
575
690
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from odoo import api, fields, models _logger = logging.getLogger(__name__) class ProductTemplate(models.Model): _inherit = "product.template" sale_lines_count = fields.Float(compute="_compute_sale_lines_count", string="Sold") @api.depends("product_variant_ids.sale_lines_count") def _compute_sale_lines_count(self): for product in self: product.sale_lines_count = sum( p.sale_lines_count for p in product.with_context(active_test=False).product_variant_ids )
31.363636
690
1,041
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProductProduct(models.Model): _inherit = "product.product" sale_lines_count = fields.Integer( compute="_compute_sale_lines_count", string="Sold" ) def _compute_sale_lines_count(self): if not self.user_has_groups("sales_team.group_sale_salesman") or not self.ids: self.sale_lines_count = 0.0 return domain = [ ("state", "in", ["sale", "done"]), ("product_id", "in", self.ids), ("company_id", "in", self.env.companies.ids), ] sale_line_data = self.env["sale.order.line"].read_group( domain, ["product_id"], ["product_id"] ) mapped_data = { m["product_id"][0]: m["product_id_count"] for m in sale_line_data } for product in self: product.sale_lines_count = mapped_data.get(product.id, 0)
34.7
1,041
589
py
PYTHON
15.0
# Copyright (C) 2021 Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Order Line Menu", "version": "15.0.1.0.1", "author": "Open Source Integrators, Odoo Community Association (OCA)", "summary": "Adds a Sale Order Lines Menu", "website": "https://github.com/OCA/sale-workflow", "license": "AGPL-3", "depends": ["sale"], "category": "Sales/Sales", "data": [ "views/sale_order_line_views.xml", ], "installable": True, "maintainer": "dreispt", "development_status": "Beta", }
31
589
788
py
PYTHON
15.0
# Copyright 2015 ADHOC SA (http://www.adhoc.com.ar) # Copyright 2017 - 2019 Alex Comba - Agile Business Group # Copyright 2017 Tecnativa - David Vidal # Copyright 2018 Jacques-Etienne Baudoux (BCIM sprl) <je@bcim.be> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Triple Discount", "version": "15.0.1.0.1", "category": "Sales", "author": "ADHOC SA, Agile Business Group, Tecnativa, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "license": "AGPL-3", "summary": "Manage triple discount on sale order lines", "depends": ["sale_management", "account_invoice_triple_discount"], "data": ["views/sale_order_report.xml", "views/sale_order_view.xml"], "installable": True, }
41.473684
788
9,312
py
PYTHON
15.0
# Copyright 2017 Tecnativa - David Vidal # Copyright 2018 Simone Rubino - Agile Business Group # Copyright 2022 Manuel Regidor - Sygel Technology # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import json from odoo.tests import common class TestSaleOrder(common.TransactionCase): @classmethod def setUpClass(cls): super(TestSaleOrder, cls).setUpClass() cls.partner = cls.env["res.partner"].create({"name": "Mr. Odoo"}) cls.product1 = cls.env["product.product"].create( {"name": "Test Product 1", "type": "service", "invoice_policy": "order"} ) cls.product2 = cls.env["product.product"].create( {"name": "Test Product 2", "type": "service", "invoice_policy": "order"} ) cls.tax = cls.env["account.tax"].create( { "name": "TAX 15%", "amount_type": "percent", "type_tax_use": "sale", "amount": 15.0, } ) cls.order = cls.env["sale.order"].create({"partner_id": cls.partner.id}) so_line = cls.env["sale.order.line"] cls.so_line1 = so_line.create( { "order_id": cls.order.id, "product_id": cls.product1.id, "name": "Line 1", "product_uom_qty": 1.0, "tax_id": [(6, 0, [cls.tax.id])], "price_unit": 600.0, } ) cls.so_line2 = so_line.create( { "order_id": cls.order.id, "product_id": cls.product2.id, "name": "Line 2", "product_uom_qty": 10.0, "tax_id": [(6, 0, [cls.tax.id])], "price_unit": 60.0, } ) def test_01_sale_order_classic_discount(self): """Tests with single discount""" self.so_line1.discount = 50.0 self.so_line2.discount = 75.0 self.assertAlmostEqual(self.so_line1.price_subtotal, 300.0) self.assertAlmostEqual(self.so_line2.price_subtotal, 150.0) self.assertAlmostEqual(self.order.amount_untaxed, 450.0) self.assertAlmostEqual(self.order.amount_tax, 67.5) # Mix taxed and untaxed: self.so_line1.tax_id = False self.assertAlmostEqual(self.order.amount_tax, 22.5) def test_02_sale_order_simple_triple_discount(self): """Tests on a single line""" self.so_line2.unlink() # Divide by two on every discount: self.so_line1.discount = 50.0 self.so_line1.discount2 = 50.0 self.so_line1.discount3 = 50.0 self.assertAlmostEqual(self.so_line1.price_subtotal, 75.0) self.assertAlmostEqual(self.order.amount_untaxed, 75.0) self.assertAlmostEqual(self.order.amount_tax, 11.25) # Unset first discount: self.so_line1.discount = 0.0 self.assertAlmostEqual(self.so_line1.price_subtotal, 150.0) self.assertAlmostEqual(self.order.amount_untaxed, 150.0) self.assertAlmostEqual(self.order.amount_tax, 22.5) # Set a charge instead: self.so_line1.discount2 = -50.0 self.assertAlmostEqual(self.so_line1.price_subtotal, 450.0) self.assertAlmostEqual(self.order.amount_untaxed, 450.0) self.assertAlmostEqual(self.order.amount_tax, 67.5) # sale tax total json (multiplicative) json_vals = json.loads(self.order.tax_totals_json) self.assertAlmostEqual( json_vals["groups_by_subtotal"]["Untaxed Amount"][0]["tax_group_amount"], 67.5, ) # set discount_type to additive self.so_line1.discount = 10.0 self.so_line1.discount2 = 10.0 self.so_line1.discount3 = 10.0 self.so_line1.discounting_type = "additive" self.assertAlmostEqual(self.so_line1.price_subtotal, 420.0) self.assertAlmostEqual(self.order.amount_untaxed, 420.0) self.assertAlmostEqual(self.order.amount_tax, 63.0) # sale tax total json (additive) json_vals = json.loads(self.order.tax_totals_json) self.assertAlmostEqual( json_vals["groups_by_subtotal"]["Untaxed Amount"][0]["tax_group_amount"], 63.0, ) # set discount over 100% self.so_line1.discount = 30.0 self.so_line1.discount2 = 70.0 self.so_line1.discount3 = 50.0 self.assertAlmostEqual(self.so_line1.price_subtotal, 0.0) self.assertAlmostEqual(self.order.amount_untaxed, 0.0) self.assertAlmostEqual(self.order.amount_tax, 0.0) # set discount_type to multiplicative self.so_line1.discount = 50.0 self.so_line1.discount2 = 50.0 self.so_line1.discount3 = 50.0 self.so_line1.discounting_type = "multiplicative" self.assertAlmostEqual(self.so_line1.price_subtotal, 75.0) self.assertAlmostEqual(self.order.amount_untaxed, 75.0) self.assertAlmostEqual(self.order.amount_tax, 11.25) def test_03_sale_order_complex_triple_discount(self): """Tests on multiple lines""" self.so_line1.discount = 50.0 self.so_line1.discount2 = 50.0 self.so_line1.discount3 = 50.0 self.assertAlmostEqual(self.so_line1.price_subtotal, 75.0) self.assertAlmostEqual(self.order.amount_untaxed, 675.0) self.assertAlmostEqual(self.order.amount_tax, 101.25) # additive discount self.so_line2.discount3 = 50.0 self.assertAlmostEqual(self.so_line2.price_subtotal, 300.0) self.assertAlmostEqual(self.order.amount_untaxed, 375.0) self.assertAlmostEqual(self.order.amount_tax, 56.25) self.so_line2.discounting_type = "additive" self.so_line2.discount2 = 10.0 self.assertAlmostEqual(self.so_line2.price_subtotal, 240.0) self.assertAlmostEqual(self.order.amount_untaxed, 315.0) self.assertAlmostEqual(self.order.amount_tax, 47.25) # multiplicative discount self.so_line2.discount2 = 0.0 self.so_line2.discount3 = 50.0 self.assertAlmostEqual(self.so_line2.price_subtotal, 300.0) self.assertAlmostEqual(self.order.amount_untaxed, 375.0) self.assertAlmostEqual(self.order.amount_tax, 56.25) self.so_line2.discounting_type = "multiplicative" self.so_line2.discount2 = 10.0 self.assertAlmostEqual(self.so_line2.price_subtotal, 270.0) self.assertAlmostEqual(self.order.amount_untaxed, 345.0) self.assertAlmostEqual(self.order.amount_tax, 51.75) def test_04_sale_order_triple_discount_invoicing(self): """When a confirmed order is invoiced, the resultant invoice should inherit the discounts""" self.so_line1.discount = 50.0 self.so_line1.discount2 = 50.0 self.so_line1.discount3 = 50.0 self.so_line2.discount3 = 50.0 self.order.action_confirm() if self.order.state == "waiting_approval": self.order.action_approve() self.assertAlmostEqual(self.order.state, "approved") self.order.action_confirm() self.order._create_invoices() invoice = self.order.invoice_ids[0] self.assertAlmostEqual( self.so_line1.discount, invoice.invoice_line_ids[0].discount ) self.assertAlmostEqual( self.so_line1.discount2, invoice.invoice_line_ids[0].discount2 ) self.assertAlmostEqual( self.so_line1.discount3, invoice.invoice_line_ids[0].discount3 ) self.assertAlmostEqual( self.so_line1.price_subtotal, invoice.invoice_line_ids[0].price_subtotal ) self.assertAlmostEqual( self.so_line2.discount3, invoice.invoice_line_ids[1].discount3 ) self.assertAlmostEqual( self.so_line2.price_subtotal, invoice.invoice_line_ids[1].price_subtotal ) self.assertAlmostEqual(self.order.amount_total, invoice.amount_total) def test_05_round_globally(self): """Tests on multiple lines when 'round_globally' is active""" self.env.user.company_id.tax_calculation_rounding_method = "round_globally" self.so_line1.discount = 50.0 self.so_line1.discount2 = 50.0 self.so_line1.discount3 = 50.0 self.assertEqual(self.so_line1.price_subtotal, 75.0) self.assertEqual(self.order.amount_untaxed, 675.0) self.assertEqual(self.order.amount_tax, 101.25) self.so_line2.discount3 = 50.0 self.assertEqual(self.so_line2.price_subtotal, 300.0) self.assertEqual(self.order.amount_untaxed, 375.0) self.assertEqual(self.order.amount_tax, 56.25) def test_06_discount_0(self): self.so_line1.discounting_type = "additive" self.so_line1.discount = 0.0 self.so_line1.discount2 = 0.0 self.so_line1.discount3 = 0.0 self.so_line2.discounting_type = "additive" self.so_line2.discount = 0.0 self.so_line2.discount2 = 0.0 self.so_line2.discount3 = 0.0 self.assertAlmostEqual(self.so_line1.price_subtotal, 600.0) self.assertAlmostEqual(self.so_line2.price_subtotal, 600.0) self.assertAlmostEqual(self.order.amount_untaxed, 1200.0) self.assertAlmostEqual(self.order.amount_tax, 180.0)
44.132701
9,312
2,625
py
PYTHON
15.0
# Copyright 2018 Simone Rubino - Agile Business Group # Copyright 2018 Jacques-Etienne Baudoux (BCIM sprl) <je@bcim.be> # Copyright 2017 - 2019 Alex Comba - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import json from odoo import api, models class SaleOrder(models.Model): _inherit = "sale.order" @api.depends( "order_line.tax_id", "order_line.price_unit", "amount_total", "amount_untaxed" ) def _compute_tax_totals_json(self): def compute_taxes(order_line): price = 0.0 if order_line.discounting_type == "additive": total_discount = ( order_line.discount + order_line.discount2 + order_line.discount3 ) price = order_line.price_unit * (1 - total_discount / 100.0) elif order_line.discounting_type == "multiplicative": price = order_line.price_unit * ( 1 - (order_line.discount or 0.0) / 100.0 ) price = price * (1 - (order_line.discount2 or 0.0) / 100.0) price = price * (1 - (order_line.discount3 or 0.0) / 100.0) order = order_line.order_id order = order_line.order_id return order_line.tax_id._origin.compute_all( price, order.currency_id, order_line.product_uom_qty, product=order_line.product_id, partner=order.partner_shipping_id, ) vals = super()._compute_tax_totals_json() for order in self.filtered( lambda a: any(line.discount2 or line.discount3 for line in a.order_line) ): account_move = self.env["account.move"] tax_lines_data = ( account_move._prepare_tax_lines_data_for_totals_from_object( order.order_line, compute_taxes ) ) tax_totals = account_move._get_tax_totals( order.partner_id, tax_lines_data, order.amount_total, order.amount_untaxed, order.currency_id, ) order.tax_totals_json = json.dumps(tax_totals) return vals @api.depends("order_line.price_total") def _amount_all(self): prev_values = dict() for order in self: prev_values.update(order.order_line.triple_discount_preprocess()) res = super()._amount_all() self.env["sale.order.line"].triple_discount_postprocess(prev_values) return res
38.602941
2,625
4,492
py
PYTHON
15.0
# Copyright 2015 ADHOC SA (http://www.adhoc.com.ar) # Copyright 2017 - 2019 Alex Comba - Agile Business Group # Copyright 2017 Tecnativa - David Vidal # Copyright 2018 Simone Rubino - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class SaleOrderLine(models.Model): _inherit = "sale.order.line" discount2 = fields.Float( string="Disc. 2 (%)", digits="Discount", default=0.0, ) discount3 = fields.Float( string="Disc. 3 (%)", digits="Discount", default=0.0, ) discounting_type = fields.Selection( selection=[("additive", "Additive"), ("multiplicative", "Multiplicative")], default="multiplicative", required=True, help="Specifies whether discounts should be additive " "or multiplicative.\nAdditive discounts are summed first and " "then applied.\nMultiplicative discounts are applied sequentially.\n" "Multiplicative discounts are default", ) def _get_final_discount(self): self.ensure_one() if self.discounting_type == "additive": return self._additive_discount() elif self.discounting_type == "multiplicative": return self._multiplicative_discount() else: raise ValidationError( _("Sale order line %(name)s has unknown discounting type %(dic_type)s") % {"name": self.name, "disc_type": self.discounting_type} ) def _additive_discount(self): self.ensure_one() discount = sum(self[x] or 0.0 for x in self._discount_fields()) if discount <= 0: return 0 elif discount >= 100: return 100 return discount def _multiplicative_discount(self): self.ensure_one() discounts = [1 - (self[x] or 0.0) / 100 for x in self._discount_fields()] final_discount = 1 for discount in discounts: final_discount *= discount return 100 - final_discount * 100 def _discount_fields(self): return ["discount", "discount2", "discount3"] @api.depends("discount2", "discount3", "discounting_type") def _compute_amount(self): prev_values = self.triple_discount_preprocess() res = super()._compute_amount() self.triple_discount_postprocess(prev_values) return res _sql_constraints = [ ( "discount2_limit", "CHECK (discount2 <= 100.0)", "Discount 2 must be lower or equal than 100%.", ), ( "discount3_limit", "CHECK (discount3 <= 100.0)", "Discount 3 must be lower or equal than 100%.", ), ] def _prepare_invoice_line(self, **kwargs): res = super()._prepare_invoice_line(**kwargs) res.update({"discount2": self.discount2, "discount3": self.discount3}) return res def triple_discount_preprocess(self): """Prepare data for post processing. Save the values of the discounts in a dictionary, to be restored in postprocess. Resetting discount2 and discount3 to 0.0 avoids issues if this method is called multiple times. Updating the cache provides consistency through recomputations.""" prev_values = dict() self.invalidate_cache( fnames=["discount", "discount2", "discount3"], ids=self.ids ) for line in self: prev_values[line] = dict( discount=line.discount, discount2=line.discount2, discount3=line.discount3, ) line._cache.update( { "discount": line._get_final_discount(), "discount2": 0.0, "discount3": 0.0, } ) return prev_values @api.model def triple_discount_postprocess(self, prev_values): """Restore the discounts of the lines in the dictionary prev_values. Updating the cache provides consistency through recomputations.""" self.invalidate_cache( fnames=["discount", "discount2", "discount3"], ids=[line.id for line in list(prev_values.keys())], ) for line, prev_vals_dict in list(prev_values.items()): line._cache.update(prev_vals_dict)
34.553846
4,492
243
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). def pre_init_hook(cr): cr.execute( """ ALTER TABLE sale_order_line ADD COLUMN last_delivery_date TIMESTAMP;""" )
27
243
638
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Stock Last Date", "summary": "Displays last delivery date in sale order lines", "version": "15.0.1.0.0", "development_status": "Beta", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale_stock"], "data": ["views/sale_order_view.xml", "reports/sale_report_view.xml"], "pre_init_hook": "pre_init_hook", }
37.529412
638
3,138
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests import Form, TransactionCase class TestSaleStockLastDate(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.warehouse = cls.env.ref("stock.warehouse0") cls.product = cls.env["product.product"].create( {"name": "test", "type": "product"} ) cls.env["stock.quant"].create( { "product_id": cls.product.id, "location_id": cls.warehouse.lot_stock_id.id, "quantity": 2000, } ) cls.partner = cls.env["res.partner"].create({"name": "test - partner"}) order_form = Form(cls.env["sale.order"]) order_form.partner_id = cls.partner with order_form.order_line.new() as line_form: line_form.product_id = cls.product line_form.product_uom_qty = 10 line_form.price_unit = 1000 cls.order = order_form.save() def _return_whole_picking(self, picking, to_refund=True): """Helper method to create a return of the original picking. It could be refundable or not""" return_wiz_form = Form( self.env["stock.return.picking"].with_context( active_ids=picking.ids, active_id=picking.ids[0], active_model="stock.picking", ) ) return_wiz = return_wiz_form.save() return_wiz.product_return_moves.quantity = picking.move_lines.quantity_done return_wiz.product_return_moves.to_refund = to_refund res = return_wiz.create_returns() return_picking = self.env["stock.picking"].browse(res["res_id"]) self._validate_picking(return_picking) def _validate_picking(self, picking): """Helper method to confirm the pickings""" for line in picking.move_lines: line.quantity_done = line.product_uom_qty picking._action_done() def test_last_delivery_date(self): self.order.action_confirm() self.assertFalse(self.order.order_line.last_delivery_date) # Partial delivery one picking = self.order.picking_ids picking.action_assign() picking.move_lines.quantity_done = 2.0 picking._action_done() # Discard any so line like as delivery line for tests in travis so_line = self.order.order_line.filtered( lambda ln: ln.product_id == self.product ) self.assertEqual(so_line.last_delivery_date, picking.move_lines.date) # Partial delivery two backorder = self.order.picking_ids.filtered(lambda p: p.state != "done") backorder.action_assign() backorder.move_lines.quantity_done = 2.0 backorder._action_done() self.assertEqual(so_line.last_delivery_date, backorder.move_lines.date) # Make a return. This movement does not affect self._return_whole_picking(picking, to_refund=True) self.assertEqual(so_line.last_delivery_date, backorder.move_lines.date)
41.84
3,138
801
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Sergio Teruel # 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" last_delivery_date = fields.Datetime( string="Last delivery date", compute="_compute_last_delivery_date", store=True ) @api.depends("move_ids.state", "move_ids.date") def _compute_last_delivery_date(self): for line in self: stock_moves = line.move_ids.filtered( lambda m: ( m.picking_code == "outgoing" and m.state == "done" and not m.scrapped ) ) line.last_delivery_date = stock_moves.sorted("date", reverse=True)[:1].date
34.826087
801
626
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Sergio Teruel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from odoo import fields, models class SaleReport(models.Model): _inherit = "sale.report" last_delivery_date = fields.Datetime( string="Last delivery date", ) def _query(self, with_clause="", fields=None, groupby="", from_clause=""): fields = fields or {} fields["last_delivery_date"] = ", l.last_delivery_date AS" " last_delivery_date" groupby += ", l.last_delivery_date" return super(SaleReport, self)._query(with_clause, fields, groupby, from_clause)
34.777778
626
625
py
PYTHON
15.0
# Copyright 2020 Iván Todorovich # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale documents permissions by teams", "summary": "Integrates sales_team_security with sale", "version": "15.0.1.0.0", "category": "Sales", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Iván Todorovich, Odoo Community Association (OCA)", "license": "AGPL-3", "development_status": "Production/Stable", "maintainers": ["ivantodorovich"], "depends": ["sale", "sales_team_security"], "data": ["security/security.xml"], "auto_install": True, }
36.647059
623
1,243
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from odoo import SUPERUSER_ID, api def migrate(cr, version): """Adjust record rules according new definition.""" if not version: return env = api.Environment(cr, SUPERUSER_ID, {}) record = env.ref("sales_team_security_sale.sale_order_team_rule", False) if record: record.domain_force = ( "['|', '|', ('user_id','=',user.id), ('user_id','=',False), '|', " "('team_id', '=', user.sale_team_id.id), ('team_id', '=', False)]" ) record = env.ref("sales_team_security_sale.sale_order_report_team_rule", False) if record: record.domain_force = ( "['|', '|', ('user_id','=',user.id), ('user_id','=',False), '|', " "('team_id', '=', user.sale_team_id.id), ('team_id', '=', False)]" ) record = env.ref("sales_team_security_sale.sale_order_line_team_rule", False) if record: record.domain_force = ( "['|', '|', ('salesman_id','=',user.id), ('salesman_id','=',False), '|', " "('order_id.team_id', '=', user.sale_team_id.id), " "('order_id.team_id', '=', False)]" )
42.793103
1,241
618
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.addons.sales_team_security.tests.common import TestCommon class TestSalesTeamSecuritySale(TestCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.record = cls.env["sale.order"].create( { "partner_id": cls.partner.id, "user_id": cls.user.id, "team_id": cls.team.id, } ) def test_sale_order_permissions(self): self._check_whole_permission_set(extra_checks=False)
30.8
616
623
py
PYTHON
15.0
# Copyright 2019 Open Source Integrators # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Tier Validation", "summary": "Extends the functionality of Sale Orders to " "support a tier validation process.", "version": "15.0.1.1.1", "category": "Sale", "website": "https://github.com/OCA/sale-workflow", "author": "Open Source Integrators, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale", "base_tier_validation"], "data": ["data/mail_data.xml", "views/sale_order_view.xml"], }
38.9375
623
2,667
py
PYTHON
15.0
# Copyright 2020 Sergio Teruel <sergio.teruel@tecnativa.com> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from odoo.exceptions import ValidationError from odoo.tests import common, tagged @tagged("-at_install", "post_install") class TestSaleTierValidation(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Get sale order model cls.so_model = cls.env.ref("sale.model_sale_order") # Create users group_ids = ( cls.env.ref("base.group_system") + cls.env.ref("sales_team.group_sale_salesman_all_leads") ).ids cls.test_user_1 = cls.env["res.users"].create( { "name": "John", "login": "test1", "groups_id": [(6, 0, group_ids)], "email": "test@examlple.com", } ) # Create tier definitions: cls.tier_def_obj = cls.env["tier.definition"] cls.tier_def_obj.create( { "model_id": cls.so_model.id, "review_type": "individual", "reviewer_id": cls.test_user_1.id, "definition_domain": "[('amount_untaxed', '>', 50.0)]", } ) cls.customer = cls.env["res.partner"].create({"name": "Partner for test"}) cls.product = cls.env["product.product"].create( {"name": "Product for test", "list_price": 120.00} ) def test_tier_validation_model_name(self): self.assertIn( "sale.order", self.tier_def_obj._get_tier_validation_model_names() ) def test_validation_sale_order(self): so = self.env["sale.order"].create( { "partner_id": self.customer.id, "order_line": [ ( 0, 0, { "name": "Test line", "product_id": self.product.id, "product_uom_qty": 1, "product_uom": self.product.uom_id.id, "price_unit": self.product.list_price, }, ) ], "pricelist_id": self.customer.property_product_pricelist.id, } ) with self.assertRaises(ValidationError): so.action_confirm() so.order_line.price_unit = 45 so.request_validation() so.with_user(self.test_user_1).validate_tier() so.action_confirm() self.assertEqual(so.state, "sale")
35.56
2,667
728
py
PYTHON
15.0
# Copyright 2019 Open Source Integrators # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class SaleOrder(models.Model): _name = "sale.order" _inherit = ["sale.order", "tier.validation"] _state_from = ["draft", "sent"] _state_to = ["sale", "done"] _tier_validation_manual_config = False def _get_requested_notification_subtype(self): return "sale_tier_validation.sale_order_tier_validation_requested" def _get_accepted_notification_subtype(self): return "sale_tier_validation.sale_order_tier_validation_accepted" def _get_rejected_notification_subtype(self): return "sale_tier_validation.sale_order_tier_validation_rejected"
33.090909
728
380
py
PYTHON
15.0
# Copyright 2019 Open Source Integrators # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class TierDefinition(models.Model): _inherit = "tier.definition" @api.model def _get_tier_validation_model_names(self): res = super()._get_tier_validation_model_names() res.append("sale.order") return res
27.142857
380
833
py
PYTHON
15.0
# Copyright 2018 Acsone # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Blanket Orders", "category": "Sale", "license": "AGPL-3", "author": "Acsone SA/NV, Odoo Community Association (OCA)", "version": "15.0.1.2.0", "website": "https://github.com/OCA/sale-workflow", "summary": "Blanket Orders", "depends": ["uom", "sale_management", "web_action_conditionable"], "data": [ "security/security.xml", "security/ir.model.access.csv", "data/sequence.xml", "data/ir_cron.xml", "wizard/create_sale_orders.xml", "views/sale_config_settings.xml", "views/sale_blanket_order_views.xml", "views/sale_order_views.xml", "report/templates.xml", "report/report.xml", ], "installable": True, }
33.32
833
16,108
py
PYTHON
15.0
# Copyright (C) 2018 Eficent Business and IT Consulting Services S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import date, timedelta from odoo import fields from odoo.exceptions import UserError from odoo.tests import common class TestSaleBlanketOrders(common.TransactionCase): def setUp(self): super().setUp() self.blanket_order_obj = self.env["sale.blanket.order"] self.blanket_order_line_obj = self.env["sale.blanket.order.line"] self.blanket_order_wiz_obj = self.env["sale.blanket.order.wizard"] self.so_obj = self.env["sale.order"] self.payment_term = self.env.ref("account.account_payment_term_immediate") self.sale_pricelist = self.env["product.pricelist"].create( {"name": "Test Pricelist", "currency_id": self.env.ref("base.USD").id} ) # UoM self.categ_unit = self.env.ref("uom.product_uom_categ_unit") self.uom_dozen = self.env["uom.uom"].create( { "name": "Test-DozenA", "category_id": self.categ_unit.id, "factor_inv": 12, "uom_type": "bigger", "rounding": 0.001, } ) self.partner = self.env["res.partner"].create( { "name": "TEST CUSTOMER", "property_product_pricelist": self.sale_pricelist.id, } ) self.product = self.env["product.product"].create( { "name": "Demo", "categ_id": self.env.ref("product.product_category_1").id, "standard_price": 35.0, "type": "consu", "uom_id": self.env.ref("uom.product_uom_unit").id, "default_code": "PROD_DEL01", } ) self.product2 = self.env["product.product"].create( { "name": "Demo 2", "categ_id": self.env.ref("product.product_category_1").id, "standard_price": 50.0, "type": "consu", "uom_id": self.env.ref("uom.product_uom_unit").id, "default_code": "PROD_DEL02", } ) self.yesterday = date.today() - timedelta(days=1) self.tomorrow = date.today() + timedelta(days=1) def test_01_create_blanket_order(self): """We create a blanket order and check constrains to confirm BO""" blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.yesterday), "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 0.0, # will be updated later }, ), ( 0, 0, { "name": "My section", "display_type": "line_section", }, ), ], } ) blanket_order.sudo().onchange_partner_id() blanket_order.line_ids[0].sudo().onchange_product() blanket_order.line_ids[0].sudo()._get_display_price(self.product) self.assertEqual(blanket_order.state, "draft") # date in the past with self.assertRaises(UserError): blanket_order.sudo().action_confirm() blanket_order.validity_date = fields.Date.to_string(self.tomorrow) blanket_order.sudo().action_confirm() self.assertEqual(blanket_order.state, "open") blanket_order.sudo().action_cancel() self.assertEqual(blanket_order.state, "expired") blanket_order.sudo().set_to_draft() self.assertEqual(blanket_order.state, "draft") blanket_order.sudo().action_confirm() def test_02_create_sale_orders_from_blanket_order(self): """We create a blanket order and create two sale orders""" blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.tomorrow), "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "line_ids": [ ( 0, 0, { "product_id": False, "product_uom": False, "name": "My section", "display_type": "line_section", }, ), ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() blanket_order.sudo().action_confirm() wizard1 = self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="sale.blanket.order" ).create({}) wizard1.line_ids[0].write({"qty": 10.0}) wizard1.sudo().create_sale_order() wizard2 = self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="sale.blanket.order" ).create({}) wizard2.line_ids[0].write({"qty": 10.0}) wizard2.sudo().create_sale_order() self.assertEqual(blanket_order.state, "done") self.assertEqual(blanket_order.sale_count, 2) view_action = blanket_order.action_view_sale_orders() domain_ids = view_action["domain"][0][2] self.assertEqual(len(domain_ids), 2) sos = self.so_obj.browse(domain_ids) for so in sos: self.assertEqual(so.origin, blanket_order.name) def test_03_create_sale_orders_from_blanket_order_line(self): """We create a blanket order and create two sale orders from the blanket order lines""" blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.tomorrow), "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product2.id, "product_uom": self.product2.uom_id.id, "original_uom_qty": 50.0, "price_unit": 60.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() blanket_order.sudo().action_confirm() bo_lines = blanket_order.line_ids self.assertEqual(len(bo_lines), 2) wizard1 = self.blanket_order_wiz_obj.with_context( active_ids=[bo_lines[0].id, bo_lines[1].id] ).create({}) self.assertEqual(len(wizard1.line_ids), 2) wizard1.line_ids[0].write({"qty": 10.0}) wizard1.line_ids[1].write({"qty": 20.0}) wizard1.sudo().create_sale_order() self.assertEqual(bo_lines[0].remaining_uom_qty, 10.0) self.assertEqual(bo_lines[1].remaining_uom_qty, 30.0) def test_04_create_sale_order_add_blanket_order_line(self): """We create a blanket order and the separately we create a sale order and see if blanket order lines have been correctly assigned""" blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.tomorrow), "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "currency_id": self.sale_pricelist.currency_id.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product2.id, "product_uom": self.product2.uom_id.id, "original_uom_qty": 50.0, "price_unit": 60.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() blanket_order.sudo().action_confirm() bo_lines = blanket_order.line_ids sale_order = self.so_obj.create( { "partner_id": self.partner.id, "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "order_line": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "product_uom_qty": 10.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product2.id, "product_uom": self.product2.uom_id.id, "product_uom_qty": 50.0, "price_unit": 60.0, }, ), ], } ) sale_order.order_line[0].onchange_product_id() self.assertEqual(bo_lines[0].remaining_uom_qty, 10.0) def test_05_create_sale_order_blanket_order_with_different_uom(self): """We create a blanket order and the separately we create a sale order with different uom and see if blanket order lines have been correctly assigned""" blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.tomorrow), "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.uom_dozen.id, "original_uom_qty": 2.0, "price_unit": 240.0, }, ) ], } ) blanket_order.sudo().onchange_partner_id() blanket_order.sudo().action_confirm() sale_order = self.so_obj.create( { "partner_id": self.partner.id, "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "order_line": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "product_uom_qty": 12.0, "price_unit": 30.0, }, ) ], } ) sale_order.order_line[0].onchange_product_id() sale_order.order_line[0].onchange_blanket_order_line() self.assertEqual(blanket_order.line_ids[0].remaining_qty, 12.0) self.assertEqual(sale_order.order_line[0].price_unit, 20.0) def test_06_create_sale_orders_from_blanket_order(self): """We create a blanket order and create three sale orders where the first two consume the first blanket order line """ blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.tomorrow), "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 30.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product2.id, "product_uom": self.product2.uom_id.id, "original_uom_qty": 20.0, "price_unit": 60.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() blanket_order.sudo().action_confirm() wizard1 = self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="sale.blanket.order" ).create({}) wizard1.line_ids.filtered(lambda l: l.product_id == self.product).write( {"qty": 10.0} ) wizard1.line_ids.filtered(lambda l: l.product_id == self.product2).write( {"qty": 10.0} ) wizard1.sudo().create_sale_order() wizard2 = self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="sale.blanket.order" ).create({}) wizard2.line_ids.filtered(lambda l: l.product_id == self.product).write( {"qty": 20.0} ) wizard2.line_ids.filtered(lambda l: l.product_id == self.product2).write( {"qty": 0} ) wizard2.sudo().create_sale_order() wizard3 = self.blanket_order_wiz_obj.with_context( active_id=blanket_order.id, active_model="sale.blanket.order" ).create({}) wizard3.line_ids.filtered(lambda l: l.product_id == self.product2).write( {"qty": 10.0} ) wizard3.sudo().create_sale_order() self.assertEqual(blanket_order.state, "done") self.assertEqual(blanket_order.sale_count, 3) view_action = blanket_order.action_view_sale_orders() domain_ids = view_action["domain"][0][2] self.assertEqual(len(domain_ids), 3)
38.170616
16,108
7,561
py
PYTHON
15.0
# Copyright (C) 2018 Eficent Business and IT Consulting Services S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import date, timedelta from odoo import fields from odoo.tests import common class TestSaleOrder(common.TransactionCase): def setUp(self): super().setUp() self.blanket_order_obj = self.env["sale.blanket.order"] self.blanket_order_line_obj = self.env["sale.blanket.order.line"] self.sale_order_obj = self.env["sale.order"] self.sale_order_line_obj = self.env["sale.order.line"] self.partner = self.env["res.partner"].create({"name": "TEST CUSTOMER"}) self.payment_term = self.env.ref("account.account_payment_term_immediate") self.sale_pricelist = self.env["product.pricelist"].create( {"name": "Test Pricelist", "currency_id": self.env.ref("base.USD").id} ) self.product = self.env["product.product"].create( { "name": "Demo", "categ_id": self.env.ref("product.product_category_1").id, "standard_price": 40.0, "type": "consu", "uom_id": self.env.ref("uom.product_uom_unit").id, "default_code": "PROD_DEL01", } ) self.product_2 = self.env["product.product"].create( { "name": "Demo 2", "categ_id": self.env.ref("product.product_category_1").id, "standard_price": 35.0, "type": "consu", "uom_id": self.env.ref("uom.product_uom_unit").id, "default_code": "PROD_DEL02", } ) self.validity = date.today() + timedelta(days=365) self.date_schedule_1 = date.today() + timedelta(days=10) self.date_schedule_2 = date.today() + timedelta(days=20) def create_blanket_order_01(self): blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.validity), "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "date_schedule": fields.Date.to_string( self.date_schedule_1 ), "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "date_schedule": fields.Date.to_string( self.date_schedule_2 ), "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() return blanket_order def create_blanket_order_02(self): blanket_order = self.blanket_order_obj.create( { "partner_id": self.partner.id, "validity_date": fields.Date.to_string(self.validity), "payment_term_id": self.payment_term.id, "pricelist_id": self.sale_pricelist.id, "line_ids": [ ( 0, 0, { "product_id": self.product.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ( 0, 0, { "product_id": self.product_2.id, "product_uom": self.product.uom_id.id, "original_uom_qty": 20.0, "price_unit": 30.0, }, ), ], } ) blanket_order.sudo().onchange_partner_id() return blanket_order def test_01_create_sale_order(self): blanket_order = self.create_blanket_order_01() blanket_order.sudo().action_confirm() bo_lines = self.blanket_order_line_obj.search( [("order_id", "=", blanket_order.id)] ) self.assertEqual(len(bo_lines), 2) so = self.sale_order_obj.create( { "partner_id": self.partner.id, "order_line": [ ( 0, 0, { "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 5.0, "product_uom": self.product.uom_po_id.id, "price_unit": 10.0, }, ) ], } ) so_line = so.order_line[0] so_line.with_context(from_sale_order=True).name_get() so_line.onchange_product_id() self.assertEqual(so_line._get_eligible_bo_lines(), bo_lines) bo_line_assigned = self.blanket_order_line_obj.search( [("date_schedule", "=", fields.Date.to_string(self.date_schedule_1))] ) self.assertEqual(so_line.blanket_order_line, bo_line_assigned) def test_02_create_sale_order(self): blanket_order = self.create_blanket_order_02() blanket_order.sudo().action_confirm() bo_lines = self.blanket_order_line_obj.search( [("order_id", "=", blanket_order.id)] ) self.assertEqual(len(bo_lines), 2) so = self.sale_order_obj.create( { "partner_id": self.partner.id, "order_line": [ ( 0, 0, { "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 5.0, "product_uom": self.product.uom_po_id.id, "price_unit": 10.0, }, ) ], } ) so_line = so.order_line[0] so_line.with_context(from_sale_order=True).name_get() so_line.onchange_product_id() self.assertEqual( so_line._get_eligible_bo_lines(), bo_lines.filtered(lambda l: l.product_id == self.product), ) bo_line_assigned = self.blanket_order_line_obj.search( [ ("order_id", "=", blanket_order.id), ("product_id", "=", self.product.id), ("date_schedule", "=", False), ] ) self.assertEqual(so_line.blanket_order_line, bo_line_assigned)
38.576531
7,561
8,194
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from collections import defaultdict from odoo import _, api, fields, models from odoo.exceptions import UserError from odoo.tools import float_is_zero class BlanketOrderWizard(models.TransientModel): _name = "sale.blanket.order.wizard" _description = "Blanket order wizard" @api.model def _default_order(self): # in case the cron hasn't run self.env["sale.blanket.order"].expire_orders() if not self.env.context.get("active_id"): return False blanket_order = self.env["sale.blanket.order"].search( [("id", "=", self.env.context["active_id"])], limit=1 ) if blanket_order.state == "expired": raise UserError( _("You can't create a sale order from " "an expired blanket order!") ) return blanket_order @api.model def _check_valid_blanket_order_line(self, bo_lines): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) company_id = False if all( float_is_zero(line.remaining_uom_qty, precision_digits=precision) for line in bo_lines ): raise UserError(_("The sale has already been completed.")) for line in bo_lines: if line.order_id.state != "open": raise UserError( _("Sale Blanket Order %s is not open") % line.order_id.name ) line_company_id = line.company_id and line.company_id.id or False if company_id is not False and line_company_id != company_id: raise UserError(_("You have to select lines " "from the same company.")) else: company_id = line_company_id @api.model def _default_lines(self): blanket_order_line_obj = self.env["sale.blanket.order.line"] blanket_order_line_ids = self.env.context.get("active_ids", False) active_model = self.env.context.get("active_model", False) if active_model == "sale.blanket.order": bo_lines = self._default_order().line_ids else: bo_lines = blanket_order_line_obj.browse(blanket_order_line_ids) self._check_valid_blanket_order_line(bo_lines) lines = [ ( 0, 0, { "blanket_line_id": bol.id, "product_id": bol.product_id.id, "date_schedule": bol.date_schedule, "remaining_uom_qty": bol.remaining_uom_qty, "price_unit": bol.price_unit, "product_uom": bol.product_uom, "qty": bol.remaining_uom_qty, "partner_id": bol.partner_id, }, ) for bol in bo_lines.filtered( lambda l: not l.display_type and l.remaining_uom_qty != 0.0 ) ] return lines blanket_order_id = fields.Many2one( comodel_name="sale.blanket.order", readonly=True, default=lambda self: self._default_order(), ) sale_order_id = fields.Many2one( "sale.order", string="Purchase Order", domain=[("state", "=", "draft")] ) line_ids = fields.One2many( "sale.blanket.order.wizard.line", "wizard_id", string="Lines", default=_default_lines, ) def _prepare_so_line_vals(self, line): return { "product_id": line.product_id.id, "name": line.product_id.name, "product_uom": line.product_uom.id, "sequence": line.blanket_line_id.sequence, "price_unit": line.blanket_line_id.price_unit, "blanket_order_line": line.blanket_line_id.id, "product_uom_qty": line.qty, "tax_id": [(6, 0, line.taxes_id.ids)], "analytic_tag_ids": [(6, 0, line.blanket_line_id.analytic_tag_ids.ids)], } def _prepare_so_vals( self, customer, user_id, currency_id, pricelist_id, payment_term_id, order_lines_by_customer, ): return { "partner_id": customer, "origin": self.blanket_order_id.name, "user_id": user_id, "currency_id": currency_id, "pricelist_id": pricelist_id, "payment_term_id": payment_term_id, "order_line": order_lines_by_customer[customer], "analytic_account_id": self.blanket_order_id.analytic_account_id.id, } def create_sale_order(self): order_lines_by_customer = defaultdict(list) currency_id = 0 pricelist_id = 0 user_id = 0 payment_term_id = 0 for line in self.line_ids.filtered(lambda l: l.qty != 0.0): if line.qty > line.remaining_uom_qty: raise UserError(_("You can't order more than the remaining quantities")) vals = self._prepare_so_line_vals(line) order_lines_by_customer[line.partner_id.id].append((0, 0, vals)) if currency_id == 0: currency_id = line.blanket_line_id.order_id.currency_id.id elif currency_id != line.blanket_line_id.order_id.currency_id.id: currency_id = False if pricelist_id == 0: pricelist_id = line.blanket_line_id.pricelist_id.id elif pricelist_id != line.blanket_line_id.pricelist_id.id: pricelist_id = False if user_id == 0: user_id = line.blanket_line_id.user_id.id elif user_id != line.blanket_line_id.user_id.id: user_id = False if payment_term_id == 0: payment_term_id = line.blanket_line_id.payment_term_id.id elif payment_term_id != line.blanket_line_id.payment_term_id.id: payment_term_id = False if not order_lines_by_customer: raise UserError(_("An order can't be empty")) if not currency_id: raise UserError( _( "Can not create Sale Order from Blanket " "Order lines with different currencies" ) ) res = [] for customer in order_lines_by_customer: order_vals = self._prepare_so_vals( customer, user_id, currency_id, pricelist_id, payment_term_id, order_lines_by_customer, ) sale_order = self.env["sale.order"].create(order_vals) res.append(sale_order.id) return { "domain": [("id", "in", res)], "name": _("Sales Orders"), "view_type": "form", "view_mode": "tree,form", "res_model": "sale.order", "context": {"from_sale_order": True}, "type": "ir.actions.act_window", } class BlanketOrderWizardLine(models.TransientModel): _name = "sale.blanket.order.wizard.line" _description = "Blanket order wizard line" wizard_id = fields.Many2one("sale.blanket.order.wizard") blanket_line_id = fields.Many2one("sale.blanket.order.line") product_id = fields.Many2one( "product.product", related="blanket_line_id.product_id", string="Product" ) product_uom = fields.Many2one( "uom.uom", related="blanket_line_id.product_uom", string="Unit of Measure" ) date_schedule = fields.Date(string="Scheduled Date") remaining_uom_qty = fields.Float(related="blanket_line_id.remaining_uom_qty") qty = fields.Float(string="Quantity to Order", required=True) price_unit = fields.Float(related="blanket_line_id.price_unit") currency_id = fields.Many2one("res.currency", related="blanket_line_id.currency_id") partner_id = fields.Many2one( "res.partner", related="blanket_line_id.partner_id", string="Vendor" ) taxes_id = fields.Many2many("account.tax", related="blanket_line_id.taxes_id")
37.076923
8,194
26,900
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, _, api, fields, models from odoo.exceptions import UserError from odoo.tools import float_is_zero from odoo.tools.misc import format_date class BlanketOrder(models.Model): _name = "sale.blanket.order" _inherit = ["mail.thread", "mail.activity.mixin"] _description = "Blanket Order" @api.model def _get_default_team(self): return self.env["crm.team"]._get_default_team_id() @api.model def _default_currency(self): return self.env.company.currency_id @api.model def _default_company(self): return self.env.company @api.model def _default_note(self): return ( self.env["ir.config_parameter"] .sudo() .get_param("account.use_invoice_terms") and self.env.company.invoice_terms or "" ) @api.depends("line_ids.price_total") def _compute_amount_all(self): for order in self.filtered("currency_id"): amount_untaxed = amount_tax = 0.0 for line in order.line_ids: amount_untaxed += line.price_subtotal amount_tax += line.price_tax order.update( { "amount_untaxed": order.currency_id.round(amount_untaxed), "amount_tax": order.currency_id.round(amount_tax), "amount_total": amount_untaxed + amount_tax, } ) name = fields.Char(default="Draft", readonly=True, copy=False) partner_id = fields.Many2one( "res.partner", string="Partner", readonly=True, states={"draft": [("readonly", False)]}, ) line_ids = fields.One2many( "sale.blanket.order.line", "order_id", string="Order lines", copy=True ) line_count = fields.Integer( string="Sale Blanket Order Line count", compute="_compute_line_count", readonly=True, ) product_id = fields.Many2one( "product.product", related="line_ids.product_id", string="Product", ) pricelist_id = fields.Many2one( "product.pricelist", string="Pricelist", required=True, readonly=True, states={"draft": [("readonly", False)]}, ) currency_id = fields.Many2one("res.currency", related="pricelist_id.currency_id") analytic_account_id = fields.Many2one( comodel_name="account.analytic.account", string="Analytic Account", readonly=True, copy=False, check_company=True, states={"draft": [("readonly", False)]}, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", ) payment_term_id = fields.Many2one( "account.payment.term", string="Payment Terms", readonly=True, states={"draft": [("readonly", False)]}, ) confirmed = fields.Boolean(copy=False) state = fields.Selection( selection=[ ("draft", "Draft"), ("open", "Open"), ("done", "Done"), ("expired", "Expired"), ], compute="_compute_state", store=True, copy=False, ) validity_date = fields.Date(readonly=True, states={"draft": [("readonly", False)]}) client_order_ref = fields.Char( string="Customer Reference", copy=False, readonly=True, states={"draft": [("readonly", False)]}, ) note = fields.Text( readonly=True, default=_default_note, states={"draft": [("readonly", False)]} ) user_id = fields.Many2one( "res.users", string="Salesperson", readonly=True, states={"draft": [("readonly", False)]}, ) team_id = fields.Many2one( "crm.team", string="Sales Team", change_default=True, default=_get_default_team, readonly=True, states={"draft": [("readonly", False)]}, ) company_id = fields.Many2one( "res.company", string="Company", default=_default_company, readonly=True, states={"draft": [("readonly", False)]}, ) sale_count = fields.Integer(compute="_compute_sale_count") fiscal_position_id = fields.Many2one( "account.fiscal.position", string="Fiscal Position" ) amount_untaxed = fields.Monetary( string="Untaxed Amount", store=True, readonly=True, compute="_compute_amount_all", tracking=True, ) amount_tax = fields.Monetary( string="Taxes", store=True, readonly=True, compute="_compute_amount_all" ) amount_total = fields.Monetary( string="Total", store=True, readonly=True, compute="_compute_amount_all" ) # Fields use to filter in tree view original_uom_qty = fields.Float( string="Original quantity", compute="_compute_uom_qty", search="_search_original_uom_qty", default=0.0, ) ordered_uom_qty = fields.Float( string="Ordered quantity", compute="_compute_uom_qty", search="_search_ordered_uom_qty", default=0.0, ) invoiced_uom_qty = fields.Float( string="Invoiced quantity", compute="_compute_uom_qty", search="_search_invoiced_uom_qty", default=0.0, ) remaining_uom_qty = fields.Float( string="Remaining quantity", compute="_compute_uom_qty", search="_search_remaining_uom_qty", default=0.0, ) delivered_uom_qty = fields.Float( string="Delivered quantity", compute="_compute_uom_qty", search="_search_delivered_uom_qty", default=0.0, ) def _get_sale_orders(self): return self.mapped("line_ids.sale_lines.order_id") @api.depends("line_ids") def _compute_line_count(self): self.line_count = len(self.mapped("line_ids")) def _compute_sale_count(self): for blanket_order in self: blanket_order.sale_count = len(blanket_order._get_sale_orders()) @api.depends( "line_ids.remaining_uom_qty", "validity_date", "confirmed", ) def _compute_state(self): today = fields.Date.today() precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) for order in self: if not order.confirmed: order.state = "draft" elif order.validity_date <= today: order.state = "expired" elif float_is_zero( sum( order.line_ids.filtered(lambda l: not l.display_type).mapped( "remaining_uom_qty" ) ), precision_digits=precision, ): order.state = "done" else: order.state = "open" def _compute_uom_qty(self): for bo in self: bo.original_uom_qty = sum(bo.mapped("order_id.original_uom_qty")) bo.ordered_uom_qty = sum(bo.mapped("order_id.ordered_uom_qty")) bo.invoiced_uom_qty = sum(bo.mapped("order_id.invoiced_uom_qty")) bo.delivered_uom_qty = sum(bo.mapped("order_id.delivered_uom_qty")) bo.remaining_uom_qty = sum(bo.mapped("order_id.remaining_uom_qty")) @api.onchange("partner_id") def onchange_partner_id(self): """ Update the following fields when the partner is changed: - Pricelist - Payment term - Fiscal position """ if not self.partner_id: self.payment_term_id = False self.fiscal_position_id = False return values = { "pricelist_id": ( self.partner_id.property_product_pricelist and self.partner_id.property_product_pricelist.id or False ), "payment_term_id": ( self.partner_id.property_payment_term_id and self.partner_id.property_payment_term_id.id or False ), "fiscal_position_id": self.env["account.fiscal.position"] .with_context(company_id=self.company_id.id) .get_fiscal_position(self.partner_id.id), } if self.partner_id.user_id: values["user_id"] = self.partner_id.user_id.id if self.partner_id.team_id: values["team_id"] = self.partner_id.team_id.id self.update(values) def unlink(self): for order in self: if order.state not in ("draft", "expired") or order._check_active_orders(): raise UserError( _( "You can not delete an open blanket or " "with active sale orders! " "Try to cancel it before." ) ) return super().unlink() def _validate(self): try: today = fields.Date.today() for order in self: assert order.validity_date, _("Validity date is mandatory") assert order.validity_date > today, _( "Validity date must be in the future" ) assert order.partner_id, _("Partner is mandatory") assert len(order.line_ids) > 0, _("Must have some lines") order.line_ids._validate() except AssertionError as e: raise UserError(e) from e def set_to_draft(self): for order in self: order.write({"state": "draft", "confirmed": False}) return True def action_confirm(self): self._validate() for order in self: sequence_obj = self.env["ir.sequence"] if order.company_id: sequence_obj = sequence_obj.with_company(order.company_id.id) name = sequence_obj.next_by_code("sale.blanket.order") order.write({"confirmed": True, "name": name}) return True def _check_active_orders(self): for order in self.filtered("sale_count"): for so in order._get_sale_orders(): if so.state not in ("cancel"): return True return False def action_cancel(self): for order in self: if order._check_active_orders(): raise UserError( _( "You can not delete a blanket order with opened " "sale orders! " "Try to cancel them before." ) ) order.write({"state": "expired"}) return True def action_view_sale_orders(self): sale_orders = self._get_sale_orders() action = self.env.ref("sale.action_orders").read()[0] if len(sale_orders) > 0: action["domain"] = [("id", "in", sale_orders.ids)] action["context"] = [("id", "in", sale_orders.ids)] else: action = {"type": "ir.actions.act_window_close"} return action def action_view_sale_blanket_order_line(self): action = self.env.ref( "sale_blanket_order" ".act_open_sale_blanket_order_lines_view_tree" ).read()[0] lines = self.mapped("line_ids") if len(lines) > 0: action["domain"] = [("id", "in", lines.ids)] return action @api.model def expire_orders(self): today = fields.Date.today() expired_orders = self.search( [("state", "=", "open"), ("validity_date", "<=", today)] ) expired_orders.modified(["validity_date"]) expired_orders.recompute() @api.model def _search_original_uom_qty(self, operator, value): bo_line_obj = self.env["sale.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("original_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res @api.model def _search_ordered_uom_qty(self, operator, value): bo_line_obj = self.env["sale.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("ordered_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res @api.model def _search_invoiced_uom_qty(self, operator, value): bo_line_obj = self.env["sale.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("invoiced_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res @api.model def _search_delivered_uom_qty(self, operator, value): bo_line_obj = self.env["sale.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("delivered_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res @api.model def _search_remaining_uom_qty(self, operator, value): bo_line_obj = self.env["sale.blanket.order.line"] res = [] bo_lines = bo_line_obj.search([("remaining_uom_qty", operator, value)]) order_ids = bo_lines.mapped("order_id") res.append(("id", "in", order_ids.ids)) return res class BlanketOrderLine(models.Model): _name = "sale.blanket.order.line" _description = "Blanket Order Line" _inherit = ["mail.thread", "mail.activity.mixin"] @api.depends( "original_uom_qty", "price_unit", "taxes_id", "order_id.partner_id", "product_id", "currency_id", ) def _compute_amount(self): for line in self: price = line.price_unit taxes = line.taxes_id.compute_all( price, line.currency_id, line.original_uom_qty, product=line.product_id, partner=line.order_id.partner_id, ) line.update( { "price_tax": sum( t.get("amount", 0.0) for t in taxes.get("taxes", []) ), "price_total": taxes["total_included"], "price_subtotal": taxes["total_excluded"], } ) name = fields.Char("Description", tracking=True) sequence = fields.Integer() order_id = fields.Many2one("sale.blanket.order", required=True, ondelete="cascade") product_id = fields.Many2one( "product.product", string="Product", domain=[("sale_ok", "=", True)], ) product_uom = fields.Many2one("uom.uom", string="Unit of Measure") price_unit = fields.Float(string="Price", digits="Product Price") taxes_id = fields.Many2many( "account.tax", string="Taxes", domain=["|", ("active", "=", False), ("active", "=", True)], ) date_schedule = fields.Date(string="Scheduled Date") original_uom_qty = fields.Float( string="Original quantity", default=1, digits="Product Unit of Measure", ) ordered_uom_qty = fields.Float( string="Ordered quantity", compute="_compute_quantities", store=True ) invoiced_uom_qty = fields.Float( string="Invoiced quantity", compute="_compute_quantities", store=True ) remaining_uom_qty = fields.Float( string="Remaining quantity", compute="_compute_quantities", store=True ) remaining_qty = fields.Float( string="Remaining quantity in base UoM", compute="_compute_quantities", store=True, ) delivered_uom_qty = fields.Float( string="Delivered quantity", compute="_compute_quantities", store=True ) sale_lines = fields.One2many( "sale.order.line", "blanket_order_line", string="Sale order lines", readonly=True, copy=False, ) company_id = fields.Many2one( "res.company", related="order_id.company_id", store=True ) currency_id = fields.Many2one("res.currency", related="order_id.currency_id") partner_id = fields.Many2one(related="order_id.partner_id", string="Customer") user_id = fields.Many2one(related="order_id.user_id", string="Responsible") payment_term_id = fields.Many2one( related="order_id.payment_term_id", string="Payment Terms" ) pricelist_id = fields.Many2one(related="order_id.pricelist_id", string="Pricelist") price_subtotal = fields.Monetary( compute="_compute_amount", string="Subtotal", store=True ) price_total = fields.Monetary(compute="_compute_amount", string="Total", store=True) price_tax = fields.Float(compute="_compute_amount", string="Tax", store=True) analytic_tag_ids = fields.Many2many( comodel_name="account.analytic.tag", string="Analytic Tags", domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]", ) display_type = fields.Selection( [("line_section", "Section"), ("line_note", "Note")], default=False, help="Technical field for UX purpose.", ) def name_get(self): result = [] if self.env.context.get("from_sale_order"): for record in self: res = "[%s]" % record.order_id.name if record.date_schedule: formatted_date = format_date(record.env, record.date_schedule) res += " - {}: {}".format(_("Date Scheduled"), formatted_date) res += " ({}: {} {})".format( _("remaining"), record.remaining_uom_qty, record.product_uom.name, ) result.append((record.id, res)) return result return super().name_get() def _get_real_price_currency(self, product, rule_id, qty, uom, pricelist_id): """Retrieve the price before applying the pricelist :param obj product: object of current product record :param float qty: total quentity of product :param tuple price_and_rule: tuple(price, suitable_rule) coming from pricelist computation :param obj uom: unit of measure of current order line :param integer pricelist_id: pricelist id of sale order""" # Copied and adapted from the sale module PricelistItem = self.env["product.pricelist.item"] field_name = "lst_price" currency_id = None product_currency = None if rule_id: pricelist_item = PricelistItem.browse(rule_id) if pricelist_item.pricelist_id.discount_policy == "without_discount": while ( pricelist_item.base == "pricelist" and pricelist_item.base_pricelist_id and pricelist_item.base_pricelist_id.discount_policy == "without_discount" ): price, rule_id = pricelist_item.base_pricelist_id.with_context( uom=uom.id ).get_product_price_rule(product, qty, self.order_id.partner_id) pricelist_item = PricelistItem.browse(rule_id) if pricelist_item.base == "standard_price": field_name = "standard_price" if pricelist_item.base == "pricelist" and pricelist_item.base_pricelist_id: field_name = "price" product = product.with_context( pricelist=pricelist_item.base_pricelist_id.id ) product_currency = pricelist_item.base_pricelist_id.currency_id currency_id = pricelist_item.pricelist_id.currency_id product_currency = ( product_currency or (product.company_id and product.company_id.currency_id) or self.env.company.currency_id ) if not currency_id: currency_id = product_currency cur_factor = 1.0 else: if currency_id.id == product_currency.id: cur_factor = 1.0 else: cur_factor = currency_id._get_conversion_rate( product_currency, currency_id ) product_uom = product.uom_id.id if uom and uom.id != product_uom: # the unit price is in a different uom uom_factor = uom._compute_price(1.0, product.uom_id) else: uom_factor = 1.0 return product[field_name] * uom_factor * cur_factor, currency_id.id def _get_display_price(self, product): # Copied and adapted from the sale module self.ensure_one() pricelist = self.order_id.pricelist_id partner = self.order_id.partner_id if self.order_id.pricelist_id.discount_policy == "with_discount": return product.with_context(pricelist=pricelist.id).price final_price, rule_id = pricelist.get_product_price_rule( self.product_id, self.original_uom_qty or 1.0, partner ) context_partner = dict( self.env.context, partner_id=partner.id, date=fields.Date.today() ) base_price, currency_id = self.with_context( **context_partner )._get_real_price_currency( self.product_id, rule_id, self.original_uom_qty, self.product_uom, pricelist.id, ) if currency_id != pricelist.currency_id.id: currency = self.env["res.currency"].browse(currency_id) base_price = currency.with_context(**context_partner).compute( base_price, pricelist.currency_id ) # negative discounts (= surcharge) are included in the display price return max(base_price, final_price) @api.onchange("product_id", "original_uom_qty") def onchange_product(self): precision = self.env["decimal.precision"].precision_get( "Product Unit of Measure" ) if self.product_id: name = self.product_id.name if not self.product_uom: self.product_uom = self.product_id.uom_id.id if self.order_id.partner_id and float_is_zero( self.price_unit, precision_digits=precision ): self.price_unit = self._get_display_price(self.product_id) if self.product_id.code: name = "[{}] {}".format(name, self.product_id.code) if self.product_id.description_sale: name += "\n" + self.product_id.description_sale self.name = name fpos = self.order_id.fiscal_position_id if self.env.uid == SUPERUSER_ID: company_id = self.env.company.id self.taxes_id = fpos.map_tax( self.product_id.taxes_id.filtered( lambda r: r.company_id.id == company_id ) ) else: self.taxes_id = fpos.map_tax(self.product_id.taxes_id) @api.depends( "sale_lines.order_id.state", "sale_lines.blanket_order_line", "sale_lines.product_uom_qty", "sale_lines.product_uom", "sale_lines.qty_delivered", "sale_lines.qty_invoiced", "original_uom_qty", "product_uom", ) def _compute_quantities(self): for line in self: sale_lines = line.sale_lines line.ordered_uom_qty = sum( sl.product_uom._compute_quantity(sl.product_uom_qty, line.product_uom) for sl in sale_lines if sl.order_id.state != "cancel" and sl.product_id == line.product_id ) line.invoiced_uom_qty = sum( sl.product_uom._compute_quantity(sl.qty_invoiced, line.product_uom) for sl in sale_lines if sl.order_id.state != "cancel" and sl.product_id == line.product_id ) line.delivered_uom_qty = sum( sl.product_uom._compute_quantity(sl.qty_delivered, line.product_uom) for sl in sale_lines if sl.order_id.state != "cancel" and sl.product_id == line.product_id ) line.remaining_uom_qty = line.original_uom_qty - line.ordered_uom_qty line.remaining_qty = line.product_uom._compute_quantity( line.remaining_uom_qty, line.product_id.uom_id ) def _validate(self): try: for line in self: assert ( not line.display_type and line.price_unit > 0.0 ) or line.display_type, _("Price must be greater than zero") assert ( not line.display_type and line.original_uom_qty > 0.0 ) or line.display_type, _("Quantity must be greater than zero") except AssertionError as e: raise UserError(e) from e @api.model_create_multi def create(self, vals_list): for values in vals_list: if values.get( "display_type", self.default_get(["display_type"])["display_type"] ): values.update(product_id=False, price_unit=0, product_uom=False) return super().create(vals_list) _sql_constraints = [ ( "accountable_required_fields", """ CHECK( display_type IS NOT NULL OR ( product_id IS NOT NULL AND product_uom IS NOT NULL ) ) """, "Missing required fields on accountable sale order line.", ), ( "non_accountable_null_fields", """ CHECK( display_type IS NULL OR ( product_id IS NULL AND price_unit = 0 AND product_uom IS NULL ) ) """, "Forbidden values on non-accountable sale order line", ), ] def write(self, values): if "display_type" in values and self.filtered( lambda line: line.display_type != values.get("display_type") ): raise UserError( _( """ You cannot change the type of a sale order line. Instead you should delete the current line and create a new line of the proper type. """ ) ) return super(BlanketOrderLine, self).write(values)
36.204576
26,900
6,042
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # Copyright 2019 Eficent and IT Consulting Services, S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import date, timedelta from odoo import _, api, fields, models from odoo.exceptions import ValidationError class SaleOrder(models.Model): _inherit = "sale.order" blanket_order_id = fields.Many2one( "sale.blanket.order", string="Origin blanket order", related="order_line.blanket_order_line.order_id", ) @api.model def _check_exchausted_blanket_order_line(self): return any( line.blanket_order_line.remaining_qty < 0.0 for line in self.order_line ) def button_confirm(self): res = super().button_confirm() for order in self: if order._check_exchausted_blanket_order_line(): raise ValidationError( _( "Cannot confirm order %s as one of the lines refers " "to a blanket order that has no remaining quantity." ) % order.name ) return res @api.constrains("partner_id") def check_partner_id(self): for line in self.order_line: if line.blanket_order_line: if line.blanket_order_line.partner_id != self.partner_id: raise ValidationError( _( "The customer must be equal to the " "blanket order lines customer" ) ) class SaleOrderLine(models.Model): _inherit = "sale.order.line" blanket_order_line = fields.Many2one( "sale.blanket.order.line", string="Blanket Order line", copy=False ) def _get_assigned_bo_line(self, bo_lines): # We get the blanket order line with enough quantity and closest # scheduled date assigned_bo_line = False date_planned = date.today() date_delta = timedelta(days=365) for line in bo_lines.filtered(lambda l: l.date_schedule): date_schedule = line.date_schedule if date_schedule and abs(date_schedule - date_planned) < date_delta: assigned_bo_line = line date_delta = abs(date_schedule - date_planned) if assigned_bo_line: return assigned_bo_line non_date_bo_lines = bo_lines.filtered(lambda l: not l.date_schedule) if non_date_bo_lines: return non_date_bo_lines[0] def _get_eligible_bo_lines_domain(self, base_qty): filters = [ ("product_id", "=", self.product_id.id), ("remaining_qty", ">=", base_qty), ("currency_id", "=", self.order_id.currency_id.id), ("order_id.state", "=", "open"), ] if self.order_id.partner_id: filters.append(("partner_id", "=", self.order_id.partner_id.id)) return filters def _get_eligible_bo_lines(self): base_qty = self.product_uom._compute_quantity( self.product_uom_qty, self.product_id.uom_id ) filters = self._get_eligible_bo_lines_domain(base_qty) return self.env["sale.blanket.order.line"].search(filters) def get_assigned_bo_line(self): self.ensure_one() eligible_bo_lines = self._get_eligible_bo_lines() if eligible_bo_lines: if ( not self.blanket_order_line or self.blanket_order_line not in eligible_bo_lines ): self.blanket_order_line = self._get_assigned_bo_line(eligible_bo_lines) else: self.blanket_order_line = False self.onchange_blanket_order_line() return {"domain": {"blanket_order_line": [("id", "in", eligible_bo_lines.ids)]}} @api.onchange("product_id", "order_partner_id") def onchange_product_id(self): # If product has changed remove the relation with blanket order line if self.product_id: return self.get_assigned_bo_line() return @api.onchange("product_uom_qty", "product_uom") def product_uom_change(self): res = super().product_uom_change() if self.product_id and not self.env.context.get("skip_blanket_find", False): return self.get_assigned_bo_line() return res @api.onchange("blanket_order_line") def onchange_blanket_order_line(self): bol = self.blanket_order_line if bol: self.product_id = bol.product_id if bol.product_uom != self.product_uom: price_unit = bol.product_uom._compute_price( bol.price_unit, self.product_uom ) else: price_unit = bol.price_unit self.price_unit = price_unit if bol.taxes_id: self.tax_id = bol.taxes_id else: if not self.tax_id: self._compute_tax_id() self.with_context(skip_blanket_find=True).product_uom_change() @api.constrains("product_id") def check_product_id(self): for line in self: if ( line.blanket_order_line and line.product_id != line.blanket_order_line.product_id ): raise ValidationError( _( "The product in the blanket order and in the " "sales order must match" ) ) @api.constrains("currency_id") def check_currency(self): for line in self: if line.blanket_order_line: if line.currency_id != line.blanket_order_line.order_id.currency_id: raise ValidationError( _( "The currency of the blanket order must match with " "that of the sale order." ) )
36.841463
6,042
411
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class SaleConfigSettings(models.TransientModel): _inherit = "res.config.settings" group_blanket_disable_adding_lines = fields.Boolean( string="Disable adding more lines to SOs", implied_group="sale_blanket_order.blanket_orders_disable_adding_lines", )
29.357143
411
791
py
PYTHON
15.0
# Copyright 2015 Anybox # Copyright 2018 Camptocamp, ACSONE SA/NV # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale product set", "category": "Sale", "license": "AGPL-3", "author": "Anybox, Odoo Community Association (OCA)", "version": "15.0.1.0.1", "website": "https://github.com/OCA/sale-workflow", "summary": "Sale product set", "depends": ["sale", "sale_management", "onchange_helper"], "data": [ "security/ir.model.access.csv", "security/rule_product_set.xml", "views/product_set.xml", "views/product_set_line.xml", "wizard/product_set_add.xml", "views/sale_order.xml", ], "demo": ["demo/product_set.xml", "demo/product_set_line.xml"], "installable": True, }
34.391304
791
8,360
py
PYTHON
15.0
# Copyright 2015 Anybox S.A.S # Copyright 2016-2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import exceptions from odoo.tests import common class TestProductSet(common.TransactionCase): """Test Product set""" @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.so_model = cls.env["sale.order"] cls.so = cls.env.ref("sale.sale_order_6") cls.product_set_add = cls.env["product.set.add"] cls.product_set = cls.env.ref("sale_product_set.product_set_i5_computer") def _get_wiz(self, ctx=None, **kw): vals = { "product_set_id": self.product_set.id, "order_id": self.so.id, "quantity": 2, } vals.update(kw) return self.product_set_add.with_context(**ctx or {}).create(vals) def test_add_set_lines_init(self): wiz = self._get_wiz() # Default to all lines from set self.assertEqual(wiz.product_set_line_ids, self.product_set.set_line_ids) self.assertEqual( [x.id for x in wiz._get_lines()], self.product_set.set_line_ids.ids ) # Pass via ctx line_ids = self.env.ref("sale_product_set.product_set_line_computer_1").ids wiz = self._get_wiz(ctx=dict(product_set_add__set_line_ids=line_ids)) self.assertEqual(wiz.product_set_line_ids.ids, line_ids) self.assertEqual([x.id for x in wiz._get_lines()], line_ids) # Pass at create line_ids = self.env.ref("sale_product_set.product_set_line_computer_3").ids wiz = self._get_wiz() wiz.product_set_line_ids = line_ids self.assertEqual(wiz.product_set_line_ids.ids, line_ids) self.assertEqual([x.id for x in wiz._get_lines()], line_ids) def test_add_set(self): so = self.so count_lines = len(so.order_line) # Simulation the opening of the wizard and adding a set on the # current sale order wiz = self._get_wiz() wiz.add_set() # checking our sale order self.assertEqual(len(so.order_line), count_lines + 3) # check all lines are included for line in self.product_set.set_line_ids: order_line = so.order_line.filtered( lambda x: x.product_id == line.product_id ) order_line.ensure_one() self.assertEqual(order_line.product_uom_qty, line.quantity * wiz.quantity) sequence = {} for line in so.order_line: sequence[line.product_id.id] = line.sequence # make sure sale order line sequence keep sequence set on set seq_line1 = sequence.pop( self.env.ref("sale_product_set.product_set_line_computer_4").product_id.id ) seq_line2 = sequence.pop( self.env.ref("sale_product_set.product_set_line_computer_1").product_id.id ) seq_line3 = sequence.pop( self.env.ref("sale_product_set.product_set_line_computer_3").product_id.id ) self.assertTrue( max(v for k, v in sequence.items()) < seq_line1 < seq_line2 < seq_line3 ) def test_add_set_sequence(self): so = self.so count_lines = len(so.order_line) # Start from -1 to have mixed negative, null and positive (-1, 0, 1) for seq, line in enumerate(self.product_set.set_line_ids, start=-1): line.write({"sequence": seq}) wiz = self._get_wiz() wiz.add_set() sequence = {line.product_id: line.sequence for line in so.order_line} self.assertEqual(len(so.order_line), count_lines + 3) # make sure sale order line sequence keep sequence set on set seq_line1 = sequence.pop( self.env.ref("sale_product_set.product_set_line_computer_4").product_id ) seq_line2 = sequence.pop( self.env.ref("sale_product_set.product_set_line_computer_1").product_id ) seq_line3 = sequence.pop( self.env.ref("sale_product_set.product_set_line_computer_3").product_id ) self.assertTrue( max(v for k, v in sequence.items()) < seq_line1 < seq_line2 < seq_line3 ) def test_delete_set(self): # Simulation the opening of the wizard and adding a set on the # current sale order wiz = self._get_wiz() self.product_set.unlink() self.assertFalse(wiz.exists()) def test_add_set_on_empty_so(self): so = self.so_model.create({"partner_id": self.ref("base.res_partner_1")}) wiz = self._get_wiz(order_id=so.id) wiz.add_set() self.assertEqual(len(so.order_line), 3) def test_add_set_non_matching_partner(self): so = self.so_model.create({"partner_id": self.ref("base.res_partner_1")}) self.product_set.partner_id = self.ref("base.res_partner_2") wiz = self._get_wiz(order_id=so.id) with self.assertRaises(exceptions.ValidationError): wiz.add_set() def test_add_set_non_matching_partner_ctx_bypass(self): so = self.so_model.create({"partner_id": self.ref("base.res_partner_1")}) self.assertEqual(len(so.order_line), 0) self.product_set.partner_id = self.ref("base.res_partner_2") wiz = self._get_wiz(order_id=so.id).with_context( product_set_add_skip_validation=True ) wiz.add_set() self.assertEqual(len(so.order_line), 3) def test_add_set_non_matching_partner_ctx_override(self): so = self.so_model.create({"partner_id": self.ref("base.res_partner_1")}) self.assertEqual(len(so.order_line), 0) wiz = self._get_wiz(order_id=so.id).with_context( allowed_order_partner_ids=[self.ref("base.res_partner_2")] ) wiz.add_set() self.assertEqual(len(so.order_line), 3) def test_add_set_no_update_existing_products(self): so = self.so_model.create({"partner_id": self.ref("base.res_partner_1")}) wiz = self._get_wiz(order_id=so.id) wiz.add_set() self.assertEqual(len(so.order_line), 3) # if we run it again by default the wizard sums up quantities wiz.add_set() self.assertEqual(len(so.order_line), 6) # but we can turn it off wiz.skip_existing_products = True wiz.add_set() self.assertEqual(len(so.order_line), 6) def test_name(self): product_set = self.product_set # no ref product_set.name = "Foo" product_set.ref = "" self.assertEqual(product_set.name_get(), [(product_set.id, "Foo")]) # with ref product_set.ref = "123" self.assertEqual(product_set.name_get(), [(product_set.id, "[123] Foo")]) # with partner partner = self.env.ref("base.res_partner_1") product_set.partner_id = partner self.assertEqual( product_set.name_get(), [(product_set.id, "[123] Foo @ %s" % partner.name)] ) def test_discount(self): product_test = self.env["product.product"].create( {"name": "Test", "list_price": 100.0} ) set_line = self.env["product.set.line"].create( {"product_id": product_test.id, "quantity": 1, "discount": 50} ) prod_set = self.env["product.set"].create( {"name": "Test", "set_line_ids": [(4, set_line.id)]} ) so = self.env.ref("sale.sale_order_6") wiz = self.product_set_add.create( {"order_id": so.id, "product_set_id": prod_set.id, "quantity": 1} ) wiz.add_set() order_line = so.order_line.filtered( lambda x: x.product_id == prod_set.set_line_ids[0].product_id ) order_line.ensure_one() self.assertEqual(order_line.discount, set_line.discount) def test_product_set_delete_in_wizard(self): products = self.so.order_line.product_id wizard = self._get_wiz() wizard.write({"product_set_line_ids": [(3, wizard.product_set_line_ids[0].id)]}) products |= wizard.product_set_line_ids.product_id wizard.add_set() self.assertEqual(products, self.so.order_line.product_id) self.assertEqual(len(self.so.order_line), 3)
41.386139
8,360
5,098
py
PYTHON
15.0
# Copyright 2015 Anybox S.A.S # Copyright 2016-2020 Camptocamp SA # @author Simone Orsi <simahawk@gmail.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, exceptions, fields, models class ProductSetAdd(models.TransientModel): _name = "product.set.add" _rec_name = "product_set_id" _description = "Wizard model to add product set into a quotation" order_id = fields.Many2one( "sale.order", "Sale Order", required=True, default=lambda self: self.env.context.get("active_id") if self.env.context.get("active_model") == "sale.order" else None, ondelete="cascade", ) partner_id = fields.Many2one(related="order_id.partner_id", ondelete="cascade") product_set_id = fields.Many2one( "product.set", "Product set", required=True, ondelete="cascade" ) product_set_line_ids = fields.Many2many( "product.set.line", string="Product set lines", required=True, store=True, ondelete="cascade", compute="_compute_product_set_line_ids", readonly=False, ) quantity = fields.Float( digits="Product Unit of Measure", required=True, default=1.0 ) skip_existing_products = fields.Boolean( default=False, help="Enable this to not add new lines " "for products already included in SO lines.", ) @api.depends_context("product_set_add__set_line_ids") @api.depends("product_set_id") def _compute_product_set_line_ids(self): line_ids = self.env.context.get("product_set_add__set_line_ids", []) lines_from_ctx = self.env["product.set.line"].browse(line_ids) for rec in self: if rec.product_set_line_ids: # Passed on creation continue lines = lines_from_ctx.filtered( lambda x: x.product_set_id == rec.product_set_id ) if lines: # Use the ones from ctx but make sure they belong to the same set. rec.product_set_line_ids = lines else: # Fallback to all lines from current set rec.product_set_line_ids = rec.product_set_id.set_line_ids def _check_partner(self): """Validate order partner against product set's partner if any.""" if not self.product_set_id.partner_id or self.env.context.get( "product_set_add_skip_validation" ): return allowed_partners = self._allowed_order_partners() if self.order_id.partner_id not in allowed_partners: raise exceptions.ValidationError( _( "You can use a sale order assigned " "only to following partner(s): {}" ).format(", ".join(allowed_partners.mapped("name"))) ) def _allowed_order_partners(self): """Product sets' partners allowed for current sale order.""" partner_ids = self.env.context.get("allowed_order_partner_ids") if partner_ids: return self.env["res.partner"].browse(partner_ids) return self.product_set_id.partner_id def add_set(self): """Add product set, multiplied by quantity in sale order line""" self._check_partner() order_lines = self._prepare_order_lines() if order_lines: self.order_id.write({"order_line": order_lines}) return order_lines def _prepare_order_lines(self): max_sequence = self._get_max_sequence() order_lines = [] for seq, set_line in enumerate(self._get_lines(), start=1): values = self.prepare_sale_order_line_data(set_line) # When we play with sequence widget on a set of product, # it's possible to have a negative sequence. # In this case, the line is not added at the correct place. # So we have to force it with the order of the line. values.update({"sequence": max_sequence + seq}) order_lines.append((0, 0, values)) return order_lines def _get_max_sequence(self): max_sequence = 0 if self.order_id.order_line: max_sequence = max(line.sequence for line in self.order_id.order_line) return max_sequence def _get_lines(self): # hook here to take control on used lines so_product_ids = self.order_id.order_line.mapped("product_id").ids for set_line in self.product_set_line_ids: if self.skip_existing_products and set_line.product_id.id in so_product_ids: continue yield set_line def prepare_sale_order_line_data(self, set_line, max_sequence=0): self.ensure_one() line_values = set_line.prepare_sale_order_line_values( self.order_id, self.quantity, max_sequence=max_sequence ) sol_model = self.env["sale.order.line"] line_values.update(sol_model.play_onchanges(line_values, line_values.keys())) return line_values
39.828125
5,098
1,410
py
PYTHON
15.0
# Copyright 2015 Anybox S.A.S # Copyright 2016-2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProductSetLine(models.Model): _name = "product.set.line" _description = "Product set line" _rec_name = "product_id" _order = "sequence" product_id = fields.Many2one( comodel_name="product.product", domain=[("sale_ok", "=", True)], string="Product", required=True, ) quantity = fields.Float( digits="Product Unit of Measure", required=True, default=1.0 ) product_set_id = fields.Many2one("product.set", string="Set", ondelete="cascade") active = fields.Boolean( string="Active", related="product_set_id.active", store=True, readonly=True ) sequence = fields.Integer(required=True, default=0) discount = fields.Float(string="Discount (%)", digits="Discount", default=0.0) def prepare_sale_order_line_values(self, order, quantity, max_sequence=0): self.ensure_one() return { "order_id": order.id, "product_id": self.product_id.id, "product_uom_qty": self.quantity * quantity, "product_uom": self.product_id.uom_id.id, "sequence": max_sequence + self.sequence, "discount": self.discount, "company_id": order.company_id.id, }
36.153846
1,410
1,410
py
PYTHON
15.0
# Copyright 2015 Anybox S.A.S # Copyright 2016-2018 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProductSet(models.Model): _name = "product.set" _description = "Product set" name = fields.Char(help="Product set name", required=True) active = fields.Boolean(default=True) ref = fields.Char( string="Internal Reference", help="Product set internal reference", copy=False ) set_line_ids = fields.One2many( "product.set.line", "product_set_id", string="Products", copy=True ) company_id = fields.Many2one( "res.company", "Company", default=lambda self: self.env.company, ondelete="cascade", ) partner_id = fields.Many2one( comodel_name="res.partner", required=False, ondelete="cascade", index=True, help="You can attache the set to a specific partner " "or no one. If you don't specify one, " "it's going to be available for all of them.", ) def name_get(self): return [(rec.id, rec._name_get()) for rec in self] def _name_get(self): parts = [] if self.ref: parts.append("[%s]" % self.ref) parts.append(self.name) if self.partner_id: parts.append("@ %s" % self.partner_id.name) return " ".join(parts)
31.333333
1,410
787
py
PYTHON
15.0
# Copyright 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # Copyright 2013 Camptocamp SA (author: Guewen Baconnier) # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Automatic Workflow", "version": "15.0.1.0.1", "category": "Sales Management", "license": "AGPL-3", "author": "Akretion, " "Camptocamp, " "Sodexis, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "depends": ["sale_stock", "sales_team", "sale_delivery_state"], "data": [ "security/ir.model.access.csv", "views/sale_view.xml", "views/sale_workflow_process_view.xml", "data/automatic_workflow_data.xml", ], "installable": True, }
32.75
786
7,239
py
PYTHON
15.0
# Copyright 2014 Camptocamp SA (author: Guewen Baconnier) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import timedelta import mock from odoo import fields from odoo.tests import tagged from .common import TestAutomaticWorkflowMixin, TestCommon @tagged("post_install", "-at_install") class TestAutomaticWorkflow(TestCommon, TestAutomaticWorkflowMixin): def setUp(self): super().setUp() self.env = self.env( context=dict( self.env.context, tracking_disable=True, # Compatibility with sale_automatic_workflow_job: even if # the module is installed, ensure we don't delay a job. # Thus, we test the usual flow. _job_force_sync=True, ) ) def test_full_automatic(self): workflow = self.create_full_automatic() sale = self.create_sale_order(workflow) sale._onchange_workflow_process_id() self.assertEqual(sale.state, "draft") self.assertEqual(sale.workflow_process_id, workflow) self.run_job() self.assertEqual(sale.state, "sale") self.assertTrue(sale.picking_ids) self.assertTrue(sale.invoice_ids) invoice = sale.invoice_ids self.assertEqual(invoice.state, "posted") picking = sale.picking_ids self.run_job() self.assertEqual(picking.state, "done") def test_onchange(self): workflow = self.create_full_automatic() sale = self.create_sale_order(workflow) sale._onchange_workflow_process_id() self.assertEqual(sale.picking_policy, "one") workflow2 = self.create_full_automatic(override={"picking_policy": "direct"}) sale.workflow_process_id = workflow2.id sale._onchange_workflow_process_id() self.assertEqual(sale.picking_policy, "direct") def test_date_invoice_from_sale_order(self): workflow = self.create_full_automatic() # date_order on sale.order is date + time # invoice_date on account.move is date only last_week_time = fields.Datetime.now() - timedelta(days=7) override = {"date_order": last_week_time} sale = self.create_sale_order(workflow, override=override) sale._onchange_workflow_process_id() self.assertEqual(sale.date_order, last_week_time) self.run_job() self.assertTrue(sale.invoice_ids) invoice = sale.invoice_ids self.assertEqual(invoice.invoice_date, last_week_time.date()) self.assertEqual(invoice.workflow_process_id, sale.workflow_process_id) def test_create_invoice_from_sale_order(self): workflow = self.create_full_automatic() sale = self.create_sale_order(workflow) sale._onchange_workflow_process_id() line = sale.order_line[0] self.assertFalse(workflow.invoice_service_delivery) self.assertEqual(line.qty_delivered_method, "stock_move") self.assertEqual(line.qty_delivered, 0.0) self.assertTrue(sale.delivery_state == "no") self.assertFalse(sale.all_qty_delivered) # `_create_invoices` is already tested in `sale` module. # Make sure this addon works properly in regards to it. mock_path = "odoo.addons.sale.models.sale_order.SaleOrder._create_invoices" with mock.patch(mock_path) as mocked: sale._create_invoices() mocked.assert_called() self.assertEqual(line.qty_delivered, 0.0) workflow.invoice_service_delivery = True line.qty_delivered_method = "manual" with mock.patch(mock_path) as mocked: sale._create_invoices() mocked.assert_called() self.assertEqual(line.qty_delivered, 1.0) sale.action_confirm() sale.action_force_delivery_state() self.assertTrue(sale.delivery_state == "done") self.assertTrue(sale.all_qty_delivered) def test_invoice_from_picking_with_service_product(self): workflow = self.create_full_automatic() product_service = self.env["product.product"].create( { "name": "Remodeling Service", "categ_id": self.env.ref("product.product_category_3").id, "standard_price": 40.0, "list_price": 90.0, "type": "service", "uom_id": self.env.ref("uom.product_uom_hour").id, "uom_po_id": self.env.ref("uom.product_uom_hour").id, "description": "Example of product to invoice on order", "default_code": "PRE-PAID", "invoice_policy": "order", } ) product_uom_hour = self.env.ref("uom.product_uom_hour") override = { "order_line": [ ( 0, 0, { "name": "Prepaid Consulting", "product_id": product_service.id, "product_uom_qty": 1, "product_uom": product_uom_hour.id, }, ) ] } sale = self.create_sale_order(workflow, override=override) sale._onchange_workflow_process_id() self.run_job() self.assertFalse(sale.picking_ids) self.assertTrue(sale.invoice_ids) invoice = sale.invoice_ids self.assertEqual(invoice.workflow_process_id, sale.workflow_process_id) def test_journal_on_invoice(self): sale_journal = self.env["account.journal"].search( [("type", "=", "sale")], limit=1 ) new_sale_journal = self.env["account.journal"].create( {"name": "TTSA", "code": "TTSA", "type": "sale"} ) workflow = self.create_full_automatic() sale = self.create_sale_order(workflow) sale._onchange_workflow_process_id() self.run_job() self.assertTrue(sale.invoice_ids) invoice = sale.invoice_ids self.assertEqual(invoice.journal_id.id, sale_journal.id) workflow = self.create_full_automatic( override={"property_journal_id": new_sale_journal.id} ) sale = self.create_sale_order(workflow) sale._onchange_workflow_process_id() self.run_job() self.assertTrue(sale.invoice_ids) invoice = sale.invoice_ids self.assertEqual(invoice.journal_id.id, new_sale_journal.id) def test_automatic_sale_order_confirmation_mail(self): workflow = self.create_full_automatic() workflow.send_order_confirmation_mail = True sale = self.create_sale_order(workflow) sale._onchange_workflow_process_id() previous_message_ids = sale.message_ids self.run_job() self.assertEqual(sale.state, "sale") new_messages = self.env["mail.message"].search( [ ("id", "in", sale.message_ids.ids), ("id", "not in", previous_message_ids.ids), ] ) self.assertTrue( new_messages.filtered( lambda x: x.subtype_id == self.env.ref("mail.mt_comment") ) )
39.774725
7,239
2,710
py
PYTHON
15.0
# Copyright 2014 Camptocamp SA (author: Guewen Baconnier) # Copyright 2020 Camptocamp SA (author: Simone Orsi) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase class TestCommon(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) class TestAutomaticWorkflowMixin(object): def create_sale_order(self, workflow, override=None): sale_obj = self.env["sale.order"] partner_values = {"name": "Imperator Caius Julius Caesar Divus"} partner = self.env["res.partner"].create(partner_values) product_values = {"name": "Bread", "list_price": 5, "type": "product"} product = self.env["product.product"].create(product_values) self.product_uom_unit = self.env.ref("uom.product_uom_unit") values = { "partner_id": partner.id, "order_line": [ ( 0, 0, { "name": product.name, "product_id": product.id, "product_uom": self.product_uom_unit.id, "price_unit": product.list_price, "product_uom_qty": 1, }, ) ], "workflow_process_id": workflow.id, } if override: values.update(override) order = sale_obj.create(values) # Create inventory for line in order.order_line: if line.product_id.type == "product": inventory = self.env["stock.quant"].create( { "product_id": line.product_id.id, "location_id": self.env.ref("stock.stock_location_stock").id, "inventory_quantity": line.product_uom_qty, } ) inventory._apply_inventory() return order def create_full_automatic(self, override=None): workflow_obj = self.env["sale.workflow.process"] values = workflow_obj.create( { "name": "Full Automatic", "picking_policy": "one", "validate_order": True, "validate_picking": True, "create_invoice": True, "validate_invoice": True, "invoice_date_is_order_date": True, } ) if override: values.update(override) return values def run_job(self): self.env["automatic.workflow.job"].run()
35.657895
2,710
7,520
py
PYTHON
15.0
# Copyright 2017 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests import tagged from .common import TestCommon @tagged("post_install", "-at_install") class TestMultiCompany(TestCommon): def setUp(self): super().setUp() @classmethod def create_company(cls, values): return cls.env["res.company"].create(values) @classmethod def create_product(cls, values): values.update({"type": "consu", "invoice_policy": "order"}) product_template = cls.env["product.template"].create(values) return product_template.product_variant_id @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env( context=dict( cls.env.context, tracking_disable=True, # Compatibility with sale_automatic_workflow_job: even if # the module is installed, ensure we don't delay a job. # Thus, we test the usual flow. _job_force_sync=True, ) ) coa = cls.env.user.company_id.chart_template_id cls.company_fr = cls.create_company( { "name": "French company", "currency_id": cls.env.ref("base.EUR").id, "country_id": cls.env.ref("base.fr").id, } ) cls.company_ch = cls.create_company( { "name": "Swiss company", "currency_id": cls.env.ref("base.CHF").id, "country_id": cls.env.ref("base.ch").id, } ) cls.company_be = cls.create_company( { "name": "Belgian company", "currency_id": cls.env.ref("base.EUR").id, "country_id": cls.env.ref("base.be").id, } ) cls.company_fr_daughter = cls.create_company( { "name": "French company daughter", "currency_id": cls.env.ref("base.EUR").id, "country_id": cls.env.ref("base.fr").id, } ) cls.env.user.company_ids |= cls.company_fr cls.env.user.company_ids |= cls.company_ch cls.env.user.company_ids |= cls.company_be cls.env.user.company_ids |= cls.company_fr_daughter cls.env.user.company_id = cls.company_fr.id coa.try_loading(company=cls.env.user.company_id) cls.customer_fr = ( cls.env["res.partner"] .with_context(default_company_id=cls.company_fr.id) .create({"name": "Customer FR"}) ) cls.product_fr = cls.create_product({"name": "Evian bottle", "list_price": 2.0}) cls.env.user.company_id = cls.company_ch.id coa.try_loading(company=cls.env.user.company_id) cls.customer_ch = cls.env["res.partner"].create({"name": "Customer CH"}) cls.product_ch = cls.create_product( {"name": "Henniez bottle", "list_price": 3.0} ) cls.env.user.company_id = cls.company_be.id coa.try_loading(company=cls.env.user.company_id) cls.customer_be = cls.env["res.partner"].create({"name": "Customer BE"}) cls.product_be = ( cls.env["product.template"] .create( { "name": "SPA bottle", "list_price": 1.5, "type": "consu", "invoice_policy": "order", } ) .product_variant_id ) cls.env.user.company_id = cls.company_fr_daughter.id coa.try_loading(company=cls.env.user.company_id) cls.customer_fr_daughter = cls.env["res.partner"].create( {"name": "Customer FR Daughter"} ) cls.product_fr_daughter = cls.create_product( {"name": "Contrex bottle", "list_price": 1.5} ) cls.auto_wkf = cls.env.ref("sale_automatic_workflow.automatic_validation") cls.auto_wkf.validate_picking = True cls.env.user.company_id = cls.env.ref("base.main_company") def create_auto_wkf_order(self, company, customer, product, qty): # We need to change to the proper company # to pick up correct company dependent fields current_company = self.env.user.company_id self.env.user.company_id = company SaleOrder = self.env["sale.order"] warehouse = self.env["stock.warehouse"].search( [("company_id", "=", company.id)], limit=1 ) self.product_uom_unit = self.env.ref("uom.product_uom_unit") order = SaleOrder.create( { "partner_id": customer.id, "company_id": company.id, "warehouse_id": warehouse.id, "workflow_process_id": self.auto_wkf.id, "order_line": [ ( 0, 0, { "name": product.name, "product_id": product.id, "price_unit": product.list_price, "product_uom_qty": qty, "product_uom": self.product_uom_unit.id, }, ) ], } ) order._onchange_workflow_process_id() self.env.user.company_id = current_company return order def test_sale_order_multicompany(self): self.env.user.company_id = self.env.ref("base.main_company") order_fr = self.create_auto_wkf_order( self.company_fr, self.customer_fr, self.product_fr, 5 ) order_ch = self.create_auto_wkf_order( self.company_ch, self.customer_ch, self.product_ch, 10 ) order_be = self.create_auto_wkf_order( self.company_be, self.customer_be, self.product_be, 10 ) order_fr_daughter = self.create_auto_wkf_order( self.company_fr_daughter, self.customer_fr_daughter, self.product_fr_daughter, 4, ) self.assertEqual(order_fr.state, "draft") self.assertEqual(order_ch.state, "draft") self.assertEqual(order_be.state, "draft") self.assertEqual(order_fr_daughter.state, "draft") self.env["automatic.workflow.job"].run() self.assertTrue(order_fr.picking_ids) self.assertTrue(order_ch.picking_ids) self.assertTrue(order_be.picking_ids) self.assertEqual(order_fr.picking_ids.state, "done") self.assertEqual(order_ch.picking_ids.state, "done") self.assertEqual(order_be.picking_ids.state, "done") invoice_fr = order_fr.invoice_ids invoice_ch = order_ch.invoice_ids invoice_be = order_be.invoice_ids invoice_fr_daughter = order_fr_daughter.invoice_ids self.assertEqual(invoice_fr.state, "posted") self.assertEqual(invoice_fr.journal_id.company_id, order_fr.company_id) self.assertEqual(invoice_ch.state, "posted") self.assertEqual(invoice_ch.journal_id.company_id, order_ch.company_id) self.assertEqual(invoice_be.state, "posted") self.assertEqual(invoice_be.journal_id.company_id, order_be.company_id) self.assertEqual(invoice_fr_daughter.state, "posted") self.assertEqual( invoice_fr_daughter.journal_id.company_id, order_fr_daughter.company_id )
37.412935
7,520
444
py
PYTHON
15.0
# Copyright 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # Copyright 2013 Camptocamp SA (author: Guewen Baconnier) # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountMove(models.Model): _inherit = "account.move" workflow_process_id = fields.Many2one( comodel_name="sale.workflow.process", string="Sale Workflow Process" )
31.642857
443
2,953
py
PYTHON
15.0
# Copyright 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # Copyright 2013 Camptocamp SA (author: Guewen Baconnier) # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" workflow_process_id = fields.Many2one( comodel_name="sale.workflow.process", string="Automatic Workflow", ondelete="restrict", ) all_qty_delivered = fields.Boolean( compute="_compute_all_qty_delivered", string="All quantities delivered", store=True, ) @api.depends("delivery_state") def _compute_all_qty_delivered(self): for order in self: order.all_qty_delivered = order.delivery_state == "done" def _prepare_invoice(self): invoice_vals = super()._prepare_invoice() workflow = self.workflow_process_id if not workflow: return invoice_vals invoice_vals["workflow_process_id"] = workflow.id if workflow.invoice_date_is_order_date: invoice_vals["invoice_date"] = fields.Date.context_today( self, self.date_order ) if workflow.property_journal_id: invoice_vals["journal_id"] = workflow.property_journal_id.id return invoice_vals @api.onchange("workflow_process_id") def _onchange_workflow_process_id(self): if not self.workflow_process_id: return workflow = self.workflow_process_id if workflow.picking_policy: self.picking_policy = workflow.picking_policy if workflow.team_id: self.team_id = workflow.team_id.id if workflow.warning: warning = {"title": _("Workflow Warning"), "message": workflow.warning} return {"warning": warning} def _create_invoices(self, grouped=False, final=False, date=None): for order in self: if not order.workflow_process_id.invoice_service_delivery: continue for line in order.order_line: if line.qty_delivered_method == "manual" and not line.qty_delivered: line.write({"qty_delivered": line.product_uom_qty}) return super()._create_invoices(grouped=grouped, final=final, date=date) def write(self, vals): if vals.get("state") == "sale" and vals.get("date_order"): sales_keep_order_date = self.filtered( lambda sale: sale.workflow_process_id.invoice_date_is_order_date ) if sales_keep_order_date: new_vals = vals.copy() del new_vals["date_order"] res = super(SaleOrder, sales_keep_order_date).write(new_vals) res |= super(SaleOrder, self - sales_keep_order_date).write(vals) return res return super(SaleOrder, self).write(vals)
39.36
2,952
9,369
py
PYTHON
15.0
# Copyright 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # Copyright 2013 Camptocamp SA (author: Guewen Baconnier) # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from contextlib import contextmanager from odoo import api, fields, models from odoo.tools.safe_eval import safe_eval _logger = logging.getLogger(__name__) @contextmanager def savepoint(cr): """Open a savepoint on the cursor, then yield. Warning: using this method, the exceptions are logged then discarded. """ try: with cr.savepoint(): yield except Exception: _logger.exception("Error during an automatic workflow action.") class AutomaticWorkflowJob(models.Model): """Scheduler that will play automatically the validation of invoices, pickings...""" _name = "automatic.workflow.job" _description = ( "Scheduler that will play automatically the validation of" " invoices, pickings..." ) def _do_validate_sale_order(self, sale, domain_filter): """Validate a sales order, filter ensure no duplication""" if not self.env["sale.order"].search_count( [("id", "=", sale.id)] + domain_filter ): return "{} {} job bypassed".format(sale.display_name, sale) sale.action_confirm() return "{} {} confirmed successfully".format(sale.display_name, sale) def _do_send_order_confirmation_mail(self, sale): """Send order confirmation mail, while filtering to make sure the order is confirmed with _do_validate_sale_order() function""" if not self.env["sale.order"].search_count( [("id", "=", sale.id), ("state", "=", "sale")] ): return "{} {} job bypassed".format(sale.display_name, sale) if sale.user_id: sale = sale.with_user(sale.user_id) sale._send_order_confirmation_mail() return "{} {} send order confirmation mail successfully".format( sale.display_name, sale ) @api.model def _validate_sale_orders(self, order_filter): sale_obj = self.env["sale.order"] sales = sale_obj.search(order_filter) _logger.debug("Sale Orders to validate: %s", sales.ids) for sale in sales: with savepoint(self.env.cr): self._do_validate_sale_order( sale.with_company(sale.company_id), order_filter ) if self.env.context.get("send_order_confirmation_mail"): self._do_send_order_confirmation_mail(sale) def _do_create_invoice(self, sale, domain_filter): """Create an invoice for a sales order, filter ensure no duplication""" if not self.env["sale.order"].search_count( [("id", "=", sale.id)] + domain_filter ): return "{} {} job bypassed".format(sale.display_name, sale) payment = self.env["sale.advance.payment.inv"].create({}) payment.with_context( active_ids=sale.ids, active_model="sale.order" ).create_invoices() return "{} {} create invoice successfully".format(sale.display_name, sale) @api.model def _create_invoices(self, create_filter): sale_obj = self.env["sale.order"] sales = sale_obj.search(create_filter) _logger.debug("Sale Orders to create Invoice: %s", sales.ids) for sale in sales: with savepoint(self.env.cr): self._do_create_invoice( sale.with_company(sale.company_id), create_filter ) def _do_validate_invoice(self, invoice, domain_filter): """Validate an invoice, filter ensure no duplication""" if not self.env["account.move"].search_count( [("id", "=", invoice.id)] + domain_filter ): return "{} {} job bypassed".format(invoice.display_name, invoice) invoice.with_company(invoice.company_id).action_post() return "{} {} validate invoice successfully".format( invoice.display_name, invoice ) @api.model def _validate_invoices(self, validate_invoice_filter): move_obj = self.env["account.move"] invoices = move_obj.search(validate_invoice_filter) _logger.debug("Invoices to validate: %s", invoices.ids) for invoice in invoices: with savepoint(self.env.cr): self._do_validate_invoice( invoice.with_company(invoice.company_id), validate_invoice_filter ) def _do_validate_picking(self, picking, domain_filter): """Validate a stock.picking, filter ensure no duplication""" if not self.env["stock.picking"].search_count( [("id", "=", picking.id)] + domain_filter ): return "{} {} job bypassed".format(picking.display_name, picking) picking.validate_picking() return "{} {} validate picking successfully".format( picking.display_name, picking ) @api.model def _validate_pickings(self, picking_filter): picking_obj = self.env["stock.picking"] pickings = picking_obj.search(picking_filter) _logger.debug("Pickings to validate: %s", pickings.ids) for picking in pickings: with savepoint(self.env.cr): self._do_validate_picking(picking, picking_filter) def _do_sale_done(self, sale, domain_filter): """Set a sales order to done, filter ensure no duplication""" if not self.env["sale.order"].search_count( [("id", "=", sale.id)] + domain_filter ): return "{} {} job bypassed".format(sale.display_name, sale) sale.action_done() return "{} {} set done successfully".format(sale.display_name, sale) @api.model def _sale_done(self, sale_done_filter): sale_obj = self.env["sale.order"] sales = sale_obj.search(sale_done_filter) _logger.debug("Sale Orders to done: %s", sales.ids) for sale in sales: with savepoint(self.env.cr): self._do_sale_done(sale.with_company(sale.company_id), sale_done_filter) def _prepare_dict_account_payment(self, invoice): partner_type = ( invoice.move_type in ("out_invoice", "out_refund") and "customer" or "supplier" ) return { "reconciled_invoice_ids": [(6, 0, invoice.ids)], "amount": invoice.amount_residual, "partner_id": invoice.partner_id.id, "partner_type": partner_type, "date": fields.Date.context_today(self), } @api.model def _register_payments(self, payment_filter): invoice_obj = self.env["account.move"] invoices = invoice_obj.search(payment_filter) _logger.debug("Invoices to Register Payment: %s", invoices.ids) for invoice in invoices: with savepoint(self.env.cr): self._register_payment_invoice(invoice) return def _register_payment_invoice(self, invoice): payment = self.env["account.payment"].create( self._prepare_dict_account_payment(invoice) ) payment.action_post() domain = [ ("account_internal_type", "in", ("receivable", "payable")), ("reconciled", "=", False), ] payment_lines = payment.line_ids.filtered_domain(domain) lines = invoice.line_ids for account in payment_lines.account_id: (payment_lines + lines).filtered_domain( [("account_id", "=", account.id), ("reconciled", "=", False)] ).reconcile() @api.model def run_with_workflow(self, sale_workflow): workflow_domain = [("workflow_process_id", "=", sale_workflow.id)] if sale_workflow.validate_order: self.with_context( send_order_confirmation_mail=sale_workflow.send_order_confirmation_mail )._validate_sale_orders( safe_eval(sale_workflow.order_filter_id.domain) + workflow_domain ) if sale_workflow.validate_picking: self._validate_pickings( safe_eval(sale_workflow.picking_filter_id.domain) + workflow_domain ) if sale_workflow.create_invoice: self._create_invoices( safe_eval(sale_workflow.create_invoice_filter_id.domain) + workflow_domain ) if sale_workflow.validate_invoice: self._validate_invoices( safe_eval(sale_workflow.validate_invoice_filter_id.domain) + workflow_domain ) if sale_workflow.sale_done: self._sale_done( safe_eval(sale_workflow.sale_done_filter_id.domain) + workflow_domain ) if sale_workflow.register_payment: self._register_payments( safe_eval(sale_workflow.payment_filter_id.domain) + workflow_domain ) @api.model def run(self): """Must be called from ir.cron""" sale_workflow_process = self.env["sale.workflow.process"] for sale_workflow in sale_workflow_process.search([]): self.run_with_workflow(sale_workflow) return True
39.527426
9,368
544
py
PYTHON
15.0
# Copyright 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # Copyright 2013 Camptocamp SA (author: Guewen Baconnier) # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockMove(models.Model): _inherit = "stock.move" def _get_new_picking_values(self): values = super()._get_new_picking_values() sale = self.group_id.sale_id if sale: values["workflow_process_id"] = sale.workflow_process_id.id return values
31.941176
543
1,335
py
PYTHON
15.0
# Copyright 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # Copyright 2013 Camptocamp SA (author: Guewen Baconnier) # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models from odoo.tools import float_compare class StockPicking(models.Model): _inherit = "stock.picking" workflow_process_id = fields.Many2one( comodel_name="sale.workflow.process", string="Sale Workflow Process" ) def validate_picking(self): """Set quantities automatically and validate the pickings.""" for picking in self: picking.action_assign() for move in picking.move_lines.filtered( lambda m: m.state not in ["done", "cancel"] ): rounding = move.product_id.uom_id.rounding if ( float_compare( move.quantity_done, move.product_qty, precision_rounding=rounding, ) == -1 ): for move_line in move.move_line_ids: move_line.qty_done = move_line.product_uom_qty picking.with_context(skip_immediate=True, skip_sms=True).button_validate() return True
37.055556
1,334
4,855
py
PYTHON
15.0
# Copyright 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # Copyright 2013 Camptocamp SA (author: Guewen Baconnier) # Copyright 2016 Sodexis # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models class SaleWorkflowProcess(models.Model): """A workflow process is the setup of the automation of a sales order. Each sales order can be linked to a workflow process. Then, the options of the workflow will change how the sales order behave, and how it is automatized. A workflow process may be linked with a Sales payment method, so each time a payment method is used, the workflow will be applied. """ _name = "sale.workflow.process" _description = "Sale Workflow Process" @api.model def _default_filter(self, xmlid): record = self.env.ref(xmlid, raise_if_not_found=False) if record: return record return self.env["ir.filters"].browse() name = fields.Char() picking_policy = fields.Selection( selection=[ ("direct", "Deliver each product when available"), ("one", "Deliver all products at once"), ], string="Shipping Policy", default="direct", ) validate_order = fields.Boolean() send_order_confirmation_mail = fields.Boolean( help="When checked, after order confirmation, a confirmation email will be " "sent (if not already sent).", ) order_filter_domain = fields.Text( string="Order Filter Domain", related="order_filter_id.domain" ) create_invoice = fields.Boolean() create_invoice_filter_domain = fields.Text( string="Create Invoice Filter Domain", related="create_invoice_filter_id.domain" ) validate_invoice = fields.Boolean() validate_invoice_filter_domain = fields.Text( string="Validate Invoice Filter Domain", related="validate_invoice_filter_id.domain", ) validate_picking = fields.Boolean(string="Confirm and Transfer Picking") picking_filter_domain = fields.Text( string="Picking Filter Domain", related="picking_filter_id.domain" ) invoice_date_is_order_date = fields.Boolean( string="Force Invoice Date", help="When checked, the invoice date will be " "the same than the order's date", ) invoice_service_delivery = fields.Boolean( string="Invoice Service on delivery", help="If this box is checked, when the first invoice is created " "The service sale order lines will be included and will be " "marked as delivered", ) sale_done = fields.Boolean() sale_done_filter_domain = fields.Text( string="Sale Done Filter Domain", related="sale_done_filter_id.domain" ) warning = fields.Text( "Warning Message", translate=True, help="If set, displays the message when an user" "selects the process on a sale order", ) team_id = fields.Many2one(comodel_name="crm.team", string="Sales Team") property_journal_id = fields.Many2one( comodel_name="account.journal", company_dependent=True, string="Sales Journal", help="Set default journal to use on invoice", ) order_filter_id = fields.Many2one( "ir.filters", default=lambda self: self._default_filter( "sale_automatic_workflow.automatic_workflow_order_filter" ), ) picking_filter_id = fields.Many2one( "ir.filters", string="Picking Filter", default=lambda self: self._default_filter( "sale_automatic_workflow.automatic_workflow_picking_filter" ), ) create_invoice_filter_id = fields.Many2one( "ir.filters", string="Create Invoice Filter", default=lambda self: self._default_filter( "sale_automatic_workflow.automatic_workflow_create_invoice_filter" ), ) validate_invoice_filter_id = fields.Many2one( "ir.filters", string="Validate Invoice Filter", default=lambda self: self._default_filter( "sale_automatic_workflow." "automatic_workflow_validate_invoice_filter" ), ) sale_done_filter_id = fields.Many2one( "ir.filters", string="Sale Done Filter", default=lambda self: self._default_filter( "sale_automatic_workflow.automatic_workflow_sale_done_filter" ), ) payment_filter_id = fields.Many2one( comodel_name="ir.filters", string="Register Payment Invoice Filter", default=lambda self: self._default_filter( "sale_automatic_workflow.automatic_workflow_payment_filter" ), ) register_payment = fields.Boolean() payment_filter_domain = fields.Text( related="payment_filter_id.domain", )
36.772727
4,854
655
py
PYTHON
15.0
# Copyright 2015 Omar Castiñeira, Comunitea Servicios Tecnológicos S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Advance Payment", "version": "15.0.1.0.3", "author": "Comunitea, Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "category": "Sales", "license": "AGPL-3", "summary": "Allow to add advance payments on sales and then use them on invoices", "depends": ["sale"], "data": [ "wizard/sale_advance_payment_wzd_view.xml", "views/sale_view.xml", "security/ir.model.access.csv", ], "installable": True, }
34.368421
653
13,823
py
PYTHON
15.0
# Copyright (C) 2021 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html) import json from odoo import fields from odoo.exceptions import ValidationError from odoo.tests import common class TestSaleAdvancePayment(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() # Partners cls.res_partner_1 = cls.env["res.partner"].create({"name": "Wood Corner"}) cls.res_partner_address_1 = cls.env["res.partner"].create( {"name": "Willie Burke", "parent_id": cls.res_partner_1.id} ) cls.res_partner_2 = cls.env["res.partner"].create({"name": "Partner 12"}) # Products cls.product_1 = cls.env["product.product"].create( {"name": "Desk Combination", "invoice_policy": "order"} ) cls.product_2 = cls.env["product.product"].create( {"name": "Conference Chair", "invoice_policy": "order"} ) cls.product_3 = cls.env["product.product"].create( {"name": "Repair Services", "invoice_policy": "order"} ) cls.tax = cls.env["account.tax"].create( { "name": "Tax 15", "type_tax_use": "sale", "amount": 20, } ) # Sale Order cls.sale_order_1 = cls.env["sale.order"].create( {"partner_id": cls.res_partner_1.id} ) cls.order_line_1 = cls.env["sale.order.line"].create( { "order_id": cls.sale_order_1.id, "product_id": cls.product_1.id, "product_uom": cls.product_1.uom_id.id, "product_uom_qty": 10.0, "price_unit": 100.0, "tax_id": cls.tax, } ) cls.order_line_2 = cls.env["sale.order.line"].create( { "order_id": cls.sale_order_1.id, "product_id": cls.product_2.id, "product_uom": cls.product_2.uom_id.id, "product_uom_qty": 25.0, "price_unit": 40.0, "tax_id": cls.tax, } ) cls.order_line_3 = cls.env["sale.order.line"].create( { "order_id": cls.sale_order_1.id, "product_id": cls.product_3.id, "product_uom": cls.product_3.uom_id.id, "product_uom_qty": 20.0, "price_unit": 50.0, "tax_id": cls.tax, } ) cls.active_euro = False cls.currency_euro = ( cls.env["res.currency"] .with_context(active_test=False) .search([("name", "=", "EUR")]) ) # active euro currency if inactive for test if not cls.currency_euro.active: cls.currency_euro.active = True cls.active_euro = True cls.currency_usd = cls.env["res.currency"].search([("name", "=", "USD")]) cls.currency_rate = cls.env["res.currency.rate"].search( [ ("currency_id", "=", cls.currency_usd.id), ("name", "=", fields.Date.today()), ] ) if cls.currency_rate: cls.currency_rate.write({"rate": 1.20}) else: cls.currency_rate = cls.env["res.currency.rate"].create( { "rate": 1.20, "currency_id": cls.currency_usd.id, "name": fields.Date.today(), } ) cls.journal_eur_bank = cls.env["account.journal"].create( { "name": "Journal Euro Bank", "type": "bank", "code": "111", "currency_id": cls.currency_euro.id, } ) cls.journal_usd_bank = cls.env["account.journal"].create( { "name": "Journal USD Bank", "type": "bank", "code": "222", "currency_id": cls.currency_usd.id, } ) cls.journal_eur_cash = cls.env["account.journal"].create( { "name": "Journal Euro Cash", "type": "cash", "code": "333", "currency_id": cls.currency_euro.id, } ) cls.journal_usd_cash = cls.env["account.journal"].create( { "name": "Journal USD Cash", "type": "cash", "code": "444", "currency_id": cls.currency_usd.id, } ) def test_01_sale_advance_payment(self): self.assertEqual( self.sale_order_1.amount_residual, 3600, ) self.assertEqual( self.sale_order_1.amount_residual, self.sale_order_1.amount_total, "Amounts should match", ) context_payment = { "active_ids": [self.sale_order_1.id], "active_id": self.sale_order_1.id, } # Check residual > advance payment and the comparison takes # into account the currency. 3001*1.2 > 3600 with self.assertRaises(ValidationError): advance_payment_0 = ( self.env["account.voucher.wizard"] .with_context(**context_payment) .create( { "journal_id": self.journal_eur_bank.id, "payment_type": "inbound", "amount_advance": 3001, "order_id": self.sale_order_1.id, } ) ) advance_payment_0.make_advance_payment() # Create Advance Payment 1 - EUR - bank advance_payment_1 = ( self.env["account.voucher.wizard"] .with_context(**context_payment) .create( { "journal_id": self.journal_eur_bank.id, "payment_type": "inbound", "amount_advance": 100, "order_id": self.sale_order_1.id, } ) ) advance_payment_1.make_advance_payment() self.assertEqual(self.sale_order_1.amount_residual, 3480) # Create Advance Payment 2 - USD - cash advance_payment_2 = ( self.env["account.voucher.wizard"] .with_context(**context_payment) .create( { "journal_id": self.journal_usd_cash.id, "payment_type": "inbound", "amount_advance": 200, "order_id": self.sale_order_1.id, } ) ) advance_payment_2.make_advance_payment() self.assertEqual(self.sale_order_1.amount_residual, 3280) # Confirm Sale Order self.sale_order_1.action_confirm() # Create Advance Payment 3 - EUR - cash advance_payment_3 = ( self.env["account.voucher.wizard"] .with_context(**context_payment) .create( { "journal_id": self.journal_eur_cash.id, "payment_type": "inbound", "amount_advance": 250, "order_id": self.sale_order_1.id, } ) ) advance_payment_3.make_advance_payment() self.assertEqual(self.sale_order_1.amount_residual, 2980) # Create Advance Payment 4 - USD - bank advance_payment_4 = ( self.env["account.voucher.wizard"] .with_context(**context_payment) .create( { "journal_id": self.journal_usd_bank.id, "payment_type": "inbound", "amount_advance": 400, "order_id": self.sale_order_1.id, } ) ) advance_payment_4.make_advance_payment() self.assertEqual(self.sale_order_1.amount_residual, 2580) # Check that the outbound amount is not greated than the # amount paid in advanced (in EUR) with self.assertRaises(ValidationError): advance_payment_5 = ( self.env["account.voucher.wizard"] .with_context(**context_payment) .create( { "journal_id": self.journal_eur_bank.id, "payment_type": "outbound", "amount_advance": 850.01, "order_id": self.sale_order_1.id, } ) ) advance_payment_5.make_advance_payment() # Confirm Sale Order self.sale_order_1.action_confirm() # Create Invoice invoice = self.sale_order_1._create_invoices() invoice.action_post() # Compare payments rate = self.currency_rate.rate payment_list = [100 * rate, 200, 250 * rate, 400] payments = json.loads(invoice.invoice_outstanding_credits_debits_widget) result = [d["amount"] for d in payments["content"]] self.assertEqual(set(payment_list), set(result)) def test_02_residual_amount_with_invoice(self): self.assertEqual( self.sale_order_1.amount_residual, 3600, ) self.assertEqual( self.sale_order_1.amount_residual, self.sale_order_1.amount_total, ) # Create Advance Payment 1 - EUR - bank context_payment = { "active_ids": [self.sale_order_1.id], "active_id": self.sale_order_1.id, } # Create Advance Payment 2 - USD - cash advance_payment_2 = ( self.env["account.voucher.wizard"] .with_context(**context_payment) .create( { "journal_id": self.journal_usd_cash.id, "payment_type": "inbound", "amount_advance": 200, "order_id": self.sale_order_1.id, } ) ) advance_payment_2.make_advance_payment() pre_payment = self.sale_order_1.account_payment_ids self.assertEqual(len(pre_payment), 1) self.assertEqual(self.sale_order_1.amount_residual, 3400) # generate invoice, pay invoice, check amount residual. self.sale_order_1.action_confirm() self.assertEqual(self.sale_order_1.invoice_status, "to invoice") self.sale_order_1._create_invoices() self.assertEqual(self.sale_order_1.invoice_status, "invoiced") self.assertEqual(self.sale_order_1.amount_residual, 3400) invoice = self.sale_order_1.invoice_ids invoice.invoice_date = fields.Date.today() invoice.action_post() active_ids = invoice.ids self.env["account.payment.register"].with_context( active_model="account.move", active_ids=active_ids ).create( { "amount": 1200.0, "group_payment": True, "payment_difference_handling": "open", } )._create_payments() self.assertEqual(self.sale_order_1.amount_residual, 2200) def test_03_residual_amount_big_pre_payment(self): self.assertEqual( self.sale_order_1.amount_residual, 3600, ) self.assertEqual( self.sale_order_1.amount_residual, self.sale_order_1.amount_total, ) # Create Advance Payment 1 - EUR - bank context_payment = { "active_ids": [self.sale_order_1.id], "active_id": self.sale_order_1.id, } # Create Advance Payment 2 - USD - cash advance_payment_2 = ( self.env["account.voucher.wizard"] .with_context(**context_payment) .create( { "journal_id": self.journal_usd_cash.id, "payment_type": "inbound", "amount_advance": 2000, "order_id": self.sale_order_1.id, } ) ) advance_payment_2.make_advance_payment() pre_payment = self.sale_order_1.account_payment_ids self.assertEqual(len(pre_payment), 1) self.assertEqual(self.sale_order_1.amount_residual, 1600) # generate a partial invoice, reconcile with pre payment, check amount residual. self.sale_order_1.action_confirm() self.assertEqual(self.sale_order_1.invoice_status, "to invoice") # Adjust invoice_policy method to then do a partial invoice with a total amount # smaller than the pre-payment. self.product_1.invoice_policy = "delivery" self.order_line_1.qty_delivered = 10.0 self.assertEqual(self.order_line_1.qty_to_invoice, 10.0) self.product_2.invoice_policy = "delivery" self.order_line_2.qty_delivered = 0.0 self.assertEqual(self.order_line_2.qty_to_invoice, 0.0) self.product_3.invoice_policy = "delivery" self.order_line_3.qty_delivered = 0.0 self.assertEqual(self.order_line_3.qty_to_invoice, 0.0) self.sale_order_1._create_invoices() self.assertEqual(self.sale_order_1.invoice_status, "no") self.assertEqual(self.sale_order_1.amount_residual, 1600) invoice = self.sale_order_1.invoice_ids invoice.invoice_date = fields.Date.today() invoice.action_post() self.assertEqual(invoice.amount_total, 1200) self.assertEqual(invoice.amount_residual, 0.0) self.assertEqual(self.sale_order_1.amount_residual, 1600) self.assertEqual(invoice.amount_residual, 0)
36.472296
13,823
5,834
py
PYTHON
15.0
# Copyright 2017 Omar Castiñeira, Comunitea Servicios Tecnológicos S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, exceptions, fields, models from odoo.exceptions import UserError from odoo.tools import float_compare class AccountVoucherWizard(models.TransientModel): _name = "account.voucher.wizard" _description = "Account Voucher Wizard" order_id = fields.Many2one("sale.order", required=True) journal_id = fields.Many2one( "account.journal", "Journal", required=True, domain=[("type", "in", ("bank", "cash"))], ) journal_currency_id = fields.Many2one( "res.currency", "Journal Currency", store=True, readonly=False, compute="_compute_get_journal_currency", ) currency_id = fields.Many2one("res.currency", "Currency", readonly=True) amount_total = fields.Monetary(readonly=True) amount_advance = fields.Monetary( "Amount advanced", required=True, currency_field="journal_currency_id" ) date = fields.Date(required=True, default=fields.Date.context_today) currency_amount = fields.Monetary( "Curr. amount", readonly=True, currency_field="currency_id" ) payment_ref = fields.Char("Ref.") payment_type = fields.Selection( [("inbound", "Inbound"), ("outbound", "Outbound")], default="inbound", required=True, ) @api.depends("journal_id") def _compute_get_journal_currency(self): for wzd in self: wzd.journal_currency_id = ( wzd.journal_id.currency_id.id or wzd.journal_id.company_id.currency_id.id ) @api.constrains("amount_advance") def check_amount(self): if self.amount_advance <= 0: raise exceptions.ValidationError(_("Amount of advance must be positive.")) if self.env.context.get("active_id", False): self.onchange_date() if self.payment_type == "inbound": if ( float_compare( self.currency_amount, self.order_id.amount_residual, precision_digits=2, ) > 0 ): raise exceptions.ValidationError( _( "Inbound amount of advance is greater than residual amount on sale" ) ) else: paid_in_advanced = self.order_id.amount_total - self.amount_total if ( float_compare( self.currency_amount, paid_in_advanced, precision_digits=2, ) > 0 ): raise exceptions.ValidationError( _( "Outbound amount of advance is greater than the " "advanced paid amount" ) ) @api.model def default_get(self, fields_list): res = super().default_get(fields_list) sale_ids = self.env.context.get("active_ids", []) if not sale_ids: return res sale_id = fields.first(sale_ids) sale = self.env["sale.order"].browse(sale_id) if "amount_total" in fields_list: res.update( { "order_id": sale.id, "amount_total": sale.amount_residual, "currency_id": sale.pricelist_id.currency_id.id, } ) return res @api.onchange("journal_id", "date", "amount_advance") def onchange_date(self): if self.journal_currency_id != self.currency_id: amount_advance = self.journal_currency_id._convert( self.amount_advance, self.currency_id, self.order_id.company_id, self.date or fields.Date.today(), ) else: amount_advance = self.amount_advance self.currency_amount = amount_advance def _prepare_payment_vals(self, sale): partner_id = sale.partner_invoice_id.commercial_partner_id.id if self.amount_advance < 0.0: raise UserError( _( "The amount to advance must always be positive. " "Please use the payment type to indicate if this " "is an inbound or an outbound payment." ) ) return { "date": self.date, "amount": self.amount_advance, "payment_type": self.payment_type, "partner_type": "customer", "ref": self.payment_ref or sale.name, "journal_id": self.journal_id.id, "currency_id": self.journal_currency_id.id, "partner_id": partner_id, "payment_method_id": self.env.ref( "account.account_payment_method_manual_in" ).id, } def make_advance_payment(self): """Create customer paylines and validates the payment""" self.ensure_one() payment_obj = self.env["account.payment"] sale_obj = self.env["sale.order"] sale_ids = self.env.context.get("active_ids", []) if sale_ids: sale_id = fields.first(sale_ids) sale = sale_obj.browse(sale_id) payment_vals = self._prepare_payment_vals(sale) payment = payment_obj.create(payment_vals) sale.account_payment_ids |= payment payment.action_post() return { "type": "ir.actions.act_window_close", }
36
5,832
950
py
PYTHON
15.0
# Copyright 2022 Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import json from odoo import models class AccountMove(models.Model): _inherit = "account.move" def action_post(self): # Automatic reconciliation of payment when invoice confirmed. res = super(AccountMove, self).action_post() sale_order = self.mapped("line_ids.sale_line_ids.order_id") if ( sale_order and json.loads(self.invoice_outstanding_credits_debits_widget) is not False ): json_invoice_outstanding_data = json.loads( self.invoice_outstanding_credits_debits_widget ).get("content", []) for data in json_invoice_outstanding_data: if data.get("move_id") in sale_order.account_payment_ids.move_id.ids: self.js_assign_outstanding_line(line_id=data.get("id")) return res
36.538462
950
366
py
PYTHON
15.0
# Copyright 2017 Omar Castiñeira, Comunitea Servicios Tecnológicos S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountPayment(models.Model): _inherit = "account.payment" sale_id = fields.Many2one( "sale.order", "Sale", readonly=True, states={"draft": [("readonly", False)]} )
28
364
3,696
py
PYTHON
15.0
# Copyright 2017 Omar Castiñeira, Comunitea Servicios Tecnológicos S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.tools import float_compare class SaleOrder(models.Model): _inherit = "sale.order" account_payment_ids = fields.One2many( "account.payment", "sale_id", string="Pay sale advanced", readonly=True ) amount_residual = fields.Float( "Residual amount", readonly=True, compute="_compute_advance_payment", store=True, ) payment_line_ids = fields.Many2many( "account.move.line", string="Payment move lines", compute="_compute_advance_payment", store=True, ) advance_payment_status = fields.Selection( selection=[ ("not_paid", "Not Paid"), ("paid", "Paid"), ("partial", "Partially Paid"), ], store=True, readonly=True, copy=False, tracking=True, compute="_compute_advance_payment", ) @api.depends( "currency_id", "company_id", "amount_total", "account_payment_ids", "account_payment_ids.state", "account_payment_ids.move_id", "account_payment_ids.move_id.line_ids", "account_payment_ids.move_id.line_ids.date", "account_payment_ids.move_id.line_ids.debit", "account_payment_ids.move_id.line_ids.credit", "account_payment_ids.move_id.line_ids.currency_id", "account_payment_ids.move_id.line_ids.amount_currency", "invoice_ids.amount_residual", ) def _compute_advance_payment(self): for order in self: mls = order.account_payment_ids.mapped("move_id.line_ids").filtered( lambda x: x.account_id.internal_type == "receivable" and x.parent_state == "posted" ) advance_amount = 0.0 for line in mls: line_currency = line.currency_id or line.company_id.currency_id # Exclude reconciled pre-payments amount because once reconciled # the pre-payment will reduce invoice residual amount like any # other payment. line_amount = ( line.amount_residual_currency if line.currency_id else line.amount_residual ) line_amount *= -1 if line_currency != order.currency_id: advance_amount += line.currency_id._convert( line_amount, order.currency_id, order.company_id, line.date or fields.Date.today(), ) else: advance_amount += line_amount # Consider payments in related invoices. invoice_paid_amount = 0.0 for inv in order.invoice_ids: invoice_paid_amount += inv.amount_total - inv.amount_residual amount_residual = order.amount_total - advance_amount - invoice_paid_amount payment_state = "not_paid" if mls: has_due_amount = float_compare( amount_residual, 0.0, precision_rounding=order.currency_id.rounding ) if has_due_amount <= 0: payment_state = "paid" elif has_due_amount > 0: payment_state = "partial" order.payment_line_ids = mls order.amount_residual = amount_residual order.advance_payment_status = payment_state
37.693878
3,694
565
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Sale Order Qty change no recompute", "summary": "Prevent recompute if only quantity has changed in sale order line", "version": "15.0.2.0.0", "category": "Sale Workflow", "website": "https://github.com/OCA/sale-workflow", "author": "Tecnativa, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["sale"], "maintainers": ["victoralmau"], }
37.533333
563
1,381
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import Form, TransactionCase class TestSaleOrderQtyChange(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product_1 = cls.env["product.product"].create( {"name": "Test Product 1", "list_price": 25.00, "taxes_id": False} ) cls.product_2 = cls.env["product.product"].create( {"name": "Test Product 2", "list_price": 30.00, "taxes_id": False} ) pricelist = cls.env["product.pricelist"].create({"name": "Test pricelist"}) sale_form = Form( cls.env["sale.order"].with_context(prevent_onchange_quantity=True) ) sale_form.partner_id = cls.env.ref("base.res_partner_12") sale_form.pricelist_id = pricelist with sale_form.order_line.new() as cls.line_form: cls.line_form.product_id = cls.product_1 cls.line_form.product_uom_qty = 1 def test_sale_line_misc(self): self.assertEqual(self.line_form.price_unit, 25) self.line_form.price_unit = 10 self.line_form.product_uom_qty = 2 self.assertEqual(self.line_form.price_unit, 10) self.line_form.product_id = self.product_2 self.assertEqual(self.line_form.price_unit, 30)
43.09375
1,379
1,218
py
PYTHON
15.0
# Copyright 2021 Tecnativa - Víctor Martínez # Copyright 2021 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models from odoo.tools import config class SaleOrderLine(models.Model): _inherit = "sale.order.line" def _onchange_eval(self, field_name, onchange, result): """Remove the trigger for the undesired onchange method with this field. We have to act at this place, as `_onchange_methods` is defined as a property, and thus it can't be inherited due to the conflict of inheritance between Python and Odoo ORM, so we can consider this as a HACK. """ ctx = self.env.context if field_name in {"product_uom_qty", "product_uom"} and ( not config["test_enable"] or (config["test_enable"] and ctx.get("prevent_onchange_quantity", False)) ): cls = type(self) for method in self._onchange_methods.get(field_name, ()): if method == cls.product_uom_change: self._onchange_methods[field_name].remove(method) break return super()._onchange_eval(field_name, onchange, result)
41.931034
1,216
448
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). def post_init_hook(cr, registry): """ As we change the invoice policy to computed field, we must initialize the default policy with original values """ query = """ UPDATE product_template SET default_invoice_policy = invoice_policy WHERE invoice_policy IS NOT NULL""" cr.execute(query)
29.866667
448
689
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Sale invoice Policy", "summary": """ Sales Management: let the user choose the invoice policy on the order""", "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "category": "Sales Management", "version": "15.0.1.0.1", "license": "AGPL-3", "depends": ["sale_stock"], "data": [ "views/product_template_view.xml", "views/res_config_settings_view.xml", "views/sale_view.xml", ], "post_init_hook": "post_init_hook", }
34.45
689
7,501
py
PYTHON
15.0
# © 2017 Acsone SA/NV (http://www.acsone.eu) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import odoo.tests.common as common class TestSaleOrderInvoicePolicy(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.product_obj = cls.env["product.product"] cls.sale_obj = cls.env["sale.order"] cls.partner = cls.env.ref("base.res_partner_2") cls.product = cls.product_obj.create( {"name": "Test", "type": "consu", "list_price": 20.0} ) cls.product2 = cls.product_obj.create( {"name": "Test 2", "type": "consu", "list_price": 45.0} ) cls.product3 = cls.product_obj.create( {"name": "Test 3 (service)", "type": "service", "list_price": 850.5} ) def test_sale_order_invoice_order(self): """Test invoicing based on ordered quantities""" so = self.env["sale.order"].create( { "partner_id": self.env.ref("base.res_partner_2").id, "order_line": [ (0, 0, {"product_id": self.product.id, "product_uom_qty": 2.0}), (0, 0, {"product_id": self.product2.id, "product_uom_qty": 3.0}), ], "invoice_policy": "order", } ) so.action_confirm() self.assertEqual(len(so.picking_ids), 1) for picking in so.picking_ids: picking.action_assign() self.assertEqual(picking.state, "assigned") so_line = so.order_line[0] self.assertEqual(so_line.qty_to_invoice, 2) self.assertEqual(so_line.invoice_status, "to invoice") so_line = so.order_line[1] self.assertEqual(so_line.qty_to_invoice, 3) self.assertEqual(so_line.invoice_status, "to invoice") def test_sale_order_invoice_deliver(self): """Test invoicing based on delivered quantities""" so = self.env["sale.order"].create( { "partner_id": self.env.ref("base.res_partner_2").id, "invoice_policy": "delivery", "order_line": [ (0, 0, {"product_id": self.product.id, "product_uom_qty": 2.0}), (0, 0, {"product_id": self.product2.id, "product_uom_qty": 3.0}), ], } ) so.action_confirm() self.assertEqual(len(so.picking_ids), 1) for picking in so.picking_ids: picking.action_assign() self.assertEqual(picking.state, "assigned") so_line = so.order_line[0] self.assertEqual(so_line.qty_to_invoice, 0) self.assertEqual(so_line.invoice_status, "no") so_line = so.order_line[1] self.assertEqual(so_line.qty_to_invoice, 0) self.assertEqual(so_line.invoice_status, "no") for mv in picking.move_lines: mv.quantity_done = mv.product_uom_qty picking.button_validate() self.assertEqual(picking.state, "done") so_line = so.order_line[0] self.assertEqual(so_line.qty_to_invoice, 2) self.assertEqual(so_line.invoice_status, "to invoice") so_line = so.order_line[1] self.assertEqual(so_line.qty_to_invoice, 3) self.assertEqual(so_line.invoice_status, "to invoice") def test_sale_order_invoice_policy_service1(self): """ For this test, we check if the invoice policy is correctly updated (into the product) when the type is 'service'. The behaviour should be: - Get the value of the context but if the type is 'service': use the default_invoice_policy field value :return: bool """ product = self.product3 invoice_policy = "delivery" product.write({"default_invoice_policy": invoice_policy}) self.assertEqual(product.invoice_policy, invoice_policy) product = product.with_context( invoice_policy="order", ) # Shouldn't be impacted by the context because the type is service self.assertEqual(product.invoice_policy, invoice_policy) return True def test_sale_order_invoice_policy_service2(self): """ For this test, we check if the invoice policy is correctly updated (into the product) when the type is 'service'. The behaviour should be: - Get the value of the context but if the type is 'service': use the default_invoice_policy field value :return: bool """ product = self.product3 invoice_policy = "order" product.write({"default_invoice_policy": invoice_policy}) self.assertEqual(product.invoice_policy, invoice_policy) product = product.with_context( invoice_policy="delivery", ) # Shouldn't be impacted by the context because the type is service self.assertEqual(product.invoice_policy, invoice_policy) return True def test_sale_order_invoice_policy_service3(self): """ For this test, we check if the invoice policy is correctly updated (into the product) when the type is 'service'. The behaviour should be: - Get the value of the context but if the type is 'service': use the default_invoice_policy field value :return: bool """ product = self.product3 product2 = self.product2 products = product products |= product2 invoice_policy = "order" products.write({"default_invoice_policy": invoice_policy}) self.assertEqual(product.invoice_policy, invoice_policy) self.assertEqual(product2.invoice_policy, invoice_policy) new_invoice_policy = "delivery" product = product.with_context( invoice_policy=new_invoice_policy, ) product2 = product2.with_context( invoice_policy=new_invoice_policy, ) # Shouldn't be impacted by the context because the type is service self.assertEqual(product.invoice_policy, invoice_policy) # This one is not a service so it must be impacted by the context self.assertEqual(product2.invoice_policy, new_invoice_policy) product = product.with_context( invoice_policy=invoice_policy, ) product2 = product2.with_context( invoice_policy=invoice_policy, ) # Shouldn't be impacted by the context because the type is service self.assertEqual(product.invoice_policy, invoice_policy) # This one is not a service so it must be impacted by the context self.assertEqual(product2.invoice_policy, invoice_policy) return True def test_inverse_invoice_policy(self): self.product.default_invoice_policy = "order" self.assertEqual("order", self.product.default_invoice_policy) self.product.invoice_policy = "delivery" self.assertEqual("delivery", self.product.default_invoice_policy) def test_settings(self): settings = self.env["res.config.settings"].create({}) settings.sale_default_invoice_policy = "delivery" settings.sale_invoice_policy_required = True settings.execute() so = self.env["sale.order"].create( {"partner_id": self.env.ref("base.res_partner_2").id} ) self.assertEqual(so.invoice_policy, "delivery") self.assertTrue(so.invoice_policy_required)
40.106952
7,500
1,588
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" invoice_policy = fields.Selection( [("order", "Ordered quantities"), ("delivery", "Delivered quantities")], readonly=True, states={"draft": [("readonly", False)], "sent": [("readonly", False)]}, help="Ordered Quantity: Invoice based on the quantity the customer " "ordered.\n" "Delivered Quantity: Invoiced based on the quantity the vendor " "delivered (time or deliveries).", ) invoice_policy_required = fields.Boolean( compute="_compute_invoice_policy_required", default=lambda self: self.env["ir.default"].get( "res.config.settings", "sale_invoice_policy_required" ), ) @api.model def default_get(self, fields_list): res = super().default_get(fields_list) default_sale_invoice_policy = self.env["ir.default"].get( "res.config.settings", "sale_default_invoice_policy" ) if "invoice_policy" not in res: res.update({"invoice_policy": default_sale_invoice_policy}) return res @api.depends("partner_id") def _compute_invoice_policy_required(self): invoice_policy_required = self.env["ir.default"].get( "res.config.settings", "sale_invoice_policy_required" ) for sale in self: sale.invoice_policy_required = invoice_policy_required
36.930233
1,588
2,748
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" @api.depends( "qty_invoiced", "qty_delivered", "product_uom_qty", "order_id.state", "order_id.invoice_policy", ) def _get_to_invoice_qty(self): invoice_policies = set(self.mapped("order_id.invoice_policy")) line_by_id = {line.id: line for line in self} done_lines = self.env["sale.order.line"].browse() for invoice_policy in invoice_policies: so_lines = ( self.with_context(invoice_policy=invoice_policy) .filtered(lambda x, p=invoice_policy: x.order_id.invoice_policy == p) .with_prefetch() ) done_lines |= so_lines so_lines.mapped("product_id") if so_lines: super(SaleOrderLine, so_lines)._get_to_invoice_qty() for line in so_lines: # due to the change of context in compute methods, # assign the value in the modified context to self line_by_id[line.id].qty_to_invoice = line.qty_to_invoice # Not to break function if (it could not happen) some records # were not in so_lines super(SaleOrderLine, self - done_lines)._get_to_invoice_qty() return True @api.depends( "state", "product_uom_qty", "qty_delivered", "qty_to_invoice", "qty_invoiced", "order_id.invoice_policy", ) def _compute_invoice_status(self): invoice_policies = set(self.mapped("order_id.invoice_policy")) line_by_id = {line.id: line for line in self} done_lines = self.env["sale.order.line"].browse() for invoice_policy in invoice_policies: so_lines = ( self.with_context(invoice_policy=invoice_policy) .filtered(lambda x, p=invoice_policy: x.order_id.invoice_policy == p) .with_prefetch() ) done_lines |= so_lines if so_lines: super(SaleOrderLine, so_lines)._compute_invoice_status() for line in so_lines: # due to the change of context in compute methods, # assign the value in the modified context to self line_by_id[line.id].invoice_status = line.invoice_status # Not to break function if (it could not happen) some records # were not in so_lines super(SaleOrderLine, self - done_lines)._compute_invoice_status() return True
39.826087
2,748
1,993
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" default_invoice_policy = fields.Selection( [("order", "Ordered quantities"), ("delivery", "Delivered quantities")], string="Default Invoicing Policy", help="Ordered Quantity: Invoice based on the quantity the customer " "ordered.\n" "Delivered Quantity: Invoiced based on the quantity the vendor " "delivered (time or deliveries).", default=lambda self: self.env["ir.default"].get( "res.config.settings", "default_invoice_policy" ), ) invoice_policy = fields.Selection( compute="_compute_invoice_policy", store=False, readonly=True, search="_search_invoice_policy", inverse="_inverse_invoice_policy", ) def _inverse_invoice_policy(self): for template in self.filtered("invoice_policy"): template.default_invoice_policy = template.invoice_policy @api.depends("type", "default_invoice_policy") @api.depends_context("invoice_policy") def _compute_invoice_policy(self): """ Apply the invoice_policy given by context (if exist) otherwise use the default invoice policy given by the field with this same name. If the product is type = 'service', we don't have to apply the invoice policy given by the context. :return: """ invoice_policy = self.env.context.get("invoice_policy") for tmpl in self: if tmpl.type != "service" and invoice_policy: tmpl.invoice_policy = invoice_policy else: tmpl.invoice_policy = tmpl.default_invoice_policy @api.model def _search_invoice_policy(self, operator, value): return [("default_invoice_policy", operator, value)]
37.603774
1,993
1,462
py
PYTHON
15.0
# Copyright 2018 ACSONE SA/NV (<http://acsone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ResConfigSettings(models.TransientModel): _name = "res.config.settings" _inherit = "res.config.settings" sale_default_invoice_policy = fields.Selection( related="default_invoice_policy", string="Default Sale Invoice Policy", readonly=True, ) sale_invoice_policy_required = fields.Boolean( help="This makes Invoice Policy required on Sale Orders" ) @api.model def get_values(self): res = super().get_values() res.update( sale_invoice_policy_required=self.env["ir.default"].get( "res.config.settings", "sale_invoice_policy_required" ) ) return res def set_values(self): super().set_values() ir_default_obj = self.env["ir.default"] if self.env["res.users"].has_group("base.group_erp_manager"): ir_default_obj = ir_default_obj.sudo() ir_default_obj.set( "res.config.settings", "sale_invoice_policy_required", self.sale_invoice_policy_required, ) ir_default_obj.set( "res.config.settings", "sale_default_invoice_policy", self.sale_default_invoice_policy, ) return True
31.782609
1,462
569
py
PYTHON
15.0
# Copyright 2020-21 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Sale Stock Delivery Address", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/sale-workflow", "category": "Sales Management", "license": "AGPL-3", "development_status": "Production/Stable", "depends": ["sale_stock", "sale_procurement_group_by_line"], "data": ["views/sale_order_view.xml", "views/res_partner_view.xml"], "installable": True, }
37.933333
569
5,565
py
PYTHON
15.0
# Copyright 2020-22 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests import TransactionCase class TestStockSourcingAddress(TransactionCase): def setUp(self): super(TestStockSourcingAddress, self).setUp() self.partner_model = self.env["res.partner"] self.product_model = self.env["product.product"] self.warehouse_model = self.env["stock.warehouse"] self.move_model = self.env["stock.move"] self.location_model = self.env["stock.location"] self.warehouse = self.env.ref("stock.warehouse0") self.customer_loc_default = self.env.ref("stock.stock_location_customers") self.customer_loc_secondary = self.location_model.create( {"name": "Test customer location", "usage": "customer"} ) self.partner = self.partner_model.create({"name": "Test partner"}) self.address_1 = self.partner_model.create( {"name": "Address 1", "parent_id": self.partner.id, "type": "delivery"} ) self.address_2 = self.partner_model.create( {"name": "Address 2", "parent_id": self.partner.id, "type": "delivery"} ) self.product = self.product_model.create( {"name": "Test product", "type": "product"} ) # Create route for secondary customer location: self.secondary_route = self.env["stock.location.route"].create( { "warehouse_selectable": True, "name": "Ship to customer sec location", "warehouse_ids": [(6, 0, self.warehouse.ids)], } ) self.wh2_rule = self.env["stock.rule"].create( { "location_id": self.customer_loc_secondary.id, "location_src_id": self.warehouse.lot_stock_id.id, "action": "pull_push", "warehouse_id": self.warehouse.id, "picking_type_id": self.env.ref("stock.picking_type_out").id, "name": "Stock -> Customers 2", "route_id": self.secondary_route.id, } ) # Create a SO with a couple of lines: self.so = self.env["sale.order"].create( { "partner_id": self.partner.id, "partner_invoice_id": self.partner.id, "partner_shipping_id": self.partner.id, "warehouse_id": self.warehouse.id, "order_line": [ ( 0, 0, { "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 2, "product_uom": self.product.uom_id.id, "price_unit": self.product.list_price, }, ), ( 0, 0, { "name": self.product.name, "product_id": self.product.id, "product_uom_qty": 5, "product_uom": self.product.uom_id.id, "price_unit": self.product.list_price, }, ), ], } ) self.line_1 = self.so.order_line[0] self.line_2 = self.so.order_line[1] def test_01_one_address_per_line(self): self.line_1.dest_address_id = self.address_1 self.line_2.dest_address_id = self.address_2 self.so.action_confirm() self.assertEqual(len(self.so.picking_ids), 2) self.assertNotEqual( self.so.picking_ids[0].partner_id, self.so.picking_ids[1].partner_id ) move_1 = self.move_model.search([("sale_line_id", "=", self.line_1.id)]) self.assertEqual(move_1.picking_id.partner_id, self.address_1) move_2 = self.move_model.search([("sale_line_id", "=", self.line_2.id)]) self.assertEqual(move_2.picking_id.partner_id, self.address_2) def test_02_default_address(self): self.line_1.dest_address_id = self.address_1 self.so.action_confirm() self.assertEqual(len(self.so.picking_ids), 2) move_1 = self.move_model.search([("sale_line_id", "=", self.line_1.id)]) self.assertEqual(move_1.picking_id.partner_id, self.address_1) move_2 = self.move_model.search([("sale_line_id", "=", self.line_2.id)]) # Address in header should have been used: self.assertEqual(move_2.picking_id.partner_id, self.partner) def test_03_different_stock_location(self): # Use a different customer location in one of the addresses: self.address_1.property_stock_customer = self.customer_loc_secondary self.line_1.dest_address_id = self.address_1 self.line_2.dest_address_id = self.address_2 self.so.action_confirm() self.assertEqual(len(self.so.picking_ids), 2) move_1 = self.move_model.search([("sale_line_id", "=", self.line_1.id)]) self.assertEqual(move_1.picking_id.partner_id, self.address_1) self.assertEqual(move_1.location_dest_id, self.customer_loc_secondary) move_2 = self.move_model.search([("sale_line_id", "=", self.line_2.id)]) self.assertEqual(move_2.picking_id.partner_id, self.address_2) self.assertEqual(move_2.location_dest_id, self.customer_loc_default)
45.243902
5,565
642
py
PYTHON
15.0
# Copyright 2020-22 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, models class SaleOrder(models.Model): _inherit = "sale.order" @api.model def _prepare_procurement_group_by_line(self, line): vals = super(SaleOrder, self)._prepare_procurement_group_by_line(line) if line._get_procurement_group_key()[0] == 16 and line.dest_address_id: name_extension = ( line.dest_address_id.name or line.dest_address_id.contact_address ) vals["name"] = "/".join([vals["name"], name_extension]) return vals
35.666667
642
988
py
PYTHON
15.0
# Copyright 2020-22 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class SaleOrderLine(models.Model): _inherit = "sale.order.line" dest_address_id = fields.Many2one( comodel_name="res.partner", string="Destination Address", help="If set this address will be the delivery address instead of the " "one specified in the Sales Order header.", ) def _get_procurement_group_key(self): """Return a key with priority to be used to regroup lines in multiple procurement groups. The higher the priority number is the more preference the criteria has. """ priority = 15 key = super(SaleOrderLine, self)._get_procurement_group_key() # Check priority if key[0] >= priority: return key if self.dest_address_id: return (priority, self.dest_address_id) return (priority, key)
34.068966
988
1,612
py
PYTHON
15.0
# Copyright 2020-22 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, models class ProcurementGroup(models.Model): _inherit = "procurement.group" @api.model def run(self, procurements, raise_user_error=True): new_procs = [] Proc = self.env["procurement.group"].Procurement for procurement in procurements: sale_line_id = procurement.values.get("sale_line_id") if sale_line_id: sale_line = self.env["sale.order.line"].browse(sale_line_id) if sale_line.dest_address_id: procurement.values["partner_id"] = sale_line.dest_address_id.id group = procurement.values.get("group_id") group.partner_id = sale_line.dest_address_id new_location_id = sale_line.dest_address_id.property_stock_customer else: new_location_id = procurement.location_id new_procs.append( Proc( procurement.product_id, procurement.product_qty, procurement.product_uom, new_location_id, procurement.name, procurement.origin, procurement.company_id, procurement.values, ) ) else: new_procs.append(procurement) return super(ProcurementGroup, self).run(new_procs, raise_user_error)
41.333333
1,612
588
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Sale Discount Invoicing", "version": "15.0.1.0.0", "author": "Camptocamp, Odoo Community Association (OCA)", "license": "AGPL-3", "category": "Sales", "depends": [ "account", "sale", ], "website": "https://github.com/OCA/sale-workflow", "data": [ "views/product_category.xml", "views/product_template.xml", "views/res_config_settings.xml", "views/sale_order.xml", ], "installable": True, }
28
588
16,040
py
PYTHON
15.0
# Copyright 2022 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.exceptions import ValidationError from odoo.tests.common import Form, TransactionCase class TestSaleInvoiceDiscount(TransactionCase): # SETUP METHODS # @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) cls.setUpCompany() cls.setUpAccounts() cls.setUpTaxes() cls.setUpProducts() cls.setUpAccountJournal() cls.setUpSalePartner() @classmethod def setUpCompany(cls): """Set up main company""" cls.company = cls.env.ref("base.main_company") cls.company.country_id = cls.env.ref("base.fr") @classmethod def setUpAccounts(cls): """Set up accounts""" cls.account_tax = cls.env["account.account"].create( { "code": "VAT", "name": "VAT", "user_type_id": cls.env.ref( "account.data_account_type_current_assets" ).id, "company_id": cls.company.id, } ) cls.account_income_product = cls.env["account.account"].create( { "code": "INCOME_PROD111", "name": "Income - Test Account", "user_type_id": cls.env.ref( "account.data_account_type_direct_costs" ).id, "company_id": cls.company.id, } ) cls.account_discount_product = cls.env["account.account"].create( { "code": "DISCOUNT_PROD111", "name": "Discount - Test Account", "user_type_id": cls.env.ref( "account.data_account_type_direct_costs" ).id, "company_id": cls.company.id, } ) cls.account_property_receivable = cls.env["account.account"].create( { "code": "X2020", "name": "Receivable - Test Account", "user_type_id": cls.env.ref("account.data_account_type_receivable").id, "reconcile": True, "company_id": cls.company.id, } ) cls.account_income = cls.env["account.account"].create( { "code": "NC1112-1", "name": "Sale - Test Account", "user_type_id": cls.env.ref( "account.data_account_type_direct_costs" ).id, "company_id": cls.company.id, } ) cls.account_revenue = cls.env["account.account"].create( { "code": "NC1114-1", "name": "Sales - Test Sales Account", "user_type_id": cls.env.ref("account.data_account_type_revenue").id, "reconcile": True, "company_id": cls.company.id, } ) @classmethod def setUpTaxes(cls): """Set up some taxes""" cls.tax_price_include = cls.env["account.tax"].create( { "name": "10.0% incl", "type_tax_use": "sale", "amount_type": "percent", "amount": 10.0, "price_include": True, "include_base_amount": False, "country_id": cls.env.ref("base.fr").id, "invoice_repartition_line_ids": [ ( 0, 0, {"factor_percent": 100, "repartition_type": "base"}, ), ( 0, 0, { "factor_percent": 100, "repartition_type": "tax", "account_id": cls.account_tax.id, }, ), ], "refund_repartition_line_ids": [ ( 0, 0, {"factor_percent": 100, "repartition_type": "base"}, ), ( 0, 0, { "factor_percent": 100, "repartition_type": "tax", "account_id": cls.account_tax.id, }, ), ], } ) cls.tax_price_exclude = cls.env["account.tax"].create( { "name": "10.0% excl", "type_tax_use": "sale", "amount_type": "percent", "amount": 10.0, "price_include": False, "include_base_amount": False, "country_id": cls.env.ref("base.fr").id, "invoice_repartition_line_ids": [ ( 0, 0, {"factor_percent": 100, "repartition_type": "base"}, ), ( 0, 0, { "factor_percent": 100, "repartition_type": "tax", "account_id": cls.account_tax.id, }, ), ], "refund_repartition_line_ids": [ ( 0, 0, {"factor_percent": 100, "repartition_type": "base"}, ), ( 0, 0, { "factor_percent": 100, "repartition_type": "tax", "account_id": cls.account_tax.id, }, ), ], } ) @classmethod def setUpProducts(cls): """Set up some additional products, categories, etc...""" cls.product_discount_category = cls.env["product.category"].create( { "name": "Product Category with Discount account", "property_account_income_categ_id": cls.account_income_product.id, "property_account_discount_categ_id": cls.account_discount_product.id, } ) cls.product_order_tax_excluded = cls.env["product.product"].create( { "name": "Product Test Excluded", "standard_price": 100, "list_price": 100, "type": "consu", "uom_id": cls.env.ref("uom.product_uom_unit").id, "uom_po_id": cls.env.ref("uom.product_uom_unit").id, "invoice_policy": "order", "expense_policy": "no", "default_code": "PROD_ORDER_Excluded", "taxes_id": [(6, 0, [cls.tax_price_exclude.id])], "categ_id": cls.product_discount_category.id, } ) cls.product_order_tax_included = cls.env["product.product"].create( { "name": "Product Test 1 Included", "standard_price": 100, "list_price": 100, "type": "consu", "uom_id": cls.env.ref("uom.product_uom_unit").id, "uom_po_id": cls.env.ref("uom.product_uom_unit").id, "invoice_policy": "order", "expense_policy": "no", "default_code": "PROD_ORDER_Included", "taxes_id": [(6, 0, [cls.tax_price_include.id])], "categ_id": cls.product_discount_category.id, } ) @classmethod def setUpAccountJournal(cls): """Set up some additional journals""" cls.journal_sale_company = cls.env["account.journal"].create( { "name": "Sale Journal - Test", "code": "AJ-SALE", "type": "sale", "company_id": cls.company.id, "default_account_id": cls.account_income.id, } ) @classmethod def setUpSalePartner(cls): """Set up sale order's partner""" cls.partner1 = cls.env["res.partner"].create( { "name": "Test Partner", "company_id": False, "property_account_receivable_id": cls.account_property_receivable.id, "country_id": cls.env.ref("base.fr").id, } ) # COMMON TOOLS # def _run_test(self, tax_type: str, company_param: bool, with_discount: bool): self._set_company_param(company_param) self._create_so(tax_type=tax_type, with_discount=with_discount) self._confirm_so() self._create_invoice() self._test_results(company_param=company_param, with_discount=with_discount) def _set_company_param(self, company_param: bool): self.company.account_split_discount_line = company_param def _create_so(self, tax_type: str, with_discount: bool): if tax_type == "excluded": product = self.product_order_tax_excluded origin_price_unit = 1250 price_unit = 1000 if with_discount else origin_price_unit elif tax_type == "included": product = self.product_order_tax_included origin_price_unit = 1375 price_unit = 1100 if with_discount else origin_price_unit else: raise ValueError self.current_sale_order = self.env["sale.order"].create( { "partner_id": self.partner1.id, "partner_invoice_id": self.partner1.id, "partner_shipping_id": self.partner1.id, "order_line": [ ( 0, 0, { "name": product.name, "product_id": product.id, "product_uom": product.uom_id.id, "price_unit": price_unit, "origin_price_unit": origin_price_unit, }, ) ], } ) def _confirm_so(self): assert self.current_sale_order self.current_sale_order.action_confirm() def _create_invoice(self): assert self.current_sale_order old_invoices = self.current_sale_order.invoice_ids wiz = ( self.env["sale.advance.payment.inv"] .with_context( **{ "active_model": "sale.order", "active_ids": [self.current_sale_order.id], "active_id": self.current_sale_order.id, "default_journal_id": self.journal_sale_company.id, } ) .create({"advance_payment_method": "delivered"}) ) wiz.create_invoices() self.current_invoice = self.current_sale_order.invoice_ids - old_invoices def _test_results(self, company_param: bool, with_discount: bool): created = [ ( line.account_id.id, line.debit, line.credit, line.discount_split_by_sale_line_id.id, line.is_split_line, line.is_split_discount_line, ) for line in self.current_invoice.line_ids.sorted( lambda l: (l.debit, l.credit) ) ] if with_discount: if company_param: expected = [ (self.account_tax.id, 0.0, 100.0, False, False, False), ( self.account_income_product.id, 0.0, 1250.0, self.current_sale_order.order_line.id, True, False, ), ( self.account_discount_product.id, 250.0, 0.0, self.current_sale_order.order_line.id, True, True, ), ( self.account_property_receivable.id, 1100.0, 0.0, False, False, False, ), ] else: expected = [ (self.account_tax.id, 0.0, 100.0, False, False, False), (self.account_income_product.id, 0.0, 1000.0, False, False, False), ( self.account_property_receivable.id, 1100.0, 0.0, False, False, False, ), ] else: expected = [ (self.account_tax.id, 0.0, 125.0, False, False, False), (self.account_income_product.id, 0.0, 1250.0, False, False, False), (self.account_property_receivable.id, 1375.0, 0.0, False, False, False), ] self.assertEqual(created, expected) for line in self.current_sale_order.order_line: self.assertEqual(line.qty_invoiced, line.product_uom_qty) # PROPER TESTS # def test_00_invoicing_discount_tax_excluded(self): self._run_test(tax_type="excluded", company_param=True, with_discount=True) def test_01_invoicing_discount_tax_included(self): self._run_test(tax_type="included", company_param=True, with_discount=True) def test_02_invoicing_no_discount_tax_excluded(self): self._run_test(tax_type="excluded", company_param=True, with_discount=False) def test_03_invoicing_no_discount_tax_included(self): self._run_test(tax_type="included", company_param=True, with_discount=False) def test_04_invoicing_discount_tax_excluded_no_splitting_by_config(self): self._run_test(tax_type="excluded", company_param=False, with_discount=True) def test_05_invoicing_discount_tax_included_no_splitting_by_config(self): self._run_test(tax_type="included", company_param=False, with_discount=True) def test_06_invoicing_no_discount_tax_excluded_no_splitting_by_config(self): self._run_test(tax_type="excluded", company_param=False, with_discount=False) def test_07_invoicing_no_discount_tax_included_no_splitting_by_config(self): self._run_test(tax_type="included", company_param=False, with_discount=False) def test_08_raise_update_error_from_form_view(self): self._set_company_param(True) self._create_so(tax_type="excluded", with_discount=True) self._confirm_so() self._create_invoice() with self.assertRaisesRegex( ValidationError, "Please create/delete/modify both lines." ): with Form(self.current_invoice) as invoice_form: with invoice_form.invoice_line_ids.edit(0) as invoice_line: invoice_line.quantity += 1 def test_09_raise_delete_error_from_form_view(self): self._set_company_param(True) self._create_so(tax_type="excluded", with_discount=True) self._confirm_so() self._create_invoice() with self.assertRaisesRegex( ValidationError, "Please create/delete/modify both lines." ): with Form(self.current_invoice) as invoice_form: invoice_form.invoice_line_ids.remove(0)
37.652582
16,040