From e2e2c0dd3c9d48c9d25e0f44888bc563266d5d60 Mon Sep 17 00:00:00 2001
From: "Pedro M. Baeza" <pedro.baeza@tecnativa.com>
Date: Fri, 7 Aug 2020 20:09:43 +0200
Subject: [PATCH] [MIG] sale_commission_salesman: Migration to 13.0

* Standard procedure
* Adapt account.invoice > account.move
* Adapt tests
---
 sale_commission_salesman/README.rst           | 10 +-
 sale_commission_salesman/__manifest__.py      |  6 +-
 sale_commission_salesman/models/__init__.py   |  2 +-
 .../models/account_invoice.py                 | 24 -----
 .../models/account_move.py                    | 23 +++++
 .../models/res_partner.py                     |  4 +-
 sale_commission_salesman/models/sale_order.py | 16 +---
 .../static/description/index.html             |  6 +-
 .../tests/test_sale_commission_salesman.py    | 96 ++++++++-----------
 .../views/res_partner_views.xml               |  2 +-
 10 files changed, 84 insertions(+), 105 deletions(-)
 delete mode 100644 sale_commission_salesman/models/account_invoice.py
 create mode 100644 sale_commission_salesman/models/account_move.py

diff --git a/sale_commission_salesman/README.rst b/sale_commission_salesman/README.rst
index 49593c5b1..e0af1ac39 100644
--- a/sale_commission_salesman/README.rst
+++ b/sale_commission_salesman/README.rst
@@ -14,13 +14,13 @@ Sales commissions from salesman
     :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
     :alt: License: AGPL-3
 .. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fcommission-lightgray.png?logo=github
-    :target: https://github.com/OCA/commission/tree/12.0/sale_commission_salesman
+    :target: https://github.com/OCA/commission/tree/13.0/sale_commission_salesman
     :alt: OCA/commission
 .. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
-    :target: https://translation.odoo-community.org/projects/commission-12-0/commission-12-0-sale_commission_salesman
+    :target: https://translation.odoo-community.org/projects/commission-13-0/commission-13-0-sale_commission_salesman
     :alt: Translate me on Weblate
 .. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png
-    :target: https://runbot.odoo-community.org/runbot/165/12.0
+    :target: https://runbot.odoo-community.org/runbot/165/13.0
     :alt: Try me on Runbot
 
 |badge1| |badge2| |badge3| |badge4| |badge5| 
@@ -64,7 +64,7 @@ Bug Tracker
 Bugs are tracked on `GitHub Issues <https://github.com/OCA/commission/issues>`_.
 In case of trouble, please check there if your issue has already been reported.
 If you spotted it first, help us smashing it by providing a detailed and welcomed
-`feedback <https://github.com/OCA/commission/issues/new?body=module:%20sale_commission_salesman%0Aversion:%2012.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
+`feedback <https://github.com/OCA/commission/issues/new?body=module:%20sale_commission_salesman%0Aversion:%2013.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
 
 Do not contact contributors directly about support or help with technical issues.
 
@@ -101,6 +101,6 @@ OCA, or the Odoo Community Association, is a nonprofit organization whose
 mission is to support the collaborative development of Odoo features and
 promote its widespread use.
 
-This module is part of the `OCA/commission <https://github.com/OCA/commission/tree/12.0/sale_commission_salesman>`_ project on GitHub.
+This module is part of the `OCA/commission <https://github.com/OCA/commission/tree/13.0/sale_commission_salesman>`_ project on GitHub.
 
 You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
diff --git a/sale_commission_salesman/__manifest__.py b/sale_commission_salesman/__manifest__.py
index 29d54726a..b9ea9acaa 100644
--- a/sale_commission_salesman/__manifest__.py
+++ b/sale_commission_salesman/__manifest__.py
@@ -3,12 +3,12 @@
 
 {
     "name": "Sales commissions from salesman",
-    "version": "12.0.1.0.0",
+    "version": "13.0.1.0.0",
     "author": "Tecnativa, " "Odoo Community Association (OCA)",
     "category": "Sales",
     "website": "https://github.com/OCA/commission",
     "license": "AGPL-3",
-    "depends": ["sale_commission",],
-    "data": ["views/res_partner_views.xml",],
+    "depends": ["sale_commission"],
+    "data": ["views/res_partner_views.xml"],
     "installable": True,
 }
