Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[14.0][IMP] product_import: optionally set company on product #1077

Open
wants to merge 5 commits into
base: 14.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions product_import/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from . import models
from . import wizard
1 change: 1 addition & 0 deletions product_import/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
],
"data": [
"security/ir.model.access.csv",
"views/res_config_settings.xml",
"wizard/product_import_view.xml",
],
}
2 changes: 2 additions & 0 deletions product_import/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from . import res_company
from . import res_config_settings
15 changes: 15 additions & 0 deletions product_import/models/res_company.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo import fields, models


class ResCompany(models.Model):
_inherit = "res.company"

product_import_set_company = fields.Boolean(
string="Set company on imported product",
help="If active, then products are company-specific. "
"Beware that by default `barcode` is unique for all companies. "
"Install OCA add-on `product_barcode_constraint_per_company` "
"to circumvent this limitation.",
)
11 changes: 11 additions & 0 deletions product_import/models/res_config_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo import fields, models


class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"

product_import_set_company = fields.Boolean(
related="company_id.product_import_set_company", readonly=False
)
4 changes: 2 additions & 2 deletions product_import/tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ def setUpClass(cls):
cls.wiz_model = cls.env["product.import"]
cls.supplier = cls.env["res.partner"].create({"name": "Catalogue Vendor"})

def _mock(self, method_name):
return mock.patch.object(type(self.wiz_model), method_name)
def _mock(self, method_name, **kw):
return mock.patch.object(type(self.wiz_model), method_name, **kw)

