From 41af45de9af4fbd099fc478b72e6ffe3df0ac3dd Mon Sep 17 00:00:00 2001 From: "Laurent Mignon (ACSONE)" Date: Tue, 18 Apr 2017 11:16:47 +0200 Subject: [PATCH] [IMP] packaging_uom: declare 'inverse' method on qty This change is required to make the code working with existing addons without breaking tets. By declaring an invers on qty, we are able to assign/create the required uom to the package based on the expected qty --- packaging_uom/models/product_packaging.py | 43 +++++++++++++++++-- .../views/product_packaging_views.xml | 2 +- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/packaging_uom/models/product_packaging.py b/packaging_uom/models/product_packaging.py index c98a2e28e..20586ee41 100644 --- a/packaging_uom/models/product_packaging.py +++ b/packaging_uom/models/product_packaging.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- # Copyright 2015-2017 ACSONE SA/NV () # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). -from odoo import api, fields, models +from odoo import api, fields, models, _ +from odoo.exceptions import ValidationError class ProductPackaging(models.Model): @@ -18,9 +19,9 @@ class ProductPackaging(models.Model): uom_id = fields.Many2one( 'product.uom', 'Unit of Measure', - required=True, help="It must be in the same category than " - "the default unit of measure." + "the default unit of measure.", + required=False ) uom_categ_domain_id = fields.Many2one( default=_default_uom_categ_domain_id, @@ -28,6 +29,7 @@ class ProductPackaging(models.Model): ) qty = fields.Float( compute="_compute_qty", + inverse="_inverse_qty", store=True, readonly=True ) @@ -43,3 +45,38 @@ class ProductPackaging(models.Model): 1, to_unit=self.product_tmpl_id.uom_id) else: self.qty = 0 + + @api.one + def _inverse_qty(self): + """ + The inverse method is defined to make the code compatible with + existing modules and to not break tests... + :return: + """ + category_id = self.product_tmpl_id.uom_id.category_id + uom_id = self.uom_id.search([ + ("factor", "=", 1.0 / self.qty), + ('category_id', '=', category_id.id)]) + if not uom_id: + uom_id = self.uom_id .create({ + 'name': "%s %s" % (category_id.name, self.qty), + 'category_id': category_id.id, + 'rounding': self.product_tmpl_id.uom_id.rounding, + 'uom_type': 'bigger', + 'factor_inv': self.qty, + 'active': True + }) + self.uom_id = uom_id + + @api.multi + @api.constrains + def _check_uom_id(self): + """ Check uom_id is not null + + Since the field can be computed by the inverse method on 'qty', + it's no more possible to add a sql constrains on the column uom_id. + """ + for rec in self: + if not rec.uom_id: + raise ValidationError(_("The field Unit of Measure is " + "required")) diff --git a/packaging_uom/views/product_packaging_views.xml b/packaging_uom/views/product_packaging_views.xml index 1f3b1dd9c..31a271220 100644 --- a/packaging_uom/views/product_packaging_views.xml +++ b/packaging_uom/views/product_packaging_views.xml @@ -25,7 +25,7 @@ - +