diff --git a/sale_commission_salesman/models/__init__.py b/sale_commission_salesman/models/__init__.py
index 9582ff43d..50fe8eac5 100644
--- a/sale_commission_salesman/models/__init__.py
+++ b/sale_commission_salesman/models/__init__.py
@@ -1,5 +1,5 @@
 # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
 
-from . import account_invoice
+from . import account_move
 from . import res_partner
 from . import sale_order
diff --git a/sale_commission_salesman/models/account_invoice.py b/sale_commission_salesman/models/account_invoice.py
deleted file mode 100644
index 164cc4048..000000000
--- a/sale_commission_salesman/models/account_invoice.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright 2020 Tecnativa - Pedro M. Baeza
-# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
-
-from odoo import models
-
-
-class AccountInvoiceLine(models.Model):
-    _inherit = "account.invoice.line"
-
-    def _prepare_agents_vals(self, vals=None):
-        """Add salesman agent if configured so and no other commission
-        already populated.
-        """
-        res = super()._prepare_agents_vals(vals=vals)
-        if not res:
-            partner = self.invoice_id.user_id.partner_id
-            if not self and vals.get("invoice_id"):
-                invoice = self.env["account.invoice"].browse(vals["invoice_id"])
-                partner = invoice.user_id.partner_id
-            if partner.agent and partner.salesman_as_agent:
-                res = [
-                    (0, 0, {"agent": partner.id, "commission": partner.commission.id,}),
-                ]
-        return res
diff --git a/sale_commission_salesman/models/account_move.py b/sale_commission_salesman/models/account_move.py
new file mode 100644
index 000000000..e0028f089
--- /dev/null
+++ b/sale_commission_salesman/models/account_move.py
@@ -0,0 +1,23 @@
+# Copyright 2020 Tecnativa - Pedro M. Baeza
+# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
+
+from odoo import models
+
+
+class AccountMoveLine(models.Model):
+    _inherit = "account.move.line"
+
+    def _compute_agent_ids(self):
+        """Add salesman agent if configured so and no other commission
+        already populated.
+        """
+        super()._compute_agent_ids()
+        for record in self.filtered(
+            lambda x: x.move_id.partner_id
+            and x.move_id.type[:3] == "out"
+            and x.product_id
+            and not x.agent_ids
+        ):
+            partner = self.move_id.invoice_user_id.partner_id
+            if partner.agent and partner.salesman_as_agent:
+                record.agent_ids = [(0, 0, self._prepare_agent_vals(partner))]
diff --git a/sale_commission_salesman/models/res_partner.py b/sale_commission_salesman/models/res_partner.py
index 2ba9a9a3d..3f284bd4e 100644
--- a/sale_commission_salesman/models/res_partner.py
+++ b/sale_commission_salesman/models/res_partner.py
@@ -14,10 +14,10 @@ class ResPartner(models.Model):
         "added as the commission agent",
     )
 
-    @api.constrains("salesman_as_agent", "commission")
+    @api.constrains("salesman_as_agent", "commission_id")
     def _check_salesman_as_agent(self):
         for record in self:
-            if record.salesman_as_agent and not record.commission:
+            if record.salesman_as_agent and not record.commission_id:
                 raise exceptions.ValidationError(
                     _("You can't have a salesman auto-agent without commission.")
                 )
diff --git a/sale_commission_salesman/models/sale_order.py b/sale_commission_salesman/models/sale_order.py
index 74bd6b776..cddbb9665 100644
--- a/sale_commission_salesman/models/sale_order.py
+++ b/sale_commission_salesman/models/sale_order.py
@@ -7,18 +7,12 @@
 class SaleOrdeLine(models.Model):
     _inherit = "sale.order.line"
 
-    def _prepare_agents_vals(self, vals=None):
+    def _compute_agent_ids(self):
         """Add salesman agent if configured so and no other commission
         already populated.
         """