@property
def wiz_form(self):
Expand Down
13 changes: 10 additions & 3 deletions product_import/tests/test_product_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
},
],
"ref": "1387",
"company": {"name": "Customer ABC"},
"seller": {
"contact": False,
"email": False,
Expand Down Expand Up @@ -88,9 +89,15 @@ def test_get_company_id(self):

def test_product_import(self):
# product.product
products = self.wiz_model._create_products(
self.parsed_catalog, seller=self.supplier
product_obj = self.env["product.product"].with_context(active_test=False)
existing = product_obj.search([], order="id")

wiz = self.wiz_model.create(
{"product_file": b"====", "product_filename": "test_import.xml"}
)
with self._mock("parse_product_catalogue", return_value=self.parsed_catalog):
wiz.import_button()
products = product_obj.search([], order="id") - existing
self.assertEqual(len(products), 3)
for product, parsed in zip(products, PARSED_CATALOG["products"]):

Expand Down Expand Up @@ -140,7 +147,7 @@ def test_product_import(self):
self.assertEqual(product.seller_ids, product_tmpl.seller_ids)
self.assertEqual(
product.seller_ids.mapped("delay")[0], parsed.get("sale_delay", 0)
),
)

def test_import_button(self):
form = self.wiz_form
Expand Down
28 changes: 28 additions & 0 deletions product_import/views/res_config_settings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8" ?>
<odoo>

<record id="view_config_settings" model="ir.ui.view">
<field name="model">res.config.settings</field>
<field name="inherit_id" ref="product.res_config_settings_view_form" />
<field name="arch" type="xml">
<xpath expr="//div[@id='inter_company']" position="after">
<div
class="col-12 col-lg-6 o_setting_box"
title="Company-specific products"
id="product_import_company"
>
<div class="o_setting_left_pane">
<field name="product_import_set_company" />
</div>
<div class="o_setting_right_pane">
<label for="product_import_set_company" />
<div class="text-muted">
Assign company on imported products
</div>
</div>
</div>
</xpath>
</field>
</record>

</odoo>
113 changes: 78 additions & 35 deletions product_import/wizard/product_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,21 +149,38 @@
result.append((0, 0, seller_info))
return result

@api.model
def _prepare_product(self, parsed_product, chatter_msg, seller=None):
# Important: barcode is unique key of product.template model
# So records product.product are created with company_id=False.
# Only the pricelist (product.supplierinfo) is company-specific.
product_company_id = self.env.context.get("product_company_id", False)
if not parsed_product["barcode"]:
chatter_msg.append(
_("Cannot import product without barcode: %s") % (parsed_product,)
)
return False
product = (
def _search_product(self, domain, company_id):
if company_id:
domain = domain + [("company_id", "=", company_id)]

Check warning on line 154 in product_import/wizard/product_import.py

View check run for this annotation

Codecov / codecov/patch

product_import/wizard/product_import.py#L154

Added line #L154 was not covered by tests
return (
self.env["product.product"]
.with_context(active_test=False)
.search([("barcode", "=", parsed_product["barcode"])], limit=1)
.search(domain, order="active DESC", limit=1)
)

def _existing_product(self, barcode, code, company_id):
product = None
if barcode:
product = self._search_product([("barcode", "=", barcode)], company_id)
return product or self._search_product(
[("default_code", "=", code)], company_id
)

@api.model
def _prepare_product(self, parsed_product, seller, company_id, chatter_msg):
# By default records product.product are created with company_id=False.
# Only the pricelist (product.supplierinfo) is company-specific.
# Setting "product_import_set_company" change the behavior.
# Beware that barcode is unique key of product.template model
# Can be changed by OCA add-on "product_barcode_constraint_per_company"
import_company = self.env["res.company"].browse(company_id)
product_company_id = (
import_company.id if import_company.product_import_set_company else False
)
product = self._existing_product(
parsed_product["barcode"],
parsed_product["code"],
company_id=product_company_id,
)
uom = self._bdimport._match_uom(parsed_product["uom"], chatter_msg)
currency = self._bdimport._match_currency(
Expand All @@ -179,15 +196,15 @@
"type": "product",
"uom_id": uom.id,
"uom_po_id": uom.id,
"company_id": False,
"company_id": product_company_id,
}
seller_info = {
"name": seller and seller.id or False,
"product_code": parsed_product["product_code"],
"price": parsed_product["price"],
"currency_id": currency.id,
"min_qty": parsed_product["min_qty"],
"company_id": product_company_id,
"company_id": import_company.id,
"delay": parsed_product.get("sale_delay", 0),
}
product_vals["seller_ids"] = self._prepare_supplierinfo(seller_info, product)
Expand All @@ -197,14 +214,12 @@
return product_vals

@api.model
def create_product(self, parsed_product, chatter_msg, seller=None):
product_vals = self._prepare_product(parsed_product, chatter_msg, seller=seller)
if not product_vals:
return False
def _save_product(self, product_vals, chatter_msg):
"""Create / Update a product."""
product = product_vals.pop("recordset", None)
if product:
product.write(product_vals)
logger.info("Product %d updated", product.id)
product.update(product_vals)
logger.debug("Product %s updated", product.default_code)

Check warning on line 222 in product_import/wizard/product_import.py

View check run for this annotation

Codecov / codecov/patch

product_import/wizard/product_import.py#L221-L222

Added lines #L221 - L222 were not covered by tests
else:
product_active = product_vals.pop("active")
product = self.env["product.product"].create(product_vals)
Expand All @@ -213,33 +228,61 @@
# all characteristics into product.template
product.flush()
product.action_archive()
logger.info("Product %d created", product.id)
logger.debug("Product %s created", product.default_code)

return product

@api.model
def _create_products(self, catalogue, seller, filename=None):
products = self.env["product.product"].browse()
for product in catalogue.get("products"):
record = self.create_product(
product,
catalogue["chatter_msg"],
def _create_update_products(self, products, seller_id, company_id, chatter_msg):
"""Create / Update all products."""
seller = self.env["res.partner"].browse(seller_id)

for parsed_product in products:
product_vals = self._prepare_product(
parsed_product,
seller=seller,
company_id=company_id,
chatter_msg=chatter_msg,
)
if record:
products |= record
self._bdimport.post_create_or_update(catalogue, seller, doc_filename=filename)
logger.info("Products updated for vendor %d", seller.id)
return products
if product_vals:
product = self._save_product(product_vals, chatter_msg=chatter_msg)
chatter_msg.append(
f"Product created/updated {product.default_code} ({product.id})"
)
return True

@api.model
def create_update_products(self, products, seller_id, company_id, chatter_msg):
"""Create / Update a product.

This method can be overriden, for example to import asynchronously with queue_job.
"""
return self._create_update_products(
products, seller_id, company_id, chatter_msg=chatter_msg
)

def import_button(self):
self.ensure_one()
file_content = b64decode(self.product_file)
# 1st step: Parse the (UBL) document --> get a "catalogue" dictionary
catalogue = self.parse_product_catalogue(file_content, self.product_filename)
if not catalogue.get("products"):
raise UserError(_("This catalogue doesn't have any product!"))
company_id = self._get_company_id(catalogue)
seller = self._get_seller(catalogue)
self.with_context(product_company_id=company_id)._create_products(
catalogue, seller, filename=self.product_filename
# 2nd step: Prepare values and create the "product.product" records in Odoo
self.create_update_products(
catalogue["products"],
seller.id,
company_id,
chatter_msg=catalogue["chatter_msg"],
)
# Save imported file as attachment
self._bdimport.post_create_or_update(
catalogue, seller, doc_filename=self.product_filename
)
logger.info(
"Update for vendor %s: %d products", seller.name, len(catalogue["products"])
)

return {"type": "ir.actions.act_window_close"}