-        res = super()._prepare_agents_vals(vals=vals)
-        if not res:
+        super()._compute_agent_ids()
+        for record in self.filtered(lambda x: x.order_id.partner_id):
             partner = self.order_id.user_id.partner_id
-            if not self and vals.get("order_id"):
-                order = self.env["sale.order"].browse(vals["order_id"])
-                partner = order.user_id.partner_id
-            if partner.agent and partner.salesman_as_agent:
-                res = [
-                    (0, 0, {"agent": partner.id, "commission": partner.commission.id,}),
-                ]
-        return res
+            if not record.agent_ids and partner.agent and partner.salesman_as_agent:
+                record.agent_ids = [(0, 0, self._prepare_agent_vals(partner))]
diff --git a/sale_commission_salesman/static/description/index.html b/sale_commission_salesman/static/description/index.html
index 19a4fe370..2a0da26f1 100644
--- a/sale_commission_salesman/static/description/index.html
+++ b/sale_commission_salesman/static/description/index.html
@@ -367,7 +367,7 @@ <h1 class="title">Sales commissions from salesman</h1>
 !! This file is generated by oca-gen-addon-readme !!
 !! changes will be overwritten.                   !!
 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -->
-<p><a class="reference external" href="https://odoo-community.org/page/development-status"><img alt="Beta" src="https://img.shields.io/badge/maturity-Beta-yellow.png" /></a> <a class="reference external" href="http://www.gnu.org/licenses/agpl-3.0-standalone.html"><img alt="License: AGPL-3" src="https://img.shields.io/badge/licence-AGPL--3-blue.png" /></a> <a class="reference external" href="https://github.com/OCA/commission/tree/12.0/sale_commission_salesman"><img alt="OCA/commission" src="https://img.shields.io/badge/github-OCA%2Fcommission-lightgray.png?logo=github" /></a> <a class="reference external" href="https://translation.odoo-community.org/projects/commission-12-0/commission-12-0-sale_commission_salesman"><img alt="Translate me on Weblate" src="https://img.shields.io/badge/weblate-Translate%20me-F47D42.png" /></a> <a class="reference external" href="https://runbot.odoo-community.org/runbot/165/12.0"><img alt="Try me on Runbot" src="https://img.shields.io/badge/runbot-Try%20me-875A7B.png" /></a></p>
+<p><a class="reference external" href="https://odoo-community.org/page/development-status"><img alt="Beta" src="https://img.shields.io/badge/maturity-Beta-yellow.png" /></a> <a class="reference external" href="http://www.gnu.org/licenses/agpl-3.0-standalone.html"><img alt="License: AGPL-3" src="https://img.shields.io/badge/licence-AGPL--3-blue.png" /></a> <a class="reference external" href="https://github.com/OCA/commission/tree/13.0/sale_commission_salesman"><img alt="OCA/commission" src="https://img.shields.io/badge/github-OCA%2Fcommission-lightgray.png?logo=github" /></a> <a class="reference external" href="https://translation.odoo-community.org/projects/commission-13-0/commission-13-0-sale_commission_salesman"><img alt="Translate me on Weblate" src="https://img.shields.io/badge/weblate-Translate%20me-F47D42.png" /></a> <a class="reference external" href="https://runbot.odoo-community.org/runbot/165/13.0"><img alt="Try me on Runbot" src="https://img.shields.io/badge/runbot-Try%20me-875A7B.png" /></a></p>
 <p>This module extends the functionality of <cite>sale_commission</cite> to allow you to
 auto-populate salesmen as commission agents without setting explicitly them
 on the customer.</p>
@@ -415,7 +415,7 @@ <h1><a class="toc-backref" href="#id3">Bug Tracker</a></h1>
 <p>Bugs are tracked on <a class="reference external" href="https://github.com/OCA/commission/issues">GitHub Issues</a>.
 In case of trouble, please check there if your issue has already been reported.
 If you spotted it first, help us smashing it by providing a detailed and welcomed
-<a class="reference external" href="https://github.com/OCA/commission/issues/new?body=module:%20sale_commission_salesman%0Aversion:%2012.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**">feedback</a>.</p>
+<a class="reference external" href="https://github.com/OCA/commission/issues/new?body=module:%20sale_commission_salesman%0Aversion:%2013.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**">feedback</a>.</p>
 <p>Do not contact contributors directly about support or help with technical issues.</p>
 </div>
 <div class="section" id="credits">
@@ -448,7 +448,7 @@ <h2><a class="toc-backref" href="#id8">Maintainers</a></h2>
 <p>OCA, or the Odoo Community Association, is a nonprofit organization whose
 mission is to support the collaborative development of Odoo features and
 promote its widespread use.</p>
-<p>This module is part of the <a class="reference external" href="https://github.com/OCA/commission/tree/12.0/sale_commission_salesman">OCA/commission</a> project on GitHub.</p>
+<p>This module is part of the <a class="reference external" href="https://github.com/OCA/commission/tree/13.0/sale_commission_salesman">OCA/commission</a> project on GitHub.</p>
 <p>You are welcome to contribute. To learn how please visit <a class="reference external" href="https://odoo-community.org/page/Contribute">https://odoo-community.org/page/Contribute</a>.</p>
 </div>
 </div>
diff --git a/sale_commission_salesman/tests/test_sale_commission_salesman.py b/sale_commission_salesman/tests/test_sale_commission_salesman.py
index 073e62160..cc9a8ac17 100644
--- a/sale_commission_salesman/tests/test_sale_commission_salesman.py
+++ b/sale_commission_salesman/tests/test_sale_commission_salesman.py
@@ -2,7 +2,7 @@
 # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
 
 from odoo import exceptions
-from odoo.tests.common import SavepointCase
+from odoo.tests.common import Form, SavepointCase
 
 
 class TestSaleCommissionSalesman(SavepointCase):
@@ -10,93 +10,79 @@ class TestSaleCommissionSalesman(SavepointCase):
     def setUpClass(cls):
         super().setUpClass()
         cls.product = cls.env["product.product"].create(
-            {"name": "Test Product 1", "list_price": 100,}
+            {"name": "Test Product 1", "list_price": 100}
         )
         SaleCommission = cls.env["sale.commission"]
         cls.commission_1 = SaleCommission.create(
-            {"name": "1% commission", "fix_qty": 1.0,}
+            {"name": "1% commission", "fix_qty": 1.0}
         )
         Partner = cls.env["res.partner"]
         cls.salesman = cls.env["res.users"].create(
-            {"name": "Test agent", "login": "sale_comission_salesman_test",}
+            {"name": "Test agent", "login": "sale_comission_salesman_test"}
         )
         cls.agent = cls.salesman.partner_id
         cls.agent.write(
             {
                 "agent": True,
                 "salesman_as_agent": True,
-                "commission": cls.commission_1.id,
+                "commission_id": cls.commission_1.id,
             }
         )
         cls.other_agent = Partner.create(
             {
                 "name": "Test other agent",
                 "agent": True,
-                "commission": cls.commission_1.id,
+                "commission_id": cls.commission_1.id,
             }
         )
-        cls.partner = Partner.create({"name": "Partner test",})
+        cls.partner = Partner.create({"name": "Partner test"})
         cls.sale_order = cls.env["sale.order"].create(
-            {"partner_id": cls.partner.id, "user_id": cls.salesman.id,}
+            {"partner_id": cls.partner.id, "user_id": cls.salesman.id}
         )
-        cls.invoice = cls.env["account.invoice"].create(
-            {"partner_id": cls.partner.id, "user_id": cls.salesman.id,}
+        cls.invoice = cls.env["account.move"].create(
+            {
+                "partner_id": cls.partner.id,
+                "invoice_user_id": cls.salesman.id,
+                "type": "out_invoice",
+            }
         )
 
     def test_check_salesman_commission(self):
         with self.assertRaises(exceptions.ValidationError):
-            self.agent.commission = False
+            self.agent.commission_id = False
 
     def test_sale_commission_salesman(self):
-        line = (
-            self.env["sale.order.line"]
-            .with_context(partner_id=self.partner.id)
-            .create({"order_id": self.sale_order.id, "product_id": self.product.id,})
+        line = self.env["sale.order.line"].create(
+            {"order_id": self.sale_order.id, "product_id": self.product.id}
         )
-        self.assertTrue(line.agents)
-        self.assertTrue(line.agents.agent, self.agent)
-        self.assertTrue(line.agents.commission, self.commission_1)
+        self.assertTrue(line.agent_ids)
+        self.assertTrue(line.agent_ids.agent_id, self.agent)
+        self.assertTrue(line.agent_ids.commission_id, self.commission_1)
 
     def test_sale_commission_salesman_no_population(self):
-        self.partner.agents = [(4, self.other_agent.id)]
-        line = (
-            self.env["sale.order.line"]
-            .with_context(partner_id=self.partner.id)
-            .create({"order_id": self.sale_order.id, "product_id": self.product.id,})
+        self.partner.agent_ids = [(4, self.other_agent.id)]
+        line = self.env["sale.order.line"].create(
+            {"order_id": self.sale_order.id, "product_id": self.product.id}
         )
-        self.assertTrue(len(line.agents), 1)
-        self.assertTrue(line.agents.agent, self.other_agent)
+        self.assertTrue(len(line.agent_ids), 1)
+        self.assertTrue(line.agent_ids.agent_id, self.other_agent)
 
     def test_invoice_commission_salesman(self):
-        line_obj = self.env["account.invoice.line"]
-        line = line_obj.with_context(partner_id=self.partner.id).create(
-            {
-                "invoice_id": self.invoice.id,
-                "product_id": self.product.id,
-                "account_id": line_obj.get_invoice_line_account(
-                    self.invoice.type, self.product, False, self.invoice.company_id
-                ).id,
-                "name": self.product.name,
-                "price_unit": 1,
-            }
-        )
-        self.assertTrue(line.agents)
-        self.assertTrue(line.agents.agent, self.agent)
-        self.assertTrue(line.agents.commission, self.commission_1)
+        invoice_form = Form(self.invoice)
+        with invoice_form.invoice_line_ids.new() as line_form:
+            line_form.product_id = self.product
+        invoice_form.save()
+        line = self.invoice.invoice_line_ids
+        self.assertTrue(line.agent_ids)
+        self.assertTrue(line.agent_ids.agent_id, self.agent)
+        self.assertTrue(line.agent_ids.commission_id, self.commission_1)
 
     def test_invoice_commission_salesman_no_population(self):
-        self.partner.agents = [(4, self.other_agent.id)]
-        line_obj = self.env["account.invoice.line"]
-        line = line_obj.with_context(partner_id=self.partner.id).create(
-            {
-                "invoice_id": self.invoice.id,
-                "product_id": self.product.id,
-                "account_id": line_obj.get_invoice_line_account(
-                    self.invoice.type, self.product, False, self.invoice.company_id
-                ).id,
-                "name": self.product.name,
-                "price_unit": 1,
-            }
-        )
-        self.assertTrue(len(line.agents), 1)
-        self.assertTrue(line.agents.agent, self.other_agent)
+        self.partner.agent_ids = [(4, self.other_agent.id)]
+        invoice_form = Form(self.invoice)
+        with invoice_form.invoice_line_ids.new() as line_form:
+            line_form.product_id = self.product
+        invoice_form.save()
+        line = self.invoice.invoice_line_ids
+        self.assertTrue(line.agent_ids)
+        self.assertTrue(line.agent_ids.agent_id, self.other_agent)
diff --git a/sale_commission_salesman/views/res_partner_views.xml b/sale_commission_salesman/views/res_partner_views.xml
index 719563ca2..055161624 100644
--- a/sale_commission_salesman/views/res_partner_views.xml
+++ b/sale_commission_salesman/views/res_partner_views.xml
@@ -6,7 +6,7 @@
         <field name="model">res.partner</field>
         <field name="inherit_id" ref="sale_commission.view_partner_form_agent" />
         <field name="arch" type="xml">
-            <field name="commission" position="after">
+            <field name="commission_id" position="after">
                 <field name="user_ids" invisible="1" />
                 <field
                     name="salesman_as_agent"