mirror of
https://github.com/bringout/oca-ocb-sale.git
synced 2026-04-26 02:32:00 +02:00
19.0 vanilla
This commit is contained in:
parent
79f83631d5
commit
73afc09215
6267 changed files with 1534193 additions and 1130106 deletions
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
# flake8: noqa: F401
|
||||
|
|
@ -8,14 +7,23 @@
|
|||
from . import product_template
|
||||
from . import product_product
|
||||
|
||||
from . import decimal_precision
|
||||
from . import ir_attachment
|
||||
from . import product_attribute
|
||||
from . import product_attribute_custom_value
|
||||
from . import product_attribute_value
|
||||
from . import product_catalog_mixin
|
||||
from . import product_category
|
||||
from . import product_packaging
|
||||
from . import product_combo
|
||||
from . import product_combo_item
|
||||
from . import product_document
|
||||
from . import product_pricelist
|
||||
from . import product_pricelist_item
|
||||
from . import product_supplierinfo
|
||||
from . import product_tag
|
||||
from . import product_template_attribute_line
|
||||
from . import product_template_attribute_exclusion
|
||||
from . import product_template_attribute_value
|
||||
from . import product_uom
|
||||
from . import res_company
|
||||
from . import res_config_settings
|
||||
from . import res_country_group
|
||||
|
|
|
|||
|
|
@ -1,40 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models, tools, _
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
|
||||
class DecimalPrecision(models.Model):
|
||||
_inherit = 'decimal.precision'
|
||||
|
||||
@api.constrains('digits')
|
||||
def _check_main_currency_rounding(self):
|
||||
if any(precision.name == 'Account' and
|
||||
tools.float_compare(self.env.company.currency_id.rounding, 10 ** - precision.digits, precision_digits=6) == -1
|
||||
for precision in self):
|
||||
raise ValidationError(_("You cannot define the decimal precision of 'Account' as greater than the rounding factor of the company's main currency"))
|
||||
return True
|
||||
|
||||
@api.onchange('digits')
|
||||
def _onchange_digits(self):
|
||||
if self.name != "Product Unit of Measure": # precision_get() relies on this name
|
||||
return
|
||||
# We are changing the precision of UOM fields; check whether the
|
||||
# precision is equal or higher than existing units of measure.
|
||||
rounding = 1.0 / 10.0**self.digits
|
||||
dangerous_uom = self.env['uom.uom'].search([('rounding', '<', rounding)])
|
||||
if dangerous_uom:
|
||||
uom_descriptions = [
|
||||
" - %s (id=%s, precision=%s)" % (uom.name, uom.id, uom.rounding)
|
||||
for uom in dangerous_uom
|
||||
]
|
||||
return {'warning': {
|
||||
'title': _('Warning!'),
|
||||
'message': _(
|
||||
"You are setting a Decimal Accuracy less precise than the UOMs:\n"
|
||||
"%s\n"
|
||||
"This may cause inconsistencies in computations.\n"
|
||||
"Please increase the rounding of those units of measure, or the digits of this Decimal Accuracy."
|
||||
) % ('\n'.join(uom_descriptions)),
|
||||
}}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models
|
||||
|
||||
|
||||
class IrAttachment(models.Model):
|
||||
_inherit = 'ir.attachment'
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
"""Create product.document for attachments added in products chatters"""
|
||||
attachments = super().create(vals_list)
|
||||
if not self.env.context.get('disable_product_documents_creation'):
|
||||
product_attachments = attachments.filtered(
|
||||
lambda attachment:
|
||||
attachment.res_model in ('product.product', 'product.template')
|
||||
and not attachment.res_field
|
||||
)
|
||||
if product_attachments:
|
||||
self.env['product.document'].sudo().create([
|
||||
{
|
||||
'ir_attachment_id': attachment.id
|
||||
}
|
||||
for attachment in product_attachments
|
||||
])
|
||||
return attachments
|
||||
|
|
@ -1,55 +1,108 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from random import randint
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
from odoo.osv import expression
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class ProductAttribute(models.Model):
|
||||
_name = "product.attribute"
|
||||
_name = 'product.attribute'
|
||||
_description = "Product Attribute"
|
||||
# if you change this _order, keep it in sync with the method
|
||||
# `_sort_key_attribute_value` in `product.template`
|
||||
_order = 'sequence, id'
|
||||
|
||||
name = fields.Char('Attribute', required=True, translate=True)
|
||||
value_ids = fields.One2many('product.attribute.value', 'attribute_id', 'Values', copy=True)
|
||||
sequence = fields.Integer('Sequence', help="Determine the display order", index=True, default=20)
|
||||
attribute_line_ids = fields.One2many('product.template.attribute.line', 'attribute_id', 'Lines')
|
||||
create_variant = fields.Selection([
|
||||
('always', 'Instantly'),
|
||||
('dynamic', 'Dynamically'),
|
||||
('no_variant', 'Never (option)')],
|
||||
_check_multi_checkbox_no_variant = models.Constraint(
|
||||
"CHECK(display_type != 'multi' OR create_variant = 'no_variant')",
|
||||
'Multi-checkbox display type is not compatible with the creation of variants',
|
||||
)
|
||||
|
||||
name = fields.Char(string="Attribute", required=True, translate=True)
|
||||
active = fields.Boolean(
|
||||
default=True,
|
||||
help="If unchecked, it will allow you to hide the attribute without removing it.",
|
||||
)
|
||||
create_variant = fields.Selection(
|
||||
selection=[
|
||||
('always', 'Instantly'),
|
||||
('dynamic', 'Dynamically'),
|
||||
('no_variant', 'Never'),
|
||||
],
|
||||
default='always',
|
||||
string="Variants Creation Mode",
|
||||
string="Variant Creation",
|
||||
help="""- Instantly: All possible variants are created as soon as the attribute and its values are added to a product.
|
||||
- Dynamically: Each variant is created only when its corresponding attributes and values are added to a sales order.
|
||||
- Never: Variants are never created for the attribute.
|
||||
Note: the variants creation mode cannot be changed once the attribute is used on at least one product.""",
|
||||
Note: this cannot be changed once the attribute is used on a product.""",
|
||||
required=True)
|
||||
display_type = fields.Selection(
|
||||
selection=[
|
||||
('radio', 'Radio'),
|
||||
('pills', 'Pills'),
|
||||
('select', 'Select'),
|
||||
('color', 'Color'),
|
||||
('multi', 'Multi-checkbox'),
|
||||
('image', 'Image'),
|
||||
],
|
||||
default='radio',
|
||||
required=True,
|
||||
help="The display type used in the Product Configurator.")
|
||||
sequence = fields.Integer(string="Sequence", help="Determine the display order", index=True, default=20)
|
||||
|
||||
value_ids = fields.One2many(
|
||||
comodel_name='product.attribute.value',
|
||||
inverse_name='attribute_id',
|
||||
string="Values", copy=True)
|
||||
template_value_ids = fields.One2many(
|
||||
comodel_name='product.template.attribute.value',
|
||||
inverse_name='attribute_id',
|
||||
string="Template Values")
|
||||
attribute_line_ids = fields.One2many(
|
||||
comodel_name='product.template.attribute.line',
|
||||
inverse_name='attribute_id',
|
||||
string="Lines")
|
||||
product_tmpl_ids = fields.Many2many(
|
||||
comodel_name='product.template',
|
||||
string="Related Products",
|
||||
compute='_compute_products',
|
||||
store=True)
|
||||
number_related_products = fields.Integer(compute='_compute_number_related_products')
|
||||
product_tmpl_ids = fields.Many2many('product.template', string="Related Products", compute='_compute_products', store=True)
|
||||
display_type = fields.Selection([
|
||||
('radio', 'Radio'),
|
||||
('pills', 'Pills'),
|
||||
('select', 'Select'),
|
||||
('color', 'Color')], default='radio', required=True, help="The display type used in the Product Configurator.")
|
||||
|
||||
# === COMPUTE METHODS === #
|
||||
|
||||
@api.depends('product_tmpl_ids')
|
||||
def _compute_number_related_products(self):
|
||||
res = {
|
||||
attribute.id: count
|
||||
for attribute, count in self.env['product.template.attribute.line']._read_group(
|
||||
domain=[('attribute_id', 'in', self.ids), ('product_tmpl_id.active', '=', 'True')],
|
||||
groupby=['attribute_id'],
|
||||
aggregates=['__count'],
|
||||
)
|
||||
}
|
||||
for pa in self:
|
||||
pa.number_related_products = len(pa.product_tmpl_ids)
|
||||
pa.number_related_products = res.get(pa.id, 0)
|
||||
|
||||
@api.depends('attribute_line_ids.active', 'attribute_line_ids.product_tmpl_id')
|
||||
def _compute_products(self):
|
||||
templates_by_attribute = {
|
||||
attribute.id: templates
|
||||
for attribute, templates in self.env['product.template.attribute.line']._read_group(
|
||||
domain=[('attribute_id', 'in', self.ids)],
|
||||
groupby=['attribute_id'],
|
||||
aggregates=['product_tmpl_id:recordset']
|
||||
)
|
||||
}
|
||||
for pa in self:
|
||||
pa.with_context(active_test=False).product_tmpl_ids = pa.attribute_line_ids.product_tmpl_id
|
||||
pa.with_context(active_test=False).product_tmpl_ids = templates_by_attribute.get(pa.id, False)
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda pa: pa.create_variant != 'no_variant')
|
||||
# === ONCHANGE METHODS === #
|
||||
|
||||
@api.onchange('display_type')
|
||||
def _onchange_display_type(self):
|
||||
if self.display_type == 'multi' and self.number_related_products == 0:
|
||||
self.create_variant = 'no_variant'
|
||||
|
||||
# === CRUD METHODS === #
|
||||
|
||||
def write(self, vals):
|
||||
"""Override to make sure attribute type can't be changed if it's used on
|
||||
|
|
@ -62,12 +115,14 @@ class ProductAttribute(models.Model):
|
|||
if 'create_variant' in vals:
|
||||
for pa in self:
|
||||
if vals['create_variant'] != pa.create_variant and pa.number_related_products:
|
||||
raise UserError(
|
||||
_("You cannot change the Variants Creation Mode of the attribute %s because it is used on the following products:\n%s") %
|
||||
(pa.display_name, ", ".join(pa.product_tmpl_ids.mapped('display_name')))
|
||||
)
|
||||
raise UserError(_(
|
||||
"You cannot change the Variants Creation Mode of the attribute %(attribute)s"
|
||||
" because it is used on the following products:\n%(products)s",
|
||||
attribute=pa.display_name,
|
||||
products=", ".join(pa.product_tmpl_ids.mapped('display_name')),
|
||||
))
|
||||
invalidate = 'sequence' in vals and any(record.sequence != vals['sequence'] for record in self)
|
||||
res = super(ProductAttribute, self).write(vals)
|
||||
res = super().write(vals)
|
||||
if invalidate:
|
||||
# prefetched o2m have to be resequenced
|
||||
# (eg. product.template: attribute_line_ids)
|
||||
|
|
@ -79,566 +134,35 @@ class ProductAttribute(models.Model):
|
|||
def _unlink_except_used_on_product(self):
|
||||
for pa in self:
|
||||
if pa.number_related_products:
|
||||
raise UserError(
|
||||
_("You cannot delete the attribute %s because it is used on the following products:\n%s") %
|
||||
(pa.display_name, ", ".join(pa.product_tmpl_ids.mapped('display_name')))
|
||||
)
|
||||
|
||||
def action_open_related_products(self):
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _("Related Products"),
|
||||
'res_model': 'product.template',
|
||||
'view_mode': 'tree,form',
|
||||
'domain': [('id', 'in', self.with_context(active_test=False).product_tmpl_ids.ids)],
|
||||
}
|
||||
|
||||
|
||||
class ProductAttributeValue(models.Model):
|
||||
_name = "product.attribute.value"
|
||||
# if you change this _order, keep it in sync with the method
|
||||
# `_sort_key_variant` in `product.template'
|
||||
_order = 'attribute_id, sequence, id'
|
||||
_description = 'Attribute Value'
|
||||
|
||||
def _get_default_color(self):
|
||||
return randint(1, 11)
|
||||
|
||||
name = fields.Char(string='Value', required=True, translate=True)
|
||||
sequence = fields.Integer(string='Sequence', help="Determine the display order", index=True)
|
||||
attribute_id = fields.Many2one('product.attribute', string="Attribute", ondelete='cascade', required=True, index=True,
|
||||
help="The attribute cannot be changed once the value is used on at least one product.")
|
||||
|
||||
pav_attribute_line_ids = fields.Many2many('product.template.attribute.line', string="Lines",
|
||||
relation='product_attribute_value_product_template_attribute_line_rel', copy=False)
|
||||
is_used_on_products = fields.Boolean('Used on Products', compute='_compute_is_used_on_products')
|
||||
|
||||
is_custom = fields.Boolean('Is custom value', help="Allow users to input custom values for this attribute value")
|
||||
html_color = fields.Char(
|
||||
string='Color',
|
||||
help="Here you can set a specific HTML color index (e.g. #ff0000) to display the color if the attribute type is 'Color'.")
|
||||
display_type = fields.Selection(related='attribute_id.display_type', readonly=True)
|
||||
color = fields.Integer('Color Index', default=_get_default_color)
|
||||
|
||||
_sql_constraints = [
|
||||
('value_company_uniq', 'unique (name, attribute_id)', "You cannot create two values with the same name for the same attribute.")
|
||||
]
|
||||
|
||||
@api.depends('pav_attribute_line_ids')
|
||||
def _compute_is_used_on_products(self):
|
||||
for pav in self:
|
||||
pav.is_used_on_products = bool(pav.pav_attribute_line_ids)
|
||||
|
||||
def name_get(self):
|
||||
"""Override because in general the name of the value is confusing if it
|
||||
is displayed without the name of the corresponding attribute.
|
||||
Eg. on product list & kanban views, on BOM form view
|
||||
|
||||
However during variant set up (on the product template form) the name of
|
||||
the attribute is already on each line so there is no need to repeat it
|
||||
on every value.
|
||||
"""
|
||||
if not self._context.get('show_attribute', True):
|
||||
return super(ProductAttributeValue, self).name_get()
|
||||
return [(value.id, "%s: %s" % (value.attribute_id.name, value.name)) for value in self]
|
||||
|
||||
def write(self, values):
|
||||
if 'attribute_id' in values:
|
||||
for pav in self:
|
||||
if pav.attribute_id.id != values['attribute_id'] and pav.is_used_on_products:
|
||||
raise UserError(
|
||||
_("You cannot change the attribute of the value %s because it is used on the following products:%s") %
|
||||
(pav.display_name, ", ".join(pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')))
|
||||
)
|
||||
|
||||
invalidate = 'sequence' in values and any(record.sequence != values['sequence'] for record in self)
|
||||
res = super(ProductAttributeValue, self).write(values)
|
||||
if invalidate:
|
||||
# prefetched o2m have to be resequenced
|
||||
# (eg. product.template.attribute.line: value_ids)
|
||||
self.env.flush_all()
|
||||
self.env.invalidate_all()
|
||||
return res
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_except_used_on_product(self):
|
||||
for pav in self:
|
||||
if pav.is_used_on_products:
|
||||
raise UserError(
|
||||
_("You cannot delete the value %s because it is used on the following products:"
|
||||
"\n%s\n If the value has been associated to a product in the past, you will "
|
||||
"not be able to delete it.") %
|
||||
(pav.display_name, ", ".join(
|
||||
pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')
|
||||
))
|
||||
)
|
||||
linked_products = pav.env['product.template.attribute.value'].search(
|
||||
[('product_attribute_value_id', '=', pav.id)]
|
||||
).with_context(active_test=False).ptav_product_variant_ids
|
||||
unlinkable_products = linked_products._filter_to_unlink()
|
||||
if linked_products != unlinkable_products:
|
||||
raise UserError(_(
|
||||
"You cannot delete value %s because it was used in some products.",
|
||||
pav.display_name
|
||||
"You cannot delete the attribute %(attribute)s because it is used on the"
|
||||
" following products:\n%(products)s",
|
||||
attribute=pa.display_name,
|
||||
products=", ".join(pa.product_tmpl_ids.mapped('display_name')),
|
||||
))
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda pav: pav.attribute_id.create_variant != 'no_variant')
|
||||
# === ACTION METHODS === #
|
||||
|
||||
def action_archive(self):
|
||||
for attribute in self:
|
||||
if attribute.number_related_products:
|
||||
raise UserError(_(
|
||||
"You cannot archive this attribute as there are still products linked to it",
|
||||
))
|
||||
return super().action_archive()
|
||||
|
||||
class ProductTemplateAttributeLine(models.Model):
|
||||
"""Attributes available on product.template with their selected values in a m2m.
|
||||
Used as a configuration model to generate the appropriate product.template.attribute.value"""
|
||||
|
||||
_name = "product.template.attribute.line"
|
||||
_rec_name = 'attribute_id'
|
||||
_rec_names_search = ['attribute_id', 'value_ids']
|
||||
_description = 'Product Template Attribute Line'
|
||||
_order = 'attribute_id, id'
|
||||
|
||||
active = fields.Boolean(default=True)
|
||||
product_tmpl_id = fields.Many2one('product.template', string="Product Template", ondelete='cascade', required=True, index=True)
|
||||
attribute_id = fields.Many2one('product.attribute', string="Attribute", ondelete='restrict', required=True, index=True)
|
||||
value_ids = fields.Many2many('product.attribute.value', string="Values", domain="[('attribute_id', '=', attribute_id)]",
|
||||
relation='product_attribute_value_product_template_attribute_line_rel', ondelete='restrict')
|
||||
value_count = fields.Integer(compute='_compute_value_count', store=True, readonly=True)
|
||||
product_template_value_ids = fields.One2many('product.template.attribute.value', 'attribute_line_id', string="Product Attribute Values")
|
||||
|
||||
@api.depends('value_ids')
|
||||
def _compute_value_count(self):
|
||||
for record in self:
|
||||
record.value_count = len(record.value_ids)
|
||||
|
||||
@api.onchange('attribute_id')
|
||||
def _onchange_attribute_id(self):
|
||||
self.value_ids = self.value_ids.filtered(lambda pav: pav.attribute_id == self.attribute_id)
|
||||
|
||||
@api.constrains('active', 'value_ids', 'attribute_id')
|
||||
def _check_valid_values(self):
|
||||
for ptal in self:
|
||||
if ptal.active and not ptal.value_ids:
|
||||
raise ValidationError(
|
||||
_("The attribute %s must have at least one value for the product %s.") %
|
||||
(ptal.attribute_id.display_name, ptal.product_tmpl_id.display_name)
|
||||
)
|
||||
for pav in ptal.value_ids:
|
||||
if pav.attribute_id != ptal.attribute_id:
|
||||
raise ValidationError(
|
||||
_("On the product %s you cannot associate the value %s with the attribute %s because they do not match.") %
|
||||
(ptal.product_tmpl_id.display_name, pav.display_name, ptal.attribute_id.display_name)
|
||||
)
|
||||
return True
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
"""Override to:
|
||||
- Activate archived lines having the same configuration (if they exist)
|
||||
instead of creating new lines.
|
||||
- Set up related values and related variants.
|
||||
|
||||
Reactivating existing lines allows to re-use existing variants when
|
||||
possible, keeping their configuration and avoiding duplication.
|
||||
"""
|
||||
create_values = []
|
||||
activated_lines = self.env['product.template.attribute.line']
|
||||
for value in vals_list:
|
||||
vals = dict(value, active=value.get('active', True))
|
||||
# While not ideal for peformance, this search has to be done at each
|
||||
# step to exclude the lines that might have been activated at a
|
||||
# previous step. Since `vals_list` will likely be a small list in
|
||||
# all use cases, this is an acceptable trade-off.
|
||||
archived_ptal = self.search([
|
||||
('active', '=', False),
|
||||
('product_tmpl_id', '=', vals.pop('product_tmpl_id', 0)),
|
||||
('attribute_id', '=', vals.pop('attribute_id', 0)),
|
||||
], limit=1)
|
||||
if archived_ptal:
|
||||
# Write given `vals` in addition of `active` to ensure
|
||||
# `value_ids` or other fields passed to `create` are saved too,
|
||||
# but change the context to avoid updating the values and the
|
||||
# variants until all the expected lines are created/updated.
|
||||
archived_ptal.with_context(update_product_template_attribute_values=False).write(vals)
|
||||
activated_lines += archived_ptal
|
||||
else:
|
||||
create_values.append(value)
|
||||
res = activated_lines + super(ProductTemplateAttributeLine, self).create(create_values)
|
||||
res._update_product_template_attribute_values()
|
||||
return res
|
||||
|
||||
def write(self, values):
|
||||
"""Override to:
|
||||
- Add constraints to prevent doing changes that are not supported such
|
||||
as modifying the template or the attribute of existing lines.
|
||||
- Clean up related values and related variants when archiving or when
|
||||
updating `value_ids`.
|
||||
"""
|
||||
if 'product_tmpl_id' in values:
|
||||
for ptal in self:
|
||||
if ptal.product_tmpl_id.id != values['product_tmpl_id']:
|
||||
raise UserError(
|
||||
_("You cannot move the attribute %s from the product %s to the product %s.") %
|
||||
(ptal.attribute_id.display_name, ptal.product_tmpl_id.display_name, values['product_tmpl_id'])
|
||||
)
|
||||
|
||||
if 'attribute_id' in values:
|
||||
for ptal in self:
|
||||
if ptal.attribute_id.id != values['attribute_id']:
|
||||
raise UserError(
|
||||
_("On the product %s you cannot transform the attribute %s into the attribute %s.") %
|
||||
(ptal.product_tmpl_id.display_name, ptal.attribute_id.display_name, values['attribute_id'])
|
||||
)
|
||||
# Remove all values while archiving to make sure the line is clean if it
|
||||
# is ever activated again.
|
||||
if not values.get('active', True):
|
||||
values['value_ids'] = [(5, 0, 0)]
|
||||
res = super(ProductTemplateAttributeLine, self).write(values)
|
||||
if 'active' in values:
|
||||
self.env.flush_all()
|
||||
self.env['product.template'].invalidate_model(['attribute_line_ids'])
|
||||
# If coming from `create`, no need to update the values and the variants
|
||||
# before all lines are created.
|
||||
if self.env.context.get('update_product_template_attribute_values', True):
|
||||
self._update_product_template_attribute_values()
|
||||
return res
|
||||
|
||||
def unlink(self):
|
||||
"""Override to:
|
||||
- Archive the line if unlink is not possible.
|
||||
- Clean up related values and related variants.
|
||||
|
||||
Archiving is typically needed when the line has values that can't be
|
||||
deleted because they are referenced elsewhere (on a variant that can't
|
||||
be deleted, on a sales order line, ...).
|
||||
"""
|
||||
# Try to remove the values first to remove some potentially blocking
|
||||
# references, which typically works:
|
||||
# - For single value lines because the values are directly removed from
|
||||
# the variants.
|
||||
# - For values that are present on variants that can be deleted.
|
||||
self.product_template_value_ids._only_active().unlink()
|
||||
# Keep a reference to the related templates before the deletion.
|
||||
templates = self.product_tmpl_id
|
||||
# Now delete or archive the lines.
|
||||
ptal_to_archive = self.env['product.template.attribute.line']
|
||||
for ptal in self:
|
||||
try:
|
||||
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
|
||||
super(ProductTemplateAttributeLine, ptal).unlink()
|
||||
except Exception:
|
||||
# We catch all kind of exceptions to be sure that the operation
|
||||
# doesn't fail.
|
||||
ptal_to_archive += ptal
|
||||
ptal_to_archive.action_archive() # only calls write if there are records
|
||||
# For archived lines `_update_product_template_attribute_values` is
|
||||
# implicitly called during the `write` above, but for products that used
|
||||
# unlinked lines `_create_variant_ids` has to be called manually.
|
||||
(templates - ptal_to_archive.product_tmpl_id)._create_variant_ids()
|
||||
return True
|
||||
|
||||
def _update_product_template_attribute_values(self):
|
||||
"""Create or unlink `product.template.attribute.value` for each line in
|
||||
`self` based on `value_ids`.
|
||||
|
||||
The goal is to delete all values that are not in `value_ids`, to
|
||||
activate those in `value_ids` that are currently archived, and to create
|
||||
those in `value_ids` that didn't exist.
|
||||
|
||||
This is a trick for the form view and for performance in general,
|
||||
because we don't want to generate in advance all possible values for all
|
||||
templates, but only those that will be selected.
|
||||
"""
|
||||
ProductTemplateAttributeValue = self.env['product.template.attribute.value']
|
||||
ptav_to_create = []
|
||||
ptav_to_unlink = ProductTemplateAttributeValue
|
||||
for ptal in self:
|
||||
ptav_to_activate = ProductTemplateAttributeValue
|
||||
remaining_pav = ptal.value_ids
|
||||
for ptav in ptal.product_template_value_ids:
|
||||
if ptav.product_attribute_value_id not in remaining_pav:
|
||||
# Remove values that existed but don't exist anymore, but
|
||||
# ignore those that are already archived because if they are
|
||||
# archived it means they could not be deleted previously.
|
||||
if ptav.ptav_active:
|
||||
ptav_to_unlink += ptav
|
||||
else:
|
||||
# Activate corresponding values that are currently archived.
|
||||
remaining_pav -= ptav.product_attribute_value_id
|
||||
if not ptav.ptav_active:
|
||||
ptav_to_activate += ptav
|
||||
|
||||
for pav in remaining_pav:
|
||||
# The previous loop searched for archived values that belonged to
|
||||
# the current line, but if the line was deleted and another line
|
||||
# was recreated for the same attribute, we need to expand the
|
||||
# search to those with matching `attribute_id`.
|
||||
# While not ideal for peformance, this search has to be done at
|
||||
# each step to exclude the values that might have been activated
|
||||
# at a previous step. Since `remaining_pav` will likely be a
|
||||
# small list in all use cases, this is an acceptable trade-off.
|
||||
ptav = ProductTemplateAttributeValue.search([
|
||||
('ptav_active', '=', False),
|
||||
('product_tmpl_id', '=', ptal.product_tmpl_id.id),
|
||||
('attribute_id', '=', ptal.attribute_id.id),
|
||||
('product_attribute_value_id', '=', pav.id),
|
||||
], limit=1)
|
||||
if ptav:
|
||||
ptav.write({'ptav_active': True, 'attribute_line_id': ptal.id})
|
||||
# If the value was marked for deletion, now keep it.
|
||||
ptav_to_unlink -= ptav
|
||||
else:
|
||||
# create values that didn't exist yet
|
||||
ptav_to_create.append({
|
||||
'product_attribute_value_id': pav.id,
|
||||
'attribute_line_id': ptal.id
|
||||
})
|
||||
# Handle active at each step in case a following line might want to
|
||||
# re-use a value that was archived at a previous step.
|
||||
ptav_to_activate.write({'ptav_active': True})
|
||||
ptav_to_unlink.write({'ptav_active': False})
|
||||
if ptav_to_unlink:
|
||||
ptav_to_unlink.unlink()
|
||||
ProductTemplateAttributeValue.create(ptav_to_create)
|
||||
self.product_tmpl_id._create_variant_ids()
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda ptal: ptal.attribute_id.create_variant != 'no_variant')
|
||||
|
||||
def action_open_attribute_values(self):
|
||||
@api.readonly
|
||||
def action_open_product_template_attribute_lines(self):
|
||||
self.ensure_one()
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _("Product Variant Values"),
|
||||
'res_model': 'product.template.attribute.value',
|
||||
'view_mode': 'tree,form',
|
||||
'domain': [('id', 'in', self.product_template_value_ids.ids)],
|
||||
'views': [
|
||||
(self.env.ref('product.product_template_attribute_value_view_tree').id, 'list'),
|
||||
(self.env.ref('product.product_template_attribute_value_view_form').id, 'form'),
|
||||
],
|
||||
'context': {
|
||||
'search_default_active': 1,
|
||||
},
|
||||
'name': _("Products"),
|
||||
'res_model': 'product.template.attribute.line',
|
||||
'view_mode': 'list,form',
|
||||
'domain': [('attribute_id', '=', self.id), ('product_tmpl_id.active', '=', 'True')],
|
||||
}
|
||||
|
||||
|
||||
class ProductTemplateAttributeValue(models.Model):
|
||||
"""Materialized relationship between attribute values
|
||||
and product template generated by the product.template.attribute.line"""
|
||||
|
||||
_name = "product.template.attribute.value"
|
||||
_description = "Product Template Attribute Value"
|
||||
_order = 'attribute_line_id, product_attribute_value_id, id'
|
||||
|
||||
def _get_default_color(self):
|
||||
return randint(1, 11)
|
||||
|
||||
# Not just `active` because we always want to show the values except in
|
||||
# specific case, as opposed to `active_test`.
|
||||
ptav_active = fields.Boolean("Active", default=True)
|
||||
name = fields.Char('Value', related="product_attribute_value_id.name")
|
||||
|
||||
# defining fields: the product template attribute line and the product attribute value
|
||||
product_attribute_value_id = fields.Many2one(
|
||||
'product.attribute.value', string='Attribute Value',
|
||||
required=True, ondelete='cascade', index=True)
|
||||
attribute_line_id = fields.Many2one('product.template.attribute.line', required=True, ondelete='cascade', index=True)
|
||||
# configuration fields: the price_extra and the exclusion rules
|
||||
price_extra = fields.Float(
|
||||
string="Value Price Extra",
|
||||
default=0.0,
|
||||
digits='Product Price',
|
||||
help="Extra price for the variant with this attribute value on sale price. eg. 200 price extra, 1000 + 200 = 1200.")
|
||||
currency_id = fields.Many2one(related='attribute_line_id.product_tmpl_id.currency_id')
|
||||
|
||||
exclude_for = fields.One2many(
|
||||
'product.template.attribute.exclusion',
|
||||
'product_template_attribute_value_id',
|
||||
string="Exclude for",
|
||||
help="Make this attribute value not compatible with "
|
||||
"other values of the product or some attribute values of optional and accessory products.")
|
||||
|
||||
# related fields: product template and product attribute
|
||||
product_tmpl_id = fields.Many2one('product.template', string="Product Template", related='attribute_line_id.product_tmpl_id', store=True, index=True)
|
||||
attribute_id = fields.Many2one('product.attribute', string="Attribute", related='attribute_line_id.attribute_id', store=True, index=True)
|
||||
ptav_product_variant_ids = fields.Many2many('product.product', relation='product_variant_combination', string="Related Variants", readonly=True)
|
||||
|
||||
html_color = fields.Char('HTML Color Index', related="product_attribute_value_id.html_color")
|
||||
is_custom = fields.Boolean('Is custom value', related="product_attribute_value_id.is_custom")
|
||||
display_type = fields.Selection(related='product_attribute_value_id.display_type', readonly=True)
|
||||
color = fields.Integer('Color', default=_get_default_color)
|
||||
|
||||
_sql_constraints = [
|
||||
('attribute_value_unique', 'unique(attribute_line_id, product_attribute_value_id)', "Each value should be defined only once per attribute per product."),
|
||||
]
|
||||
|
||||
@api.constrains('attribute_line_id', 'product_attribute_value_id')
|
||||
def _check_valid_values(self):
|
||||
for ptav in self:
|
||||
if ptav.product_attribute_value_id not in ptav.attribute_line_id.value_ids:
|
||||
raise ValidationError(
|
||||
_("The value %s is not defined for the attribute %s on the product %s.") %
|
||||
(ptav.product_attribute_value_id.display_name, ptav.attribute_id.display_name, ptav.product_tmpl_id.display_name)
|
||||
)
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
if any('ptav_product_variant_ids' in v for v in vals_list):
|
||||
# Force write on this relation from `product.product` to properly
|
||||
# trigger `_compute_combination_indices`.
|
||||
raise UserError(_("You cannot update related variants from the values. Please update related values from the variants."))
|
||||
return super(ProductTemplateAttributeValue, self).create(vals_list)
|
||||
|
||||
def write(self, values):
|
||||
if 'ptav_product_variant_ids' in values:
|
||||
# Force write on this relation from `product.product` to properly
|
||||
# trigger `_compute_combination_indices`.
|
||||
raise UserError(_("You cannot update related variants from the values. Please update related values from the variants."))
|
||||
pav_in_values = 'product_attribute_value_id' in values
|
||||
product_in_values = 'product_tmpl_id' in values
|
||||
if pav_in_values or product_in_values:
|
||||
for ptav in self:
|
||||
if pav_in_values and ptav.product_attribute_value_id.id != values['product_attribute_value_id']:
|
||||
raise UserError(
|
||||
_("You cannot change the value of the value %s set on product %s.") %
|
||||
(ptav.display_name, ptav.product_tmpl_id.display_name)
|
||||
)
|
||||
if product_in_values and ptav.product_tmpl_id.id != values['product_tmpl_id']:
|
||||
raise UserError(
|
||||
_("You cannot change the product of the value %s set on product %s.") %
|
||||
(ptav.display_name, ptav.product_tmpl_id.display_name)
|
||||
)
|
||||
res = super(ProductTemplateAttributeValue, self).write(values)
|
||||
if 'exclude_for' in values:
|
||||
self.product_tmpl_id._create_variant_ids()
|
||||
return res
|
||||
|
||||
def unlink(self):
|
||||
"""Override to:
|
||||
- Clean up the variants that use any of the values in self:
|
||||
- Remove the value from the variant if the value belonged to an
|
||||
attribute line with only one value.
|
||||
- Unlink or archive all related variants.
|
||||
- Archive the value if unlink is not possible.
|
||||
|
||||
Archiving is typically needed when the value is referenced elsewhere
|
||||
(on a variant that can't be deleted, on a sales order line, ...).
|
||||
"""
|
||||
# Directly remove the values from the variants for lines that had single
|
||||
# value (counting also the values that are archived).
|
||||
single_values = self.filtered(lambda ptav: len(ptav.attribute_line_id.product_template_value_ids) == 1)
|
||||
for ptav in single_values:
|
||||
ptav.ptav_product_variant_ids.write({'product_template_attribute_value_ids': [(3, ptav.id, 0)]})
|
||||
# Try to remove the variants before deleting to potentially remove some
|
||||
# blocking references.
|
||||
self.ptav_product_variant_ids._unlink_or_archive()
|
||||
# Now delete or archive the values.
|
||||
ptav_to_archive = self.env['product.template.attribute.value']
|
||||
for ptav in self:
|
||||
try:
|
||||
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
|
||||
super(ProductTemplateAttributeValue, ptav).unlink()
|
||||
except Exception:
|
||||
# We catch all kind of exceptions to be sure that the operation
|
||||
# doesn't fail.
|
||||
ptav_to_archive += ptav
|
||||
ptav_to_archive.write({'ptav_active': False})
|
||||
return True
|
||||
|
||||
def name_get(self):
|
||||
"""Override because in general the name of the value is confusing if it
|
||||
is displayed without the name of the corresponding attribute.
|
||||
Eg. on exclusion rules form
|
||||
"""
|
||||
return [(value.id, "%s: %s" % (value.attribute_id.name, value.name)) for value in self]
|
||||
|
||||
def _only_active(self):
|
||||
return self.filtered(lambda ptav: ptav.ptav_active)
|
||||
# === TOOLING === #
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda ptav: ptav.attribute_id.create_variant != 'no_variant')
|
||||
|
||||
def _ids2str(self):
|
||||
return ','.join([str(i) for i in sorted(self.ids)])
|
||||
|
||||
def _get_combination_name(self):
|
||||
"""Exclude values from single value lines or from no_variant attributes."""
|
||||
ptavs = self._without_no_variant_attributes().with_prefetch(self._prefetch_ids)
|
||||
ptavs = ptavs._filter_single_value_lines().with_prefetch(self._prefetch_ids)
|
||||
return ", ".join([ptav.name for ptav in ptavs])
|
||||
|
||||
def _filter_single_value_lines(self):
|
||||
"""Return `self` with values from single value lines filtered out
|
||||
depending on the active state of all the values in `self`.
|
||||
|
||||
If any value in `self` is archived, archived values are also taken into
|
||||
account when checking for single values.
|
||||
This allows to display the correct name for archived variants.
|
||||
|
||||
If all values in `self` are active, only active values are taken into
|
||||
account when checking for single values.
|
||||
This allows to display the correct name for active combinations.
|
||||
"""
|
||||
only_active = all(ptav.ptav_active for ptav in self)
|
||||
return self.filtered(lambda ptav: not ptav._is_from_single_value_line(only_active))
|
||||
|
||||
def _is_from_single_value_line(self, only_active=True):
|
||||
"""Return whether `self` is from a single value line, counting also
|
||||
archived values if `only_active` is False.
|
||||
"""
|
||||
self.ensure_one()
|
||||
all_values = self.attribute_line_id.product_template_value_ids
|
||||
if only_active:
|
||||
all_values = all_values._only_active()
|
||||
return len(all_values) == 1
|
||||
|
||||
|
||||
class ProductTemplateAttributeExclusion(models.Model):
|
||||
_name = "product.template.attribute.exclusion"
|
||||
_description = 'Product Template Attribute Exclusion'
|
||||
_order = 'product_tmpl_id, id'
|
||||
|
||||
product_template_attribute_value_id = fields.Many2one(
|
||||
'product.template.attribute.value', string="Attribute Value", ondelete='cascade', index=True)
|
||||
product_tmpl_id = fields.Many2one(
|
||||
'product.template', string='Product Template', ondelete='cascade', required=True, index=True)
|
||||
value_ids = fields.Many2many(
|
||||
'product.template.attribute.value', relation="product_attr_exclusion_value_ids_rel",
|
||||
string='Attribute Values', domain="[('product_tmpl_id', '=', product_tmpl_id), ('ptav_active', '=', True)]")
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
exclusions = super().create(vals_list)
|
||||
exclusions.product_tmpl_id._create_variant_ids()
|
||||
return exclusions
|
||||
|
||||
def unlink(self):
|
||||
# Keep a reference to the related templates before the deletion.
|
||||
templates = self.product_tmpl_id
|
||||
res = super().unlink()
|
||||
templates._create_variant_ids()
|
||||
return res
|
||||
|
||||
def write(self, values):
|
||||
templates = self.env['product.template']
|
||||
if 'product_tmpl_id' in values:
|
||||
templates = self.product_tmpl_id
|
||||
res = super().write(values)
|
||||
(templates | self.product_tmpl_id)._create_variant_ids()
|
||||
return res
|
||||
|
||||
|
||||
class ProductAttributeCustomValue(models.Model):
|
||||
_name = "product.attribute.custom.value"
|
||||
_description = 'Product Attribute Custom Value'
|
||||
_order = 'custom_product_template_attribute_value_id, id'
|
||||
|
||||
name = fields.Char("Name", compute='_compute_name')
|
||||
custom_product_template_attribute_value_id = fields.Many2one('product.template.attribute.value', string="Attribute Value", required=True, ondelete='restrict')
|
||||
custom_value = fields.Char("Custom Value")
|
||||
|
||||
@api.depends('custom_product_template_attribute_value_id.name', 'custom_value')
|
||||
def _compute_name(self):
|
||||
for record in self:
|
||||
name = (record.custom_value or '').strip()
|
||||
if record.custom_product_template_attribute_value_id.display_name:
|
||||
name = "%s: %s" % (record.custom_product_template_attribute_value_id.display_name, name)
|
||||
record.name = name
|
||||
return self.filtered(lambda pa: pa.create_variant != 'no_variant')
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class ProductAttributeCustomValue(models.Model):
|
||||
_name = 'product.attribute.custom.value'
|
||||
_description = "Product Attribute Custom Value"
|
||||
_order = 'custom_product_template_attribute_value_id, id'
|
||||
|
||||
name = fields.Char(string="Name", compute='_compute_name')
|
||||
custom_product_template_attribute_value_id = fields.Many2one(
|
||||
comodel_name='product.template.attribute.value',
|
||||
string="Attribute Value",
|
||||
required=True,
|
||||
ondelete='restrict')
|
||||
custom_value = fields.Char(string="Custom Value")
|
||||
|
||||
@api.depends('custom_product_template_attribute_value_id.name', 'custom_value')
|
||||
def _compute_name(self):
|
||||
for record in self:
|
||||
name = (record.custom_value or '').strip()
|
||||
if record.custom_product_template_attribute_value_id.display_name:
|
||||
name = "%s: %s" % (record.custom_product_template_attribute_value_id.display_name, name)
|
||||
record.name = name
|
||||
|
|
@ -0,0 +1,180 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from random import randint
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class ProductAttributeValue(models.Model):
|
||||
# if you change this _order, keep it in sync with the method
|
||||
# `_sort_key_variant` in `product.template'
|
||||
_name = 'product.attribute.value'
|
||||
_order = 'attribute_id, sequence, id'
|
||||
_description = "Attribute Value"
|
||||
|
||||
def _get_default_color(self):
|
||||
return randint(1, 11)
|
||||
|
||||
name = fields.Char(string="Value", required=True, translate=True)
|
||||
sequence = fields.Integer(string="Sequence", help="Determine the display order", index=True)
|
||||
attribute_id = fields.Many2one(
|
||||
comodel_name='product.attribute',
|
||||
string="Attribute",
|
||||
help="The attribute cannot be changed once the value is used on at least one product.",
|
||||
ondelete='cascade',
|
||||
required=True,
|
||||
index=True)
|
||||
|
||||
pav_attribute_line_ids = fields.Many2many(
|
||||
comodel_name='product.template.attribute.line',
|
||||
relation='product_attribute_value_product_template_attribute_line_rel',
|
||||
string="Lines",
|
||||
copy=False)
|
||||
|
||||
default_extra_price = fields.Float()
|
||||
is_custom = fields.Boolean(
|
||||
string="Free text",
|
||||
help="Allow customers to set their own value")
|
||||
html_color = fields.Char(
|
||||
string="Color",
|
||||
help="Here you can set a specific HTML color index (e.g. #ff0000)"
|
||||
" to display the color if the attribute type is 'Color'.")
|
||||
display_type = fields.Selection(related='attribute_id.display_type')
|
||||
color = fields.Integer(string="Color Index", default=_get_default_color)
|
||||
image = fields.Image(
|
||||
string="Image",
|
||||
help="You can upload an image that will be used as the color of the attribute value.",
|
||||
max_width=70,
|
||||
max_height=70,
|
||||
)
|
||||
active = fields.Boolean(default=True)
|
||||
|
||||
is_used_on_products = fields.Boolean(
|
||||
string="Used on Products", compute='_compute_is_used_on_products')
|
||||
default_extra_price_changed = fields.Boolean(compute='_compute_default_extra_price_changed')
|
||||
|
||||
# === COMPUTE METHODS === #
|
||||
|
||||
@api.depends('attribute_id')
|
||||
@api.depends_context('show_attribute')
|
||||
def _compute_display_name(self):
|
||||
"""Override because in general the name of the value is confusing if it
|
||||
is displayed without the name of the corresponding attribute.
|
||||
Eg. on product list & kanban views, on BOM form view
|
||||
|
||||
However during variant set up (on the product template form) the name of
|
||||
the attribute is already on each line so there is no need to repeat it
|
||||
on every value.
|
||||
"""
|
||||
if not self.env.context.get('show_attribute', True):
|
||||
return super()._compute_display_name()
|
||||
for value in self:
|
||||
value.display_name = f"{value.attribute_id.name}: {value.name}"
|
||||
|
||||
@api.depends('pav_attribute_line_ids')
|
||||
def _compute_is_used_on_products(self):
|
||||
for pav in self:
|
||||
pav.is_used_on_products = bool(pav.pav_attribute_line_ids.filtered('product_tmpl_id.active'))
|
||||
|
||||
@api.depends('default_extra_price')
|
||||
def _compute_default_extra_price_changed(self):
|
||||
company_domain = self.env['product.template']._check_company_domain(self.env.companies)
|
||||
# `sudo` required to know which products we lack access to
|
||||
ptavs_by_pav = self.env['product.template.attribute.value'].sudo().search_fetch([
|
||||
('product_attribute_value_id', 'in', self.ids),
|
||||
('product_tmpl_id', 'any', company_domain),
|
||||
], ['price_extra', 'product_attribute_value_id']).grouped('product_attribute_value_id')
|
||||
for pav in self:
|
||||
ptavs = ptavs_by_pav.get(pav, [])
|
||||
pav.default_extra_price_changed = (
|
||||
pav.default_extra_price != pav._origin.default_extra_price
|
||||
or any(pav.default_extra_price != ptav.price_extra for ptav in ptavs)
|
||||
)
|
||||
|
||||
# === CRUD METHODS === #
|
||||
|
||||
def write(self, vals):
|
||||
if 'attribute_id' in vals:
|
||||
for pav in self:
|
||||
if pav.attribute_id.id != vals['attribute_id'] and pav.is_used_on_products:
|
||||
raise UserError(_(
|
||||
"You cannot change the attribute of the value %(value)s because it is used"
|
||||
" on the following products: %(products)s",
|
||||
value=pav.display_name,
|
||||
products=", ".join(pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')),
|
||||
))
|
||||
|
||||
invalidate = 'sequence' in vals and any(record.sequence != vals['sequence'] for record in self)
|
||||
res = super().write(vals)
|
||||
if invalidate:
|
||||
# prefetched o2m have to be resequenced
|
||||
# (eg. product.template.attribute.line: value_ids)
|
||||
self.env.flush_all()
|
||||
self.env.invalidate_all()
|
||||
return res
|
||||
|
||||
def check_is_used_on_products(self):
|
||||
for pav in self.filtered('is_used_on_products'):
|
||||
return _(
|
||||
"You cannot delete the value %(value)s because it is used on the following"
|
||||
" products:\n%(products)s\n",
|
||||
value=pav.display_name,
|
||||
products=", ".join(pav.pav_attribute_line_ids.product_tmpl_id.mapped('display_name')),
|
||||
)
|
||||
return False
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_except_used_on_product(self):
|
||||
if is_used_on_products := self.check_is_used_on_products():
|
||||
raise UserError(is_used_on_products)
|
||||
|
||||
def unlink(self):
|
||||
pavs_to_archive = self.env['product.attribute.value']
|
||||
for pav in self:
|
||||
linked_products = pav.env['product.template.attribute.value'].search(
|
||||
[('product_attribute_value_id', '=', pav.id)]
|
||||
).with_context(active_test=False).ptav_product_variant_ids
|
||||
active_linked_products = linked_products.filtered('active')
|
||||
if not active_linked_products and linked_products:
|
||||
# If product attribute value found on non-active product variants
|
||||
# archive PAV instead of deleting
|
||||
pavs_to_archive |= pav
|
||||
if pavs_to_archive:
|
||||
pavs_to_archive.action_archive()
|
||||
return super(ProductAttributeValue, self - pavs_to_archive).unlink()
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda pav: pav.attribute_id.create_variant != 'no_variant')
|
||||
|
||||
# === ACTION METHODS === #
|
||||
|
||||
@api.readonly
|
||||
def action_add_to_products(self):
|
||||
return {
|
||||
'name': _("Add to all products"),
|
||||
'type': 'ir.actions.act_window',
|
||||
'res_model': 'update.product.attribute.value',
|
||||
'view_mode': 'form',
|
||||
'target': 'new',
|
||||
'context': {
|
||||
'default_attribute_value_id': self.id,
|
||||
'default_mode': 'add',
|
||||
'dialog_size': 'medium',
|
||||
},
|
||||
}
|
||||
|
||||
@api.readonly
|
||||
def action_update_prices(self):
|
||||
return {
|
||||
'name': _("Update product extra prices"),
|
||||
'type': 'ir.actions.act_window',
|
||||
'res_model': 'update.product.attribute.value',
|
||||
'view_mode': 'form',
|
||||
'target': 'new',
|
||||
'context': {
|
||||
'default_attribute_value_id': self.id,
|
||||
'default_mode': 'update_extra_price',
|
||||
'dialog_size': 'medium',
|
||||
},
|
||||
}
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import _, api, models
|
||||
from odoo.fields import Domain
|
||||
|
||||
|
||||
class ProductCatalogMixin(models.AbstractModel):
|
||||
""" This mixin should be inherited when the model should be able to work
|
||||
with the product catalog.
|
||||
It assumes the model using this mixin has a O2M field where the products are added/removed and
|
||||
this field's co-related model should has a method named `_get_product_catalog_lines_data`.
|
||||
"""
|
||||
_name = 'product.catalog.mixin'
|
||||
_description = 'Product Catalog Mixin'
|
||||
|
||||
@api.readonly
|
||||
def action_add_from_catalog(self):
|
||||
kanban_view_id = self.env.ref('product.product_view_kanban_catalog').id
|
||||
search_view_id = self.env.ref('product.product_view_search_catalog').id
|
||||
additional_context = self._get_action_add_from_catalog_extra_context()
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _('Products'),
|
||||
'res_model': 'product.product',
|
||||
'views': [(kanban_view_id, 'kanban'), (False, 'form')],
|
||||
'search_view_id': [search_view_id, 'search'],
|
||||
'domain': self._get_product_catalog_domain(),
|
||||
'context': {**self.env.context, **additional_context},
|
||||
}
|
||||
|
||||
def _default_order_line_values(self, child_field=False):
|
||||
return {
|
||||
'quantity': 0,
|
||||
'readOnly': self._is_readonly() if self else False,
|
||||
}
|
||||
|
||||
def _get_product_catalog_domain(self) -> Domain:
|
||||
"""Get the domain to search for products in the catalog.
|
||||
|
||||
For a model that uses products that has to be hidden in the catalog, it
|
||||
must override this method and extend the appropriate domain.
|
||||
:returns: A domain.
|
||||
"""
|
||||
return (
|
||||
Domain('company_id', '=', False) | Domain('company_id', 'parent_of', self.company_id.id)
|
||||
) & Domain('type', '!=', 'combo')
|
||||
|
||||
def _get_product_catalog_record_lines(self, product_ids, **kwargs):
|
||||
""" Returns the record's lines grouped by product.
|
||||
Must be overrided by each model using this mixin.
|
||||
|
||||
:param list product_ids: The ids of the products currently displayed in the product catalog.
|
||||
:rtype: dict
|
||||
"""
|
||||
return {}
|
||||
|
||||
def _get_product_catalog_order_data(self, products, **kwargs):
|
||||
""" Returns a dict containing the products' data. Those data are for products who aren't in
|
||||
the record yet. For products already in the record, see `_get_product_catalog_lines_data`.
|
||||
|
||||
For each product, its id is the key and the value is another dict with all needed data.
|
||||
By default, the price is the only needed data but each model is free to add more data.
|
||||
Must be overrided by each model using this mixin.
|
||||
|
||||
:param products: Recordset of `product.product`.
|
||||
:param dict kwargs: additional values given for inherited models.
|
||||
:rtype: dict
|
||||
:return: A dict with the following structure:
|
||||
{
|
||||
'productId': int
|
||||
'quantity': float (optional)
|
||||
'productType': string
|
||||
'price': float
|
||||
'uomDisplayName': string
|
||||
'code': string (optional)
|
||||
'readOnly': bool (optional)
|
||||
}
|
||||
"""
|
||||
return {
|
||||
product.id: {
|
||||
'productType': product.type,
|
||||
'uomDisplayName': product.uom_id.display_name,
|
||||
'code': product.code if product.code else '',
|
||||
}
|
||||
for product in products
|
||||
}
|
||||
|
||||
def _get_product_catalog_order_line_info(self, product_ids, child_field=False, **kwargs):
|
||||
""" Returns products information to be shown in the catalog.
|
||||
:param list product_ids: The products currently displayed in the product catalog, as a list
|
||||
of `product.product` ids.
|
||||
:param dict kwargs: additional values given for inherited models.
|
||||
:rtype: dict
|
||||
:return: A dict with the following structure:
|
||||
{
|
||||
'productId': int
|
||||
'quantity': float (optional)
|
||||
'productType': string
|
||||
'price': float
|
||||
'uomDisplayName': string
|
||||
'code': string (optional)
|
||||
'readOnly': bool (optional)
|
||||
}
|
||||
"""
|
||||
order_line_info = {}
|
||||
|
||||
for product, record_lines in self._get_product_catalog_record_lines(product_ids, child_field=child_field, **kwargs).items():
|
||||
order_line_info[product.id] = {
|
||||
**record_lines._get_product_catalog_lines_data(parent_record=self, **kwargs),
|
||||
'productType': product.type,
|
||||
'code': product.code if product.code else '',
|
||||
}
|
||||
if not order_line_info[product.id]['uomDisplayName']:
|
||||
order_line_info[product.id]['uomDisplayName'] = product.uom_id.display_name
|
||||
|
||||
default_data = self._default_order_line_values(child_field)
|
||||
products = self.env['product.product'].browse(product_ids)
|
||||
product_data = self._get_product_catalog_order_data(products, **kwargs)
|
||||
|
||||
for product_id, data in product_data.items():
|
||||
if product_id in order_line_info:
|
||||
continue
|
||||
order_line_info[product_id] = {**default_data, **data}
|
||||
|
||||
return order_line_info
|
||||
|
||||
def _get_action_add_from_catalog_extra_context(self):
|
||||
return {
|
||||
'display_uom': self.env.user.has_group('uom.group_uom'),
|
||||
'product_catalog_order_id': self.id,
|
||||
'product_catalog_order_model': self._name,
|
||||
}
|
||||
|
||||
def _is_readonly(self):
|
||||
""" Must be overrided by each model using this mixin.
|
||||
:return: Whether the record is read-only or not.
|
||||
:rtype: bool
|
||||
"""
|
||||
return False
|
||||
|
||||
def _update_order_line_info(self, product_id, quantity, **kwargs):
|
||||
""" Update the line information for a given product or create a new one if none exists yet.
|
||||
Must be overrided by each model using this mixin.
|
||||
:param int product_id: The product, as a `product.product` id.
|
||||
:param int quantity: The product's quantity.
|
||||
:param dict kwargs: additional values given for inherited models.
|
||||
:return: The unit price of the product, based on the pricelist of the
|
||||
purchase order and the quantity selected.
|
||||
:rtype: float
|
||||
"""
|
||||
return 0
|
||||
|
|
@ -2,11 +2,12 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
|
||||
class ProductCategory(models.Model):
|
||||
_name = "product.category"
|
||||
_name = 'product.category'
|
||||
_inherit = ['mail.thread']
|
||||
_description = "Product Category"
|
||||
_parent_name = "parent_id"
|
||||
_parent_store = True
|
||||
|
|
@ -18,11 +19,12 @@ class ProductCategory(models.Model):
|
|||
'Complete Name', compute='_compute_complete_name', recursive=True,
|
||||
store=True)
|
||||
parent_id = fields.Many2one('product.category', 'Parent Category', index=True, ondelete='cascade')
|
||||
parent_path = fields.Char(index=True, unaccent=False)
|
||||
parent_path = fields.Char(index=True)
|
||||
child_id = fields.One2many('product.category', 'parent_id', 'Child Categories')
|
||||
product_count = fields.Integer(
|
||||
'# Products', compute='_compute_product_count',
|
||||
help="The number of products under this category (Does not consider the children categories)")
|
||||
product_properties_definition = fields.PropertiesDefinition('Product Properties')
|
||||
|
||||
@api.depends('name', 'parent_id.complete_name')
|
||||
def _compute_complete_name(self):
|
||||
|
|
@ -33,8 +35,8 @@ class ProductCategory(models.Model):
|
|||
category.complete_name = category.name
|
||||
|
||||
def _compute_product_count(self):
|
||||
read_group_res = self.env['product.template'].read_group([('categ_id', 'child_of', self.ids)], ['categ_id'], ['categ_id'])
|
||||
group_data = dict((data['categ_id'][0], data['categ_id_count']) for data in read_group_res)
|
||||
read_group_res = self.env['product.template']._read_group([('categ_id', 'child_of', self.ids)], ['categ_id'], ['__count'])
|
||||
group_data = {categ.id: count for categ, count in read_group_res}
|
||||
for categ in self:
|
||||
product_count = 0
|
||||
for sub_categ_id in categ.search([('id', 'child_of', categ.ids)]).ids:
|
||||
|
|
@ -43,26 +45,25 @@ class ProductCategory(models.Model):
|
|||
|
||||
@api.constrains('parent_id')
|
||||
def _check_category_recursion(self):
|
||||
if not self._check_recursion():
|
||||
if self._has_cycle():
|
||||
raise ValidationError(_('You cannot create recursive categories.'))
|
||||
|
||||
@api.model
|
||||
def name_create(self, name):
|
||||
return self.create({'name': name}).name_get()[0]
|
||||
category = self.create({'name': name})
|
||||
return category.id, category.display_name
|
||||
|
||||
def name_get(self):
|
||||
if not self.env.context.get('hierarchical_naming', True):
|
||||
return [(record.id, record.name) for record in self]
|
||||
return super().name_get()
|
||||
@api.depends_context('hierarchical_naming')
|
||||
def _compute_display_name(self):
|
||||
if self.env.context.get('hierarchical_naming', True):
|
||||
return super()._compute_display_name()
|
||||
for record in self:
|
||||
record.display_name = record.name
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_except_default_category(self):
|
||||
main_category = self.env.ref('product.product_category_all', raise_if_not_found=False)
|
||||
if main_category and main_category in self:
|
||||
raise UserError(_("You cannot delete this product category, it is the default generic category."))
|
||||
expense_category = self.env.ref('product.cat_expense', raise_if_not_found=False)
|
||||
if expense_category and expense_category in self:
|
||||
raise UserError(_("You cannot delete the %s product category.", expense_category.name))
|
||||
saleable_category = self.env.ref('product.product_category_1', raise_if_not_found=False)
|
||||
if saleable_category and saleable_category in self:
|
||||
raise UserError(_("You cannot delete the %s product category.", saleable_category.name))
|
||||
def copy_data(self, default=None):
|
||||
default = dict(default or {})
|
||||
vals_list = super().copy_data(default=default)
|
||||
if 'name' not in default:
|
||||
for category, vals in zip(self, vals_list):
|
||||
vals['name'] = _("%s (copy)", category.name)
|
||||
return vals_list
|
||||
|
|
|
|||
|
|
@ -0,0 +1,79 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
|
||||
class ProductCombo(models.Model):
|
||||
_name = 'product.combo'
|
||||
_description = "Product Combo"
|
||||
_order = 'sequence, id'
|
||||
|
||||
name = fields.Char(string="Name", required=True)
|
||||
sequence = fields.Integer(default=10, copy=False)
|
||||
company_id = fields.Many2one(string="Company", comodel_name='res.company', index=True)
|
||||
combo_item_ids = fields.One2many(
|
||||
comodel_name='product.combo.item',
|
||||
inverse_name='combo_id',
|
||||
copy=True,
|
||||
)
|
||||
combo_item_count = fields.Integer(string="Product Count", compute='_compute_combo_item_count')
|
||||
currency_id = fields.Many2one(comodel_name='res.currency', compute='_compute_currency_id')
|
||||
base_price = fields.Float(
|
||||
string="Combo Price",
|
||||
help="The minimum price among the products in this combo. This value will be used to"
|
||||
" prorate the price of this combo with respect to the other combos in a combo product."
|
||||
" This heuristic ensures that whatever product the user chooses in a combo, it will"
|
||||
" always be the same price.",
|
||||
min_display_digits='Product Price',
|
||||
compute='_compute_base_price',
|
||||
)
|
||||
|
||||
@api.depends('combo_item_ids')
|
||||
def _compute_combo_item_count(self):
|
||||
# Initialize combo_item_count to 0 as _read_group won't return any results for new combos.
|
||||
self.combo_item_count = 0
|
||||
# Optimization to count the number of combo items in each combo.
|
||||
for combo, item_count in self.env['product.combo.item']._read_group(
|
||||
domain=[('combo_id', 'in', self.ids)],
|
||||
groupby=['combo_id'],
|
||||
aggregates=['__count'],
|
||||
):
|
||||
combo.combo_item_count = item_count
|
||||
|
||||
@api.depends('company_id')
|
||||
def _compute_currency_id(self):
|
||||
main_company = self.env['res.company']._get_main_company()
|
||||
for combo in self:
|
||||
combo.currency_id = (
|
||||
combo.company_id.sudo().currency_id or main_company.currency_id
|
||||
)
|
||||
|
||||
@api.depends('combo_item_ids')
|
||||
def _compute_base_price(self):
|
||||
for combo in self:
|
||||
combo.base_price = min(combo.combo_item_ids.mapped(
|
||||
lambda item: item.currency_id._convert(
|
||||
from_amount=item.lst_price,
|
||||
to_currency=combo.currency_id,
|
||||
company=combo.company_id or self.env.company,
|
||||
date=self.env.cr.now(),
|
||||
)
|
||||
)) if combo.combo_item_ids else 0
|
||||
|
||||
@api.constrains('combo_item_ids')
|
||||
def _check_combo_item_ids_not_empty(self):
|
||||
if any(not combo.combo_item_ids for combo in self):
|
||||
raise ValidationError(_("A combo choice must contain at least 1 product."))
|
||||
|
||||
@api.constrains('combo_item_ids')
|
||||
def _check_combo_item_ids_no_duplicates(self):
|
||||
for combo in self:
|
||||
if len(combo.combo_item_ids.mapped('product_id')) < len(combo.combo_item_ids):
|
||||
raise ValidationError(_("A combo choice can't contain duplicate products."))
|
||||
|
||||
@api.constrains('company_id')
|
||||
def _check_company_id(self):
|
||||
templates = self.env['product.template'].sudo().search([('combo_ids', 'in', self.ids)])
|
||||
templates._check_company(fnames=['combo_ids'])
|
||||
self.combo_item_ids._check_company(fnames=['product_id'])
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
|
||||
class ProductComboItem(models.Model):
|
||||
_name = 'product.combo.item'
|
||||
_description = "Product Combo Item"
|
||||
_check_company_auto = True
|
||||
|
||||
company_id = fields.Many2one(related='combo_id.company_id', precompute=True, store=True)
|
||||
combo_id = fields.Many2one(comodel_name='product.combo', ondelete='cascade', required=True, index=True)
|
||||
product_id = fields.Many2one(
|
||||
string="Options",
|
||||
comodel_name='product.product',
|
||||
ondelete='restrict',
|
||||
domain=[('type', '!=', 'combo')],
|
||||
required=True,
|
||||
check_company=True,
|
||||
)
|
||||
currency_id = fields.Many2one(comodel_name='res.currency', related='product_id.currency_id')
|
||||
lst_price = fields.Float(
|
||||
string="Original Price",
|
||||
min_display_digits='Product Price',
|
||||
related='product_id.lst_price',
|
||||
)
|
||||
extra_price = fields.Float(string="Extra Price", min_display_digits='Product Price', default=0.0)
|
||||
|
||||
@api.constrains('product_id')
|
||||
def _check_product_id_no_combo(self):
|
||||
if any(combo_item.product_id.type == 'combo' for combo_item in self):
|
||||
raise ValidationError(_("A combo choice can't contain products of type \"combo\"."))
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
|
||||
class ProductDocument(models.Model):
|
||||
_name = 'product.document'
|
||||
_description = "Product Document"
|
||||
_inherits = {
|
||||
'ir.attachment': 'ir_attachment_id',
|
||||
}
|
||||
_order = 'sequence, name'
|
||||
|
||||
ir_attachment_id = fields.Many2one(
|
||||
'ir.attachment',
|
||||
string="Related attachment",
|
||||
required=True,
|
||||
ondelete='cascade')
|
||||
|
||||
active = fields.Boolean(default=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
|
||||
@api.onchange('url')
|
||||
def _onchange_url(self):
|
||||
for attachment in self:
|
||||
if attachment.type == 'url' and attachment.url and\
|
||||
not attachment.url.startswith(('https://', 'http://', 'ftp://')):
|
||||
raise ValidationError(_(
|
||||
"Please enter a valid URL.\nExample: https://www.odoo.com\n\nInvalid URL: %s",
|
||||
attachment.url
|
||||
))
|
||||
|
||||
#=== CRUD METHODS ===#
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
return super(
|
||||
ProductDocument,
|
||||
self.with_context(disable_product_documents_creation=True),
|
||||
).create(vals_list)
|
||||
|
||||
def copy_data(self, default=None):
|
||||
vals_list = super().copy_data(default=default)
|
||||
ir_default = default
|
||||
if ir_default:
|
||||
ir_fields = list(self.env['ir.attachment']._fields)
|
||||
ir_default = {field : default[field] for field in default if field in ir_fields}
|
||||
for document, vals in zip(self, vals_list):
|
||||
vals['ir_attachment_id'] = document.ir_attachment_id.with_context(
|
||||
no_document=True,
|
||||
disable_product_documents_creation=True,
|
||||
).copy(ir_default).id
|
||||
return vals_list
|
||||
|
||||
def unlink(self):
|
||||
attachments = self.ir_attachment_id
|
||||
res = super().unlink()
|
||||
return res and attachments.unlink()
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.osv import expression
|
||||
|
||||
|
||||
from odoo.tools import float_compare, float_round
|
||||
|
||||
|
||||
class ProductPackaging(models.Model):
|
||||
_name = "product.packaging"
|
||||
_description = "Product Packaging"
|
||||
_order = 'product_id, sequence, id'
|
||||
_check_company_auto = True
|
||||
|
||||
name = fields.Char('Product Packaging', required=True)
|
||||
sequence = fields.Integer('Sequence', default=1, help="The first in the sequence is the default one.")
|
||||
product_id = fields.Many2one('product.product', string='Product', check_company=True)
|
||||
qty = fields.Float('Contained Quantity', default=1, digits='Product Unit of Measure', help="Quantity of products contained in the packaging.")
|
||||
barcode = fields.Char('Barcode', copy=False, help="Barcode used for packaging identification. Scan this packaging barcode from a transfer in the Barcode app to move all the contained units")
|
||||
product_uom_id = fields.Many2one('uom.uom', related='product_id.uom_id', readonly=True)
|
||||
company_id = fields.Many2one('res.company', 'Company', index=True)
|
||||
|
||||
_sql_constraints = [
|
||||
('positive_qty', 'CHECK(qty > 0)', 'Contained Quantity should be positive.'),
|
||||
('barcode_uniq', 'unique(barcode)', 'A barcode can only be assigned to one packaging.'),
|
||||
]
|
||||
|
||||
@api.constrains('barcode')
|
||||
def _check_barcode_uniqueness(self):
|
||||
""" With GS1 nomenclature, products and packagings use the same pattern. Therefore, we need
|
||||
to ensure the uniqueness between products' barcodes and packagings' ones"""
|
||||
domain = [('barcode', 'in', [b for b in self.mapped('barcode') if b])]
|
||||
if self.env['product.product'].search(domain, order="id", limit=1):
|
||||
raise ValidationError(_("A product already uses the barcode"))
|
||||
|
||||
def _check_qty(self, product_qty, uom_id, rounding_method="HALF-UP"):
|
||||
"""Check if product_qty in given uom is a multiple of the packaging qty.
|
||||
If not, rounding the product_qty to closest multiple of the packaging qty
|
||||
according to the rounding_method "UP", "HALF-UP or "DOWN".
|
||||
"""
|
||||
self.ensure_one()
|
||||
default_uom = self.product_id.uom_id
|
||||
packaging_qty = default_uom._compute_quantity(self.qty, uom_id)
|
||||
# We do not use the modulo operator to check if qty is a mltiple of q. Indeed the quantity
|
||||
# per package might be a float, leading to incorrect results. For example:
|
||||
# 8 % 1.6 = 1.5999999999999996
|
||||
# 5.4 % 1.8 = 2.220446049250313e-16
|
||||
if product_qty and packaging_qty:
|
||||
rounded_qty = float_round(product_qty / packaging_qty, precision_rounding=1.0,
|
||||
rounding_method=rounding_method) * packaging_qty
|
||||
return rounded_qty if float_compare(rounded_qty, product_qty, precision_rounding=default_uom.rounding) else product_qty
|
||||
return product_qty
|
||||
|
||||
def _find_suitable_product_packaging(self, product_qty, uom_id):
|
||||
""" try find in `self` if a packaging's qty in given uom is a divisor of
|
||||
the given product_qty. If so, return the one with greatest divisor.
|
||||
"""
|
||||
packagings = self.sorted(lambda p: p.qty, reverse=True)
|
||||
for packaging in packagings:
|
||||
new_qty = packaging._check_qty(product_qty, uom_id)
|
||||
if new_qty == product_qty:
|
||||
return packaging
|
||||
return self.env['product.packaging']
|
||||
|
||||
def write(self, vals):
|
||||
res = super().write(vals)
|
||||
if res and not vals.get('product_id', True):
|
||||
self.unlink()
|
||||
return res
|
||||
|
|
@ -1,19 +1,30 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
from collections import defaultdict
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
class Pricelist(models.Model):
|
||||
_name = "product.pricelist"
|
||||
class ProductPricelist(models.Model):
|
||||
_name = 'product.pricelist'
|
||||
_inherit = ['mail.thread', 'mail.activity.mixin']
|
||||
_description = "Pricelist"
|
||||
_rec_names_search = ['name', 'currency_id'] # TODO check if should be removed
|
||||
_order = "sequence asc, id desc"
|
||||
_order = "sequence, id, name"
|
||||
|
||||
def _default_currency_id(self):
|
||||
return self.env.company.currency_id.id
|
||||
|
||||
def _base_domain_item_ids(self):
|
||||
return [
|
||||
'|', ('product_tmpl_id', '=', None), ('product_tmpl_id.active', '=', True),
|
||||
'|', ('product_id', '=', None), ('product_id.active', '=', True),
|
||||
]
|
||||
|
||||
def _domain_item_ids(self):
|
||||
return self._base_domain_item_ids()
|
||||
|
||||
name = fields.Char(string="Pricelist Name", required=True, translate=True)
|
||||
|
||||
active = fields.Boolean(
|
||||
|
|
@ -25,106 +36,162 @@ class Pricelist(models.Model):
|
|||
currency_id = fields.Many2one(
|
||||
comodel_name='res.currency',
|
||||
default=_default_currency_id,
|
||||
required=True)
|
||||
required=True,
|
||||
tracking=1,
|
||||
)
|
||||
|
||||
company_id = fields.Many2one(
|
||||
comodel_name='res.company')
|
||||
comodel_name='res.company',
|
||||
tracking=5,
|
||||
default=lambda self: self.env.company,
|
||||
)
|
||||
|
||||
country_group_ids = fields.Many2many(
|
||||
comodel_name='res.country.group',
|
||||
relation='res_country_group_pricelist_rel',
|
||||
column1='pricelist_id',
|
||||
column2='res_country_group_id',
|
||||
string="Country Groups")
|
||||
|
||||
discount_policy = fields.Selection(
|
||||
selection=[
|
||||
('with_discount', "Discount included in the price"),
|
||||
('without_discount', "Show public price & discount to the customer"),
|
||||
],
|
||||
default='with_discount',
|
||||
required=True)
|
||||
string="Country Groups",
|
||||
tracking=10,
|
||||
)
|
||||
|
||||
item_ids = fields.One2many(
|
||||
comodel_name='product.pricelist.item',
|
||||
inverse_name='pricelist_id',
|
||||
string="Pricelist Rules",
|
||||
# must be given as lambda for overrides to work
|
||||
domain=lambda self: self._domain_item_ids(),
|
||||
copy=True)
|
||||
|
||||
def name_get(self):
|
||||
return [(pricelist.id, '%s (%s)' % (pricelist.name, pricelist.currency_id.name)) for pricelist in self]
|
||||
@api.depends('currency_id')
|
||||
def _compute_display_name(self):
|
||||
for pricelist in self:
|
||||
pricelist_name = pricelist.name and pricelist.name or _('New')
|
||||
pricelist.display_name = f'{pricelist_name} ({pricelist.currency_id.name})'
|
||||
|
||||
def _get_products_price(self, products, quantity, uom=None, date=False, **kwargs):
|
||||
"""Compute the pricelist prices for the specified products, qty & uom.
|
||||
def write(self, vals):
|
||||
res = super().write(vals)
|
||||
|
||||
Note: self.ensure_one()
|
||||
# Make sure that there is no multi-company issue in the existing rules after the company
|
||||
# change.
|
||||
if 'company_id' in vals and len(self) == 1:
|
||||
self.item_ids._check_company()
|
||||
|
||||
:returns: dict{product_id: product price}, considering the current pricelist
|
||||
:rtype: dict
|
||||
return res
|
||||
|
||||
def copy_data(self, default=None):
|
||||
default = dict(default or {})
|
||||
vals_list = super().copy_data(default=default)
|
||||
if 'name' not in default:
|
||||
for pricelist, vals in zip(self, vals_list):
|
||||
vals['name'] = _("%s (copy)", pricelist.name)
|
||||
return vals_list
|
||||
|
||||
def _get_products_price(self, products, *args, **kwargs):
|
||||
"""Compute the pricelist prices for the specified products, quantity & uom.
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param products: recordset of products (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency) (optional)
|
||||
:param uom: unit of measure (uom.uom record) (optional)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions (optional)
|
||||
:type date: date or datetime
|
||||
|
||||
:returns: {product_id: product price}, considering the current pricelist if any
|
||||
:rtype: dict(int, float)
|
||||
"""
|
||||
self.ensure_one()
|
||||
self and self.ensure_one() # self is at most one record
|
||||
return {
|
||||
product_id: res_tuple[0]
|
||||
for product_id, res_tuple in self._compute_price_rule(
|
||||
products,
|
||||
quantity,
|
||||
uom=uom,
|
||||
date=date,
|
||||
**kwargs
|
||||
).items()
|
||||
for product_id, res_tuple in self._compute_price_rule(products, *args, **kwargs).items()
|
||||
}
|
||||
|
||||
def _get_product_price(self, product, quantity, uom=None, date=False, **kwargs):
|
||||
def _get_product_price(self, product, *args, **kwargs):
|
||||
"""Compute the pricelist price for the specified product, qty & uom.
|
||||
|
||||
Note: self.ensure_one()
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:returns: unit price of the product, considering pricelist rules
|
||||
:param product: product record (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency) (optional)
|
||||
:param uom: unit of measure (uom.uom record) (optional)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions (optional)
|
||||
:type date: date or datetime
|
||||
|
||||
:returns: unit price of the product, considering pricelist rules if any
|
||||
:rtype: float
|
||||
"""
|
||||
self.ensure_one()
|
||||
return self._compute_price_rule(
|
||||
product, quantity, uom=uom, date=date, **kwargs
|
||||
)[product.id][0]
|
||||
self and self.ensure_one() # self is at most one record
|
||||
return self._compute_price_rule(product, *args, **kwargs)[product.id][0]
|
||||
|
||||
def _get_product_price_rule(self, product, quantity, uom=None, date=False, **kwargs):
|
||||
def _get_product_price_rule(self, product, *args, **kwargs):
|
||||
"""Compute the pricelist price & rule for the specified product, qty & uom.
|
||||
|
||||
Note: self.ensure_one()
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param product: product record (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency) (optional)
|
||||
:param uom: unit of measure (uom.uom record) (optional)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions (optional)
|
||||
:type date: date or datetime
|
||||
|
||||
:returns: (product unit price, applied pricelist rule id)
|
||||
:rtype: tuple(float, int)
|
||||
"""
|
||||
self.ensure_one()
|
||||
return self._compute_price_rule(product, quantity, uom=uom, date=date, **kwargs)[product.id]
|
||||
self and self.ensure_one() # self is at most one record
|
||||
return self._compute_price_rule(product, *args, **kwargs)[product.id]
|
||||
|
||||
def _get_product_rule(self, product, quantity, uom=None, date=False, **kwargs):
|
||||
def _get_product_rule(self, product, *args, **kwargs):
|
||||
"""Compute the pricelist price & rule for the specified product, qty & uom.
|
||||
|
||||
Note: self.ensure_one()
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param product: product record (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency) (optional)
|
||||
:param uom: unit of measure (uom.uom record) (optional)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions (optional)
|
||||
:type date: date or datetime
|
||||
|
||||
:returns: applied pricelist rule id
|
||||
:rtype: int or False
|
||||
"""
|
||||
self.ensure_one()
|
||||
return self._compute_price_rule(
|
||||
product, quantity, uom=uom, date=date, **kwargs
|
||||
)[product.id][1]
|
||||
self and self.ensure_one() # self is at most one record
|
||||
return self._compute_price_rule(product, *args, compute_price=False, **kwargs)[product.id][1]
|
||||
|
||||
def _compute_price_rule(self, products, qty, uom=None, date=False, **kwargs):
|
||||
def _compute_price_rule(
|
||||
self, products, quantity, *, currency=None, uom=None, date=False, compute_price=True,
|
||||
**kwargs
|
||||
):
|
||||
""" Low-level method - Mono pricelist, multi products
|
||||
Returns: dict{product_id: (price, suitable_rule) for the given pricelist}
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param products: recordset of products (product.product/product.template)
|
||||
:param float qty: quantity of products requested (in given uom)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param currency: record of currency (res.currency)
|
||||
note: currency.ensure_one()
|
||||
:param uom: unit of measure (uom.uom record)
|
||||
If not specified, prices returned are expressed in product uoms
|
||||
:param date: date to use for price computation and currency conversions
|
||||
:type date: date or datetime
|
||||
:param bool compute_price: whether the price should be computed (default: True)
|
||||
|
||||
:returns: product_id: (price, pricelist_rule)
|
||||
:rtype: dict
|
||||
"""
|
||||
self.ensure_one()
|
||||
self and self.ensure_one() # self is at most one record
|
||||
|
||||
currency = currency or self.currency_id or self.env.company.currency_id
|
||||
currency.ensure_one()
|
||||
|
||||
if not products:
|
||||
return {}
|
||||
|
|
@ -146,32 +213,40 @@ class Pricelist(models.Model):
|
|||
# Compute quantity in product uom because pricelist rules are specified
|
||||
# w.r.t product default UoM (min_quantity, price_surchage, ...)
|
||||
if target_uom != product_uom:
|
||||
qty_in_product_uom = target_uom._compute_quantity(qty, product_uom, raise_if_failure=False)
|
||||
qty_in_product_uom = target_uom._compute_quantity(
|
||||
quantity, product_uom, raise_if_failure=False
|
||||
)
|
||||
else:
|
||||
qty_in_product_uom = qty
|
||||
qty_in_product_uom = quantity
|
||||
|
||||
for rule in rules:
|
||||
if rule._is_applicable_for(product, qty_in_product_uom):
|
||||
suitable_rule = rule
|
||||
break
|
||||
|
||||
kwargs['pricelist'] = self
|
||||
price = suitable_rule._compute_price(product, qty, target_uom, date=date, currency=self.currency_id)
|
||||
if compute_price:
|
||||
price = suitable_rule._compute_price(
|
||||
product, quantity, target_uom, date=date, currency=currency, **kwargs)
|
||||
else:
|
||||
# Skip price computation when only the rule is requested.
|
||||
price = 0.0
|
||||
|
||||
results[product.id] = (price, suitable_rule.id)
|
||||
|
||||
return results
|
||||
|
||||
# Split methods to ease (community) overrides
|
||||
def _get_applicable_rules(self, products, date, **kwargs):
|
||||
self.ensure_one()
|
||||
# Do not filter out archived pricelist items, since it means current pricelist is also archived
|
||||
# We do not want the computation of prices for archived pricelist to always fallback on the Sales price
|
||||
# because no rule was found (thanks to the automatic orm filtering on active field)
|
||||
return self.env['product.pricelist.item'].with_context(active_test=False).search(
|
||||
self and self.ensure_one() # self is at most one record
|
||||
if not self:
|
||||
return self.env['product.pricelist.item']
|
||||
|
||||
return self.env['product.pricelist.item'].search(
|
||||
self._get_applicable_rules_domain(products=products, date=date, **kwargs)
|
||||
)
|
||||
|
||||
def _get_applicable_rules_domain(self, products, date, **kwargs):
|
||||
self and self.ensure_one() # self is at most one record
|
||||
if products._name == 'product.template':
|
||||
templates_domain = ('product_tmpl_id', 'in', products.ids)
|
||||
products_domain = ('product_id.product_tmpl_id', 'in', products.ids)
|
||||
|
|
@ -189,13 +264,13 @@ class Pricelist(models.Model):
|
|||
]
|
||||
|
||||
# Multi pricelists price|rule computation
|
||||
def _price_get(self, product, qty, **kwargs):
|
||||
def _price_get(self, product, quantity, **kwargs):
|
||||
""" Multi pricelist, mono product - returns price per pricelist """
|
||||
return {
|
||||
key: price[0]
|
||||
for key, price in self._compute_price_rule_multi(product, qty, **kwargs)[product.id].items()}
|
||||
for key, price in self._compute_price_rule_multi(product, quantity, **kwargs)[product.id].items()}
|
||||
|
||||
def _compute_price_rule_multi(self, products, qty, uom=None, date=False, **kwargs):
|
||||
def _compute_price_rule_multi(self, products, quantity, uom=None, date=False, **kwargs):
|
||||
""" Low-level method - Multi pricelist, multi products
|
||||
Returns: dict{product_id: dict{pricelist_id: (price, suitable_rule)} }"""
|
||||
if not self.ids:
|
||||
|
|
@ -204,12 +279,56 @@ class Pricelist(models.Model):
|
|||
pricelists = self
|
||||
results = {}
|
||||
for pricelist in pricelists:
|
||||
subres = pricelist._compute_price_rule(products, qty, uom=uom, date=date, **kwargs)
|
||||
subres = pricelist._compute_price_rule(products, quantity, uom=uom, date=date, **kwargs)
|
||||
for product_id, price in subres.items():
|
||||
results.setdefault(product_id, {})
|
||||
results[product_id][pricelist.id] = price
|
||||
return results
|
||||
|
||||
def _get_country_pricelist_multi(self, country_ids):
|
||||
def get_param_id(key):
|
||||
string_value = self.env['ir.config_parameter'].sudo().get_param(key, False)
|
||||
try:
|
||||
return int(string_value)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
|
||||
company_id = self.env.company.id
|
||||
pl_domain = self._get_partner_pricelist_multi_search_domain_hook(company_id)
|
||||
|
||||
if (
|
||||
(ctx_code := self.env.context.get('country_code'))
|
||||
and (ctx_country := self.env['res.country'].search([('code', '=', ctx_code)], limit=1))
|
||||
):
|
||||
if ctx_country.id not in country_ids:
|
||||
country_ids.append(ctx_country.id)
|
||||
else:
|
||||
ctx_country = False
|
||||
|
||||
# get fallback pricelist when no pricelist for a given country
|
||||
pl_fallback = (
|
||||
self.search(pl_domain + [('country_group_ids', '=', False)], limit=1)
|
||||
# save data in ir.config_parameter instead of ir.default for
|
||||
# res.partner.property_product_pricelist
|
||||
# otherwise the data will become the default value while
|
||||
# creating without specifying the property_product_pricelist
|
||||
# however if the property_product_pricelist is not specified
|
||||
# the result of the previous line should have high priority
|
||||
# when computing
|
||||
or self.browse(get_param_id(f'res.partner.property_product_pricelist_{company_id}'))
|
||||
or self.browse(get_param_id('res.partner.property_product_pricelist'))
|
||||
or self.search(pl_domain, limit=1)
|
||||
)
|
||||
result = {}
|
||||
for country_id in country_ids:
|
||||
pl = self.search([
|
||||
*pl_domain,
|
||||
('country_group_ids.country_ids', '=', country_id),
|
||||
], limit=1)
|
||||
result[country_id] = pl or pl_fallback
|
||||
result[False] = result[ctx_country.id] if ctx_country else pl_fallback
|
||||
return result
|
||||
|
||||
# res.partner.property_product_pricelist field computation
|
||||
@api.model
|
||||
def _get_partner_pricelist_multi(self, partner_ids):
|
||||
|
|
@ -219,44 +338,39 @@ class Pricelist(models.Model):
|
|||
First, the pricelist of the specific property (res_id set), this one
|
||||
is created when saving a pricelist on the partner form view.
|
||||
Else, it will return the pricelist of the partner country group
|
||||
Else, it will return the generic property (res_id not set), this one
|
||||
is created on the company creation.
|
||||
Else, it will return the first available pricelist
|
||||
Else, it will return the generic property (res_id not set)
|
||||
Else, it will return the first available pricelist if any
|
||||
|
||||
:param int company_id: if passed, used for looking up properties,
|
||||
instead of current user's company
|
||||
:return: a dict {partner_id: pricelist}
|
||||
"""
|
||||
ProductPricelist = self.env['product.pricelist']
|
||||
|
||||
if not self.env['res.groups']._is_feature_enabled('product.group_product_pricelist'):
|
||||
# Skip pricelist computation if pricelists are disabled.
|
||||
return defaultdict(lambda: ProductPricelist)
|
||||
|
||||
# `partner_ids` might be ID from inactive users. We should use active_test
|
||||
# as we will do a search() later (real case for website public user).
|
||||
Partner = self.env['res.partner'].with_context(active_test=False)
|
||||
company_id = self.env.company.id
|
||||
|
||||
Property = self.env['ir.property'].with_company(company_id)
|
||||
Pricelist = self.env['product.pricelist']
|
||||
pl_domain = self._get_partner_pricelist_multi_search_domain_hook(company_id)
|
||||
|
||||
# if no specific property, try to find a fitting pricelist
|
||||
result = Property._get_multi('property_product_pricelist', Partner._name, partner_ids)
|
||||
result = {}
|
||||
remaining_partner_ids = []
|
||||
for partner in Partner.browse(partner_ids):
|
||||
if partner.specific_property_product_pricelist._get_partner_pricelist_multi_filter_hook():
|
||||
result[partner.id] = partner.specific_property_product_pricelist
|
||||
else:
|
||||
remaining_partner_ids.append(partner.id)
|
||||
|
||||
remaining_partner_ids = [pid for pid, val in result.items() if not val or
|
||||
not val._get_partner_pricelist_multi_filter_hook()]
|
||||
if remaining_partner_ids:
|
||||
# get fallback pricelist when no pricelist for a given country
|
||||
pl_fallback = (
|
||||
Pricelist.search(pl_domain + [('country_group_ids', '=', False)], limit=1) or
|
||||
Property._get('property_product_pricelist', 'res.partner') or
|
||||
Pricelist.search(pl_domain, limit=1)
|
||||
)
|
||||
# group partners by country, and find a pricelist for each country
|
||||
domain = [('id', 'in', remaining_partner_ids)]
|
||||
groups = Partner.read_group(domain, ['country_id'], ['country_id'])
|
||||
for group in groups:
|
||||
country_id = group['country_id'] and group['country_id'][0]
|
||||
pl = Pricelist.search(pl_domain + [('country_group_ids.country_ids', '=', country_id)], limit=1)
|
||||
pl = pl or pl_fallback
|
||||
for pid in Partner.search(group['__domain']).ids:
|
||||
result[pid] = pl
|
||||
remaining_partners = self.env['res.partner'].browse(remaining_partner_ids)
|
||||
partners_by_country = remaining_partners.grouped('country_id')
|
||||
country_ids = remaining_partners.country_id.ids
|
||||
pricelists_by_country_id = self._get_country_pricelist_multi(country_ids)
|
||||
for country, partners in partners_by_country.items():
|
||||
pl = pricelists_by_country_id[country.id]
|
||||
result.update(dict.fromkeys(partners._ids, pl))
|
||||
|
||||
return result
|
||||
|
||||
|
|
@ -278,14 +392,23 @@ class Pricelist(models.Model):
|
|||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
def _unlink_except_used_as_rule_base(self):
|
||||
linked_items = self.env['product.pricelist.item'].sudo().with_context(active_test=False).search([
|
||||
linked_items = self.env['product.pricelist.item'].sudo().search([
|
||||
('base', '=', 'pricelist'),
|
||||
('base_pricelist_id', 'in', self.ids),
|
||||
('pricelist_id', 'not in', self.ids),
|
||||
])
|
||||
if linked_items:
|
||||
raise UserError(_(
|
||||
'You cannot delete those pricelist(s):\n(%s)\n, they are used in other pricelist(s):\n%s',
|
||||
'\n'.join(linked_items.base_pricelist_id.mapped('display_name')),
|
||||
'\n'.join(linked_items.pricelist_id.mapped('display_name'))
|
||||
'You cannot delete pricelist(s):\n(%(pricelists)s)\nThey are used within pricelist(s):\n%(other_pricelists)s',
|
||||
pricelists='\n'.join(linked_items.base_pricelist_id.mapped('display_name')),
|
||||
other_pricelists='\n'.join(linked_items.pricelist_id.mapped('display_name')),
|
||||
))
|
||||
|
||||
@api.readonly
|
||||
def action_open_pricelist_report(self):
|
||||
self.ensure_one()
|
||||
return {
|
||||
'name': _("Pricelist Report Preview"),
|
||||
'type': 'ir.actions.client',
|
||||
'tag': 'generate_pricelist_report',
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,12 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.tools import format_datetime, formatLang
|
||||
from odoo.tools import float_round, format_amount, format_datetime, formatLang
|
||||
|
||||
|
||||
class PricelistItem(models.Model):
|
||||
_name = "product.pricelist.item"
|
||||
class ProductPricelistItem(models.Model):
|
||||
_name = 'product.pricelist.item'
|
||||
_description = "Pricelist Rule"
|
||||
_order = "applied_on, min_quantity desc, categ_id desc, id desc"
|
||||
_check_company_auto = True
|
||||
|
|
@ -20,13 +19,17 @@ class PricelistItem(models.Model):
|
|||
pricelist_id = fields.Many2one(
|
||||
comodel_name='product.pricelist',
|
||||
string="Pricelist",
|
||||
index=True, ondelete='cascade',
|
||||
required=True,
|
||||
default=_default_pricelist_id)
|
||||
index=True,
|
||||
ondelete='cascade',
|
||||
# Standard flows do not handle rules without pricelists (but some custom modules do)!
|
||||
required=False,
|
||||
default=_default_pricelist_id,
|
||||
)
|
||||
|
||||
active = fields.Boolean(related='pricelist_id.active', store=True)
|
||||
company_id = fields.Many2one(related='pricelist_id.company_id', store=True)
|
||||
currency_id = fields.Many2one(related='pricelist_id.currency_id', store=True)
|
||||
is_pricelist_required = fields.Boolean(compute='_compute_is_pricelist_required')
|
||||
|
||||
company_id = fields.Many2one(comodel_name='res.company', compute='_compute_company_id', store=True)
|
||||
currency_id = fields.Many2one(comodel_name='res.currency', compute='_compute_currency_id', store=True)
|
||||
|
||||
date_start = fields.Datetime(
|
||||
string="Start Date",
|
||||
|
|
@ -40,7 +43,7 @@ class PricelistItem(models.Model):
|
|||
min_quantity = fields.Float(
|
||||
string="Min. Quantity",
|
||||
default=0,
|
||||
digits='Product Unit of Measure',
|
||||
digits='Product Unit',
|
||||
help="For the rule to apply, bought/sold quantity must be greater "
|
||||
"than or equal to the minimum quantity specified in this field.\n"
|
||||
"Expressed in the default unit of measure of the product.")
|
||||
|
|
@ -57,21 +60,33 @@ class PricelistItem(models.Model):
|
|||
required=True,
|
||||
help="Pricelist Item applicable on selected option")
|
||||
|
||||
display_applied_on = fields.Selection(
|
||||
selection=[
|
||||
('1_product', "Product"),
|
||||
('2_product_category', "Category"),
|
||||
],
|
||||
default='1_product',
|
||||
required=True,
|
||||
help="Pricelist Item applicable on selected option")
|
||||
|
||||
categ_id = fields.Many2one(
|
||||
comodel_name='product.category',
|
||||
string="Product Category",
|
||||
string="Category",
|
||||
ondelete='cascade',
|
||||
help="Specify a product category if this rule only applies to products belonging to this category or its children categories. Keep empty otherwise.")
|
||||
product_tmpl_id = fields.Many2one(
|
||||
comodel_name='product.template',
|
||||
string="Product",
|
||||
ondelete='cascade', check_company=True,
|
||||
ondelete='cascade', check_company=True, index='btree_not_null',
|
||||
help="Specify a template if this rule only applies to one product template. Keep empty otherwise.")
|
||||
product_id = fields.Many2one(
|
||||
comodel_name='product.product',
|
||||
string="Product Variant",
|
||||
ondelete='cascade', check_company=True,
|
||||
string="Variant",
|
||||
ondelete='cascade', check_company=True, index='btree_not_null',
|
||||
domain="[('product_tmpl_id', '=', product_tmpl_id)]",
|
||||
help="Specify a product if this rule only applies to one product. Keep empty otherwise.")
|
||||
product_uom_name = fields.Char(related='product_tmpl_id.uom_name')
|
||||
product_variant_count = fields.Integer(related='product_tmpl_id.product_variant_count')
|
||||
|
||||
base = fields.Selection(
|
||||
selection=[
|
||||
|
|
@ -84,19 +99,21 @@ class PricelistItem(models.Model):
|
|||
required=True,
|
||||
help="Base price for computation.\n"
|
||||
"Sales Price: The base price will be the Sales Price.\n"
|
||||
"Cost Price : The base price will be the cost price.\n"
|
||||
"Other Pricelist : Computation of the base price based on another Pricelist.")
|
||||
"Cost Price: The base price will be the cost price.\n"
|
||||
"Other Pricelist: Computation of the base price based on another Pricelist.")
|
||||
base_pricelist_id = fields.Many2one('product.pricelist', 'Other Pricelist', check_company=True)
|
||||
|
||||
compute_price = fields.Selection(
|
||||
selection=[
|
||||
('fixed', "Fixed Price"),
|
||||
('percentage', "Discount"),
|
||||
('formula', "Formula"),
|
||||
('fixed', "Fixed Price"),
|
||||
],
|
||||
help="Use the discount rules and activate the discount settings"
|
||||
" in order to show discount to customer.",
|
||||
index=True, default='fixed', required=True)
|
||||
|
||||
fixed_price = fields.Float(string="Fixed Price", digits='Product Price')
|
||||
fixed_price = fields.Float(string="Fixed Price", min_display_digits='Product Price')
|
||||
percent_price = fields.Float(
|
||||
string="Percentage Price",
|
||||
help="You can apply a mark-up by setting a negative discount.")
|
||||
|
|
@ -108,97 +125,229 @@ class PricelistItem(models.Model):
|
|||
help="You can apply a mark-up by setting a negative discount.")
|
||||
price_round = fields.Float(
|
||||
string="Price Rounding",
|
||||
digits='Product Price',
|
||||
min_display_digits='Product Price',
|
||||
help="Sets the price so that it is a multiple of this value.\n"
|
||||
"Rounding is applied after the discount and before the surcharge.\n"
|
||||
"To have prices that end in 9.99, set rounding 10, surcharge -0.01")
|
||||
"To have prices that end in 9.99, round off to 10.00 and set an extra at -0.01")
|
||||
price_surcharge = fields.Float(
|
||||
string="Price Surcharge",
|
||||
digits='Product Price',
|
||||
string="Extra Fee",
|
||||
min_display_digits='Product Price',
|
||||
help="Specify the fixed amount to add or subtract (if negative) to the amount calculated with the discount.")
|
||||
|
||||
price_markup = fields.Float(
|
||||
string="Markup",
|
||||
digits=(16, 2),
|
||||
compute='_compute_price_markup',
|
||||
inverse='_inverse_price_markup',
|
||||
store=True,
|
||||
help="You can apply a mark-up on the cost")
|
||||
|
||||
price_min_margin = fields.Float(
|
||||
string="Min. Price Margin",
|
||||
digits='Product Price',
|
||||
min_display_digits='Product Price',
|
||||
help="Specify the minimum amount of margin over the base price.")
|
||||
price_max_margin = fields.Float(
|
||||
string="Max. Price Margin",
|
||||
digits='Product Price',
|
||||
min_display_digits='Product Price',
|
||||
help="Specify the maximum amount of margin over the base price.")
|
||||
|
||||
# functional fields used for usability purposes
|
||||
name = fields.Char(
|
||||
string="Name",
|
||||
compute='_compute_name_and_price',
|
||||
compute='_compute_name',
|
||||
help="Explicit rule name for this pricelist line.")
|
||||
price = fields.Char(
|
||||
string="Price",
|
||||
compute='_compute_name_and_price',
|
||||
compute='_compute_price_label',
|
||||
help="Explicit rule name for this pricelist line.")
|
||||
rule_tip = fields.Char(compute='_compute_rule_tip')
|
||||
|
||||
#=== COMPUTE METHODS ===#
|
||||
|
||||
@api.depends('applied_on', 'categ_id', 'product_tmpl_id', 'product_id', 'compute_price', 'fixed_price', \
|
||||
'pricelist_id', 'percent_price', 'price_discount', 'price_surcharge')
|
||||
def _compute_name_and_price(self):
|
||||
def _compute_is_pricelist_required(self):
|
||||
self.is_pricelist_required = True
|
||||
|
||||
@api.depends('pricelist_id.company_id', 'product_tmpl_id')
|
||||
def _compute_company_id(self):
|
||||
for item in self:
|
||||
item.company_id = item.pricelist_id.company_id or item.product_tmpl_id.company_id
|
||||
|
||||
@api.depends('pricelist_id.currency_id', 'company_id')
|
||||
def _compute_currency_id(self):
|
||||
for item in self:
|
||||
item.currency_id = (
|
||||
item.pricelist_id.currency_id
|
||||
or item.company_id.currency_id
|
||||
or item.env.company.currency_id
|
||||
)
|
||||
|
||||
@api.depends('applied_on', 'categ_id', 'product_tmpl_id', 'product_id')
|
||||
def _compute_name(self):
|
||||
for item in self:
|
||||
if item.categ_id and item.applied_on == '2_product_category':
|
||||
item.name = _("Category: %s") % (item.categ_id.display_name)
|
||||
item.name = _("Category: %s", item.categ_id.display_name)
|
||||
elif item.product_tmpl_id and item.applied_on == '1_product':
|
||||
item.name = _("Product: %s") % (item.product_tmpl_id.display_name)
|
||||
item.name = item.product_tmpl_id.display_name
|
||||
elif item.product_id and item.applied_on == '0_product_variant':
|
||||
item.name = _("Variant: %s") % (item.product_id.display_name)
|
||||
item.name = _("Variant: %s", item.product_id.display_name)
|
||||
elif item.display_applied_on == '2_product_category':
|
||||
item.name = _("All Categories")
|
||||
else:
|
||||
item.name = _("All Products")
|
||||
|
||||
def _get_price_label_base_str(self):
|
||||
"""This method allows you to extend it to other modules with other
|
||||
options in the base field to return a different text.
|
||||
"""
|
||||
self.ensure_one()
|
||||
base_str = ""
|
||||
if self.base == 'pricelist' and self.base_pricelist_id:
|
||||
base_str = self.base_pricelist_id.display_name
|
||||
elif self.base == 'standard_price':
|
||||
base_str = _("product cost")
|
||||
else:
|
||||
base_str = _("sales price")
|
||||
return base_str
|
||||
|
||||
@api.depends(
|
||||
'compute_price', 'fixed_price', 'pricelist_id', 'percent_price', 'price_discount',
|
||||
'price_markup', 'price_surcharge', 'base', 'base_pricelist_id',
|
||||
)
|
||||
def _compute_price_label(self):
|
||||
for item in self:
|
||||
if item.compute_price == 'fixed':
|
||||
item.price = formatLang(
|
||||
item.env, item.fixed_price, monetary=True, dp="Product Price", currency_obj=item.currency_id)
|
||||
item.env, item.fixed_price, dp="Product Price", currency_obj=item.currency_id)
|
||||
elif item.compute_price == 'percentage':
|
||||
item.price = _("%s %% discount", item.percent_price)
|
||||
percentage = self._get_integer(item.percent_price)
|
||||
if item.base_pricelist_id:
|
||||
item.price = _(
|
||||
"%(percentage)s %% discount on %(pricelist)s",
|
||||
percentage=percentage,
|
||||
pricelist=item.base_pricelist_id.display_name
|
||||
)
|
||||
else:
|
||||
item.price = _(
|
||||
"%(percentage)s %% discount on sales price",
|
||||
percentage=percentage
|
||||
)
|
||||
else:
|
||||
item.price = _("%(percentage)s %% discount and %(price)s surcharge", percentage=item.price_discount, price=item.price_surcharge)
|
||||
base_str = item._get_price_label_base_str()
|
||||
|
||||
extra_fee_str = ""
|
||||
if item.price_surcharge > 0:
|
||||
extra_fee_str = _(
|
||||
"+ %(amount)s extra fee",
|
||||
amount=format_amount(
|
||||
item.env,
|
||||
abs(item.price_surcharge),
|
||||
currency=item.currency_id,
|
||||
),
|
||||
)
|
||||
elif item.price_surcharge < 0:
|
||||
extra_fee_str = _(
|
||||
"- %(amount)s rebate",
|
||||
amount=format_amount(
|
||||
item.env,
|
||||
abs(item.price_surcharge),
|
||||
currency=item.currency_id,
|
||||
),
|
||||
)
|
||||
discount_type, percentage = self._get_displayed_discount(item)
|
||||
item.price = _("%(percentage)s %% %(discount_type)s on %(base)s %(extra)s",
|
||||
percentage=percentage,
|
||||
discount_type=discount_type,
|
||||
base=base_str,
|
||||
extra=extra_fee_str,
|
||||
)
|
||||
|
||||
@api.depends('price_discount')
|
||||
def _compute_price_markup(self):
|
||||
for item in self:
|
||||
item.price_markup = -item.price_discount
|
||||
|
||||
def _inverse_price_markup(self):
|
||||
for item in self:
|
||||
item.price_discount = -item.price_markup
|
||||
|
||||
@api.depends_context('lang')
|
||||
@api.depends('compute_price', 'price_discount', 'price_surcharge', 'base', 'price_round')
|
||||
@api.depends(
|
||||
'base', 'compute_price', 'price_discount', 'price_markup', 'price_round', 'price_surcharge',
|
||||
)
|
||||
def _compute_rule_tip(self):
|
||||
base_selection_vals = {elem[0]: elem[1] for elem in self._fields['base']._description_selection(self.env)}
|
||||
base_selection_vals = dict(self._fields['base']._description_selection(self.env))
|
||||
self.rule_tip = False
|
||||
for item in self:
|
||||
if item.compute_price != 'formula':
|
||||
if item.compute_price != 'formula' or not item.base:
|
||||
continue
|
||||
base_amount = 100
|
||||
discount_factor = (100 - item.price_discount) / 100
|
||||
discount = item.price_discount if item.base != 'standard_price' else -item.price_markup
|
||||
discount_factor = (100 - discount) / 100
|
||||
discounted_price = base_amount * discount_factor
|
||||
if item.price_round:
|
||||
discounted_price = tools.float_round(discounted_price, precision_rounding=item.price_round)
|
||||
surcharge = tools.format_amount(item.env, item.price_surcharge, item.currency_id)
|
||||
discounted_price = float_round(discounted_price, precision_rounding=item.price_round)
|
||||
surcharge = format_amount(item.env, item.price_surcharge, item.currency_id)
|
||||
discount_type, discount = self._get_displayed_discount(item)
|
||||
|
||||
item.rule_tip = _(
|
||||
"%(base)s with a %(discount)s %% discount and %(surcharge)s extra fee\n"
|
||||
"%(base)s with a %(discount)s %% %(discount_type)s and %(surcharge)s extra fee\n"
|
||||
"Example: %(amount)s * %(discount_charge)s + %(price_surcharge)s → %(total_amount)s",
|
||||
base=base_selection_vals[item.base],
|
||||
discount=item.price_discount,
|
||||
discount=discount,
|
||||
discount_type=discount_type,
|
||||
surcharge=surcharge,
|
||||
amount=tools.format_amount(item.env, 100, item.currency_id),
|
||||
amount=format_amount(item.env, 100, item.currency_id),
|
||||
discount_charge=discount_factor,
|
||||
price_surcharge=surcharge,
|
||||
total_amount=tools.format_amount(
|
||||
total_amount=format_amount(
|
||||
item.env, discounted_price + item.price_surcharge, item.currency_id),
|
||||
)
|
||||
|
||||
def _get_integer(self, percentage):
|
||||
return int(percentage) if percentage == int(percentage) else percentage
|
||||
|
||||
def _get_displayed_discount(self, item):
|
||||
if item.base == 'standard_price':
|
||||
return _("markup"), self._get_integer(item.price_markup)
|
||||
return _("discount"), self._get_integer(item.price_discount)
|
||||
|
||||
#=== CONSTRAINT METHODS ===#
|
||||
|
||||
@api.constrains('base_pricelist_id', 'base')
|
||||
def _check_base_pricelist_id(self):
|
||||
if any(item.base == 'pricelist' and not item.base_pricelist_id for item in self):
|
||||
raise ValidationError(_('A pricelist item with "Other Pricelist" as base must have a base_pricelist_id.'))
|
||||
|
||||
@api.constrains('base_pricelist_id', 'pricelist_id', 'base')
|
||||
def _check_recursion(self):
|
||||
if any(item.base == 'pricelist' and item.pricelist_id and item.pricelist_id == item.base_pricelist_id for item in self):
|
||||
raise ValidationError(_('You cannot assign the Main Pricelist as Other Pricelist in PriceList Item'))
|
||||
def _check_pricelist_recursion(self):
|
||||
def dfs_path(from_item, path, seen=set()):
|
||||
if from_item.base_pricelist_id in path:
|
||||
return path + from_item.base_pricelist_id
|
||||
for to_item in from_item.base_pricelist_id.item_ids:
|
||||
if to_item.base != 'pricelist' or to_item.id in seen:
|
||||
continue
|
||||
seen.add(to_item.id)
|
||||
if res := dfs_path(to_item, path + from_item.base_pricelist_id):
|
||||
return res
|
||||
return path.browse()
|
||||
|
||||
for item in self:
|
||||
if path := dfs_path(item, item.pricelist_id):
|
||||
raise ValidationError(_(
|
||||
"Recursive pricelist rules detected: %s",
|
||||
" ⇒ ".join(path.mapped('name')),
|
||||
))
|
||||
|
||||
@api.constrains('date_start', 'date_end')
|
||||
def _check_date_range(self):
|
||||
for item in self:
|
||||
if item.date_start and item.date_end and item.date_start >= item.date_end:
|
||||
raise ValidationError(_('%s : end date (%s) should be greater than start date (%s)', item.display_name, format_datetime(self.env, item.date_end), format_datetime(self.env, item.date_start)))
|
||||
raise ValidationError(_(
|
||||
'%(item_name)s: end date (%(end_date)s) should be after start date (%(start_date)s)',
|
||||
item_name=item.display_name,
|
||||
end_date=format_datetime(self.env, item.date_end),
|
||||
start_date=format_datetime(self.env, item.date_start),
|
||||
))
|
||||
return True
|
||||
|
||||
@api.constrains('price_min_margin', 'price_max_margin')
|
||||
|
|
@ -211,15 +360,30 @@ class PricelistItem(models.Model):
|
|||
for item in self:
|
||||
if item.applied_on == "2_product_category" and not item.categ_id:
|
||||
raise ValidationError(_("Please specify the category for which this rule should be applied"))
|
||||
elif item.applied_on == "1_product" and not item.product_tmpl_id:
|
||||
if item.applied_on == "1_product" and not item.product_tmpl_id:
|
||||
raise ValidationError(_("Please specify the product for which this rule should be applied"))
|
||||
elif item.applied_on == "0_product_variant" and not item.product_id:
|
||||
if item.applied_on == "0_product_variant" and not item.product_id:
|
||||
raise ValidationError(_("Please specify the product variant for which this rule should be applied"))
|
||||
|
||||
#=== ONCHANGE METHODS ===#
|
||||
|
||||
@api.onchange('base')
|
||||
def _onchange_base(self):
|
||||
for item in self:
|
||||
item.update({
|
||||
'price_discount': 0.0,
|
||||
'price_markup': 0.0,
|
||||
})
|
||||
|
||||
@api.onchange('base_pricelist_id')
|
||||
def _onchange_base_pricelist_id(self):
|
||||
for item in self:
|
||||
if item.compute_price == 'percentage':
|
||||
item.base = (bool(item.base_pricelist_id) and 'pricelist') or 'list_price'
|
||||
|
||||
@api.onchange('compute_price')
|
||||
def _onchange_compute_price(self):
|
||||
self.base_pricelist_id = False
|
||||
if self.compute_price != 'fixed':
|
||||
self.fixed_price = 0.0
|
||||
if self.compute_price != 'percentage':
|
||||
|
|
@ -229,11 +393,30 @@ class PricelistItem(models.Model):
|
|||
'base': 'list_price',
|
||||
'price_discount': 0.0,
|
||||
'price_surcharge': 0.0,
|
||||
'price_markup': 0.0,
|
||||
'price_round': 0.0,
|
||||
'price_min_margin': 0.0,
|
||||
'price_max_margin': 0.0,
|
||||
})
|
||||
|
||||
@api.onchange('display_applied_on')
|
||||
def _onchange_display_applied_on(self):
|
||||
for item in self:
|
||||
if not (item.product_tmpl_id or item.categ_id):
|
||||
item.update({'applied_on': '3_global'})
|
||||
elif item.display_applied_on == '1_product':
|
||||
item.update({
|
||||
'applied_on': '1_product',
|
||||
'categ_id': None,
|
||||
})
|
||||
elif item.display_applied_on == '2_product_category':
|
||||
item.update({
|
||||
'product_id': None,
|
||||
'product_tmpl_id': None,
|
||||
'applied_on': '2_product_category',
|
||||
'product_uom_name': None,
|
||||
})
|
||||
|
||||
@api.onchange('product_id')
|
||||
def _onchange_product_id(self):
|
||||
has_product_id = self.filtered('product_id')
|
||||
|
|
@ -254,25 +437,43 @@ class PricelistItem(models.Model):
|
|||
|
||||
@api.onchange('product_id', 'product_tmpl_id', 'categ_id')
|
||||
def _onchange_rule_content(self):
|
||||
if not self.user_has_groups('product.group_sale_pricelist') and not self.env.context.get('default_applied_on', False):
|
||||
# If advanced pricelists are disabled (applied_on field is not visible)
|
||||
# AND we aren't coming from a specific product template/variant.
|
||||
variants_rules = self.filtered('product_id')
|
||||
if not self.env.context.get('default_applied_on', False):
|
||||
# If we aren't coming from a specific product template/variant.
|
||||
variants_rules = self.filtered(
|
||||
lambda r: bool(r.product_id) and bool(r.product_tmpl_id)
|
||||
)
|
||||
template_rules = (self-variants_rules).filtered('product_tmpl_id')
|
||||
category_rules = self.filtered(
|
||||
lambda cat: bool(cat.categ_id) and cat.categ_id.name != 'All'
|
||||
)
|
||||
variants_rules.update({'applied_on': '0_product_variant'})
|
||||
template_rules.update({'applied_on': '1_product'})
|
||||
(self-variants_rules-template_rules).update({'applied_on': '3_global'})
|
||||
category_rules.update({'applied_on': '2_product_category'})
|
||||
global_rules = self - variants_rules - template_rules - category_rules
|
||||
global_rules.update({'applied_on': '3_global'})
|
||||
|
||||
@api.onchange('price_round')
|
||||
def _onchange_price_round(self):
|
||||
if any(item.price_round and item.price_round < 0.0 for item in self):
|
||||
raise ValidationError(_("The rounding method must be strictly positive."))
|
||||
|
||||
@api.onchange('date_start', 'date_end')
|
||||
def _onchange_validity_period(self):
|
||||
self._check_date_range()
|
||||
|
||||
#=== CRUD METHODS ===#
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for values in vals_list:
|
||||
if values.get('product_id') and not values.get('product_tmpl_id'):
|
||||
# Deduce product template from product variant if not specified.
|
||||
# Ensures that the pricelist rule is properly configured and displayed in the UX
|
||||
# even in case of partial/incomplete data (mostly for imports).
|
||||
values['product_tmpl_id'] = self.env['product.product'].browse(
|
||||
values.get('product_id')
|
||||
).product_tmpl_id.id
|
||||
|
||||
if not values.get('applied_on'):
|
||||
values['applied_on'] = (
|
||||
'0_product_variant' if values.get('product_id') else
|
||||
|
|
@ -284,31 +485,28 @@ class PricelistItem(models.Model):
|
|||
# Ensure item consistency for later searches.
|
||||
applied_on = values['applied_on']
|
||||
if applied_on == '3_global':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None, categ_id=None))
|
||||
values.update({'product_id': None, 'product_tmpl_id': None, 'categ_id': None})
|
||||
elif applied_on == '2_product_category':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None))
|
||||
values.update({'product_id': None, 'product_tmpl_id': None})
|
||||
elif applied_on == '1_product':
|
||||
values.update(dict(product_id=None, categ_id=None))
|
||||
values.update({'product_id': None, 'categ_id': None})
|
||||
elif applied_on == '0_product_variant':
|
||||
values.update(dict(categ_id=None))
|
||||
values.update({'categ_id': None})
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, values):
|
||||
if values.get('applied_on', False):
|
||||
def write(self, vals):
|
||||
if vals.get('applied_on', False):
|
||||
# Ensure item consistency for later searches.
|
||||
applied_on = values['applied_on']
|
||||
applied_on = vals['applied_on']
|
||||
if applied_on == '3_global':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None, categ_id=None))
|
||||
vals.update({'product_id': None, 'product_tmpl_id': None, 'categ_id': None})
|
||||
elif applied_on == '2_product_category':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None))
|
||||
vals.update({'product_id': None, 'product_tmpl_id': None})
|
||||
elif applied_on == '1_product':
|
||||
values.update(dict(product_id=None, categ_id=None))
|
||||
vals.update({'product_id': None, 'categ_id': None})
|
||||
elif applied_on == '0_product_variant':
|
||||
values.update(dict(categ_id=None))
|
||||
return super().write(values)
|
||||
|
||||
def toggle_active(self):
|
||||
raise ValidationError(_("You cannot disable a pricelist rule, please delete it or archive its pricelist instead."))
|
||||
vals.update({'categ_id': None})
|
||||
return super().write(vals)
|
||||
|
||||
#=== BUSINESS METHODS ===#
|
||||
|
||||
|
|
@ -331,46 +529,52 @@ class PricelistItem(models.Model):
|
|||
res = False
|
||||
|
||||
elif self.applied_on == "2_product_category":
|
||||
if (
|
||||
if not product.categ_id or (
|
||||
product.categ_id != self.categ_id
|
||||
and not product.categ_id.parent_path.startswith(self.categ_id.parent_path)
|
||||
):
|
||||
res = False
|
||||
else:
|
||||
# Applied on a specific product template/variant
|
||||
if is_product_template:
|
||||
if self.applied_on == "1_product" and product.id != self.product_tmpl_id.id:
|
||||
res = False
|
||||
elif self.applied_on == "0_product_variant" and not (
|
||||
product.product_variant_count == 1
|
||||
and product.product_variant_id.id == self.product_id.id
|
||||
):
|
||||
# product self acceptable on template if has only one variant
|
||||
res = False
|
||||
else:
|
||||
if self.applied_on == "1_product" and product.product_tmpl_id.id != self.product_tmpl_id.id:
|
||||
res = False
|
||||
elif self.applied_on == "0_product_variant" and product.id != self.product_id.id:
|
||||
res = False
|
||||
# Applied on a specific product template/variant
|
||||
elif is_product_template:
|
||||
if self.applied_on == "1_product" and product.id != self.product_tmpl_id.id:
|
||||
res = False
|
||||
elif self.applied_on == "0_product_variant" and not (
|
||||
product.product_variant_count == 1
|
||||
and product.product_variant_id.id == self.product_id.id
|
||||
):
|
||||
# product self acceptable on template if has only one variant
|
||||
res = False
|
||||
elif (
|
||||
self.applied_on == "1_product"
|
||||
and product.product_tmpl_id.id != self.product_tmpl_id.id
|
||||
) or (
|
||||
self.applied_on == "0_product_variant" and product.id != self.product_id.id
|
||||
):
|
||||
res = False
|
||||
|
||||
return res
|
||||
|
||||
def _compute_price(self, product, quantity, uom, date, currency=None):
|
||||
def _compute_price(self, product, quantity, uom, date, currency=None, **kwargs):
|
||||
"""Compute the unit price of a product in the context of a pricelist application.
|
||||
|
||||
Note: self and self.ensure_one()
|
||||
|
||||
:param product: recordset of product (product.product/product.template)
|
||||
:param float qty: quantity of products requested (in given uom)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param uom: unit of measure (uom.uom record)
|
||||
:param datetime date: date to use for price computation and currency conversions
|
||||
:param currency: pricelist currency (for the specific case where self is empty)
|
||||
:param currency: currency (for the case where self is empty)
|
||||
:param dict kwargs: unused parameters available for overrides
|
||||
|
||||
:returns: price according to pricelist rule, expressed in pricelist currency
|
||||
:returns: price according to pricelist rule or the product price, expressed in the param
|
||||
currency, the pricelist currency or the company currency
|
||||
:rtype: float
|
||||
"""
|
||||
self and self.ensure_one() # self is at most one record
|
||||
product.ensure_one()
|
||||
uom.ensure_one()
|
||||
|
||||
currency = currency or self.currency_id
|
||||
currency = currency or self.currency_id or self.env.company.currency_id
|
||||
currency.ensure_one()
|
||||
|
||||
# Pricelist specific values are specified according to product UoM
|
||||
|
|
@ -384,15 +588,16 @@ class PricelistItem(models.Model):
|
|||
if self.compute_price == 'fixed':
|
||||
price = convert(self.fixed_price)
|
||||
elif self.compute_price == 'percentage':
|
||||
base_price = self._compute_base_price(product, quantity, uom, date, currency)
|
||||
base_price = self._compute_base_price(product, quantity, uom, date, currency, **kwargs)
|
||||
price = (base_price - (base_price * (self.percent_price / 100))) or 0.0
|
||||
elif self.compute_price == 'formula':
|
||||
base_price = self._compute_base_price(product, quantity, uom, date, currency)
|
||||
base_price = self._compute_base_price(product, quantity, uom, date, currency, **kwargs)
|
||||
# complete formula
|
||||
price_limit = base_price
|
||||
price = (base_price - (base_price * (self.price_discount / 100))) or 0.0
|
||||
discount = self.price_discount if self.base != 'standard_price' else -self.price_markup
|
||||
price = base_price - (base_price * (discount / 100))
|
||||
if self.price_round:
|
||||
price = tools.float_round(price, precision_rounding=self.price_round)
|
||||
price = float_round(price, precision_rounding=self.price_round)
|
||||
|
||||
if self.price_surcharge:
|
||||
price += convert(self.price_surcharge)
|
||||
|
|
@ -403,36 +608,64 @@ class PricelistItem(models.Model):
|
|||
if self.price_max_margin:
|
||||
price = min(price, price_limit + convert(self.price_max_margin))
|
||||
else: # empty self, or extended pricelist price computation logic
|
||||
price = self._compute_base_price(product, quantity, uom, date, currency)
|
||||
price = self._compute_base_price(product, quantity, uom, date, currency, **kwargs)
|
||||
|
||||
return price
|
||||
|
||||
def _compute_base_price(self, product, quantity, uom, date, target_currency):
|
||||
""" Compute the base price for a given rule
|
||||
def _compute_base_price(self, product, quantity, uom, date, currency, **kwargs):
|
||||
"""Compute the base price for a given rule.
|
||||
|
||||
:param product: recordset of product (product.product/product.template)
|
||||
:param float quantity: quantity of products requested (in given uom)
|
||||
:param uom: unit of measure (uom.uom record)
|
||||
:param datetime date: date to use for price computation and currency conversions
|
||||
:param currency: currency in which the returned price must be expressed
|
||||
|
||||
:returns: base price, expressed in provided pricelist currency
|
||||
:rtype: float
|
||||
"""
|
||||
currency.ensure_one()
|
||||
|
||||
rule_base = self.base or 'list_price'
|
||||
if rule_base == 'pricelist' and self.base_pricelist_id:
|
||||
price = self.base_pricelist_id._get_product_price(
|
||||
product, quantity, currency=self.base_pricelist_id.currency_id, uom=uom, date=date,
|
||||
**kwargs
|
||||
)
|
||||
src_currency = self.base_pricelist_id.currency_id
|
||||
elif rule_base == "standard_price":
|
||||
src_currency = product.cost_currency_id
|
||||
price = product._price_compute(rule_base, uom=uom, date=date)[product.id]
|
||||
else: # list_price
|
||||
src_currency = product.currency_id
|
||||
price = product._price_compute(rule_base, uom=uom, date=date)[product.id]
|
||||
|
||||
if src_currency != currency:
|
||||
price = src_currency._convert(price, currency, self.env.company, date, round=False)
|
||||
|
||||
return price
|
||||
|
||||
def _compute_price_before_discount(self, *args, **kwargs):
|
||||
"""Compute the base price of the given rule, considering chained pricelists.
|
||||
|
||||
:param product: recordset of product (product.product/product.template)
|
||||
:param float qty: quantity of products requested (in given uom)
|
||||
:param uom: unit of measure (uom.uom record)
|
||||
:param datetime date: date to use for price computation and currency conversions
|
||||
:param target_currency: pricelist currency
|
||||
:param currency: currency in which the returned price must be expressed
|
||||
|
||||
:returns: base price, expressed in provided pricelist currency
|
||||
:rtype: float
|
||||
"""
|
||||
target_currency.ensure_one()
|
||||
pricelist_item = self
|
||||
# Find the lowest pricelist rule whose pricelist is configured to show the discount to the
|
||||
# customer.
|
||||
while pricelist_item.base == 'pricelist':
|
||||
rule_id = pricelist_item.base_pricelist_id._get_product_rule(*args, **kwargs)
|
||||
rule_pricelist_item = self.env['product.pricelist.item'].browse(rule_id)
|
||||
if rule_pricelist_item and rule_pricelist_item.compute_price == 'percentage':
|
||||
pricelist_item = rule_pricelist_item
|
||||
else:
|
||||
break
|
||||
|
||||
rule_base = self.base or 'list_price'
|
||||
if rule_base == 'pricelist' and self.base_pricelist_id:
|
||||
price = self.base_pricelist_id._get_product_price(product, quantity, uom, date)
|
||||
src_currency = self.base_pricelist_id.currency_id
|
||||
elif rule_base == "standard_price":
|
||||
src_currency = product.cost_currency_id
|
||||
price = product.price_compute(rule_base, uom=uom, date=date)[product.id]
|
||||
else: # list_price
|
||||
src_currency = product.currency_id
|
||||
price = product.price_compute(rule_base, uom=uom, date=date)[product.id]
|
||||
|
||||
if src_currency != target_currency:
|
||||
price = src_currency._convert(price, target_currency, self.env.company, date, round=False)
|
||||
|
||||
return price
|
||||
return pricelist_item._compute_base_price(*args, **kwargs)
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -4,28 +4,12 @@
|
|||
from odoo import api, fields, models, _
|
||||
|
||||
|
||||
class SupplierInfo(models.Model):
|
||||
_name = "product.supplierinfo"
|
||||
class ProductSupplierinfo(models.Model):
|
||||
_name = 'product.supplierinfo'
|
||||
_description = "Supplier Pricelist"
|
||||
_order = 'sequence, min_qty DESC, price, id'
|
||||
_rec_name = 'partner_id'
|
||||
|
||||
def _default_product_id(self):
|
||||
product_id = self.env.get('default_product_id')
|
||||
if not product_id:
|
||||
model, active_id = [self.env.context.get(k) for k in ['model', 'active_id']]
|
||||
if model == 'product.product' and active_id:
|
||||
product_id = self.env[model].browse(active_id).exists()
|
||||
return product_id
|
||||
|
||||
def _domain_product_id(self):
|
||||
domain = "product_tmpl_id and [('product_tmpl_id', '=', product_tmpl_id)] or []"
|
||||
if self.env.context.get('base_model_name') == 'product.template':
|
||||
domain = "[('product_tmpl_id', '=', parent.id)]"
|
||||
elif self.env.context.get('base_model_name') == 'product.product':
|
||||
domain = "[('product_tmpl_id', '=', parent.product_tmpl_id)]"
|
||||
return domain
|
||||
|
||||
partner_id = fields.Many2one(
|
||||
'res.partner', 'Vendor',
|
||||
ondelete='cascade', required=True,
|
||||
|
|
@ -38,15 +22,14 @@ class SupplierInfo(models.Model):
|
|||
help="This vendor's product code will be used when printing a request for quotation. Keep empty to use the internal one.")
|
||||
sequence = fields.Integer(
|
||||
'Sequence', default=1, help="Assigns the priority to the list of product vendor.")
|
||||
product_uom = fields.Many2one(
|
||||
'uom.uom', 'Unit of Measure',
|
||||
related='product_tmpl_id.uom_po_id')
|
||||
product_uom_id = fields.Many2one(
|
||||
'uom.uom', 'Unit', compute='_compute_product_uom_id', store=True, readonly=False, required=True, precompute=True)
|
||||
min_qty = fields.Float(
|
||||
'Quantity', default=0.0, required=True, digits="Product Unit of Measure",
|
||||
help="The quantity to purchase from this vendor to benefit from the price, expressed in the vendor Product Unit of Measure if not any, in the default unit of measure of the product otherwise.")
|
||||
'Quantity', default=0.0, required=True, digits="Product Unit",
|
||||
help="The quantity to purchase from this vendor to benefit from the unit price. If a vendor unit is set, quantity should be specified in this unit, otherwise it should be specified in the default unit of the product.")
|
||||
price = fields.Float(
|
||||
'Price', default=0.0, digits='Product Price',
|
||||
required=True, help="The price to purchase a product")
|
||||
'Unit Price', min_display_digits='Product Price', default=0.0, help="The price to purchase a product")
|
||||
price_discounted = fields.Float('Discounted Price', compute='_compute_price_discounted')
|
||||
company_id = fields.Many2one(
|
||||
'res.company', 'Company',
|
||||
default=lambda self: self.env.company.id, index=1)
|
||||
|
|
@ -58,15 +41,49 @@ class SupplierInfo(models.Model):
|
|||
date_end = fields.Date('End Date', help="End date for this vendor price")
|
||||
product_id = fields.Many2one(
|
||||
'product.product', 'Product Variant', check_company=True,
|
||||
domain=_domain_product_id, default=_default_product_id,
|
||||
domain="[('product_tmpl_id', '=', product_tmpl_id)] if product_tmpl_id else []",
|
||||
compute='_compute_product_id', store=True, readonly=False, precompute=True,
|
||||
help="If not set, the vendor price will apply to all variants of this product.")
|
||||
product_tmpl_id = fields.Many2one(
|
||||
'product.template', 'Product Template', check_company=True,
|
||||
index=True, ondelete='cascade')
|
||||
'product.template', 'Product Template', check_company=True, compute='_compute_product_tmpl_id', precompute=True,
|
||||
store=True, readonly=False, required=True, index=True, ondelete='cascade')
|
||||
product_variant_count = fields.Integer('Variant Count', related='product_tmpl_id.product_variant_count')
|
||||
delay = fields.Integer(
|
||||
'Delivery Lead Time', default=1, required=True,
|
||||
'Lead Time', default=1, required=True,
|
||||
help="Lead time in days between the confirmation of the purchase order and the receipt of the products in your warehouse. Used by the scheduler for automatic computation of the purchase order planning.")
|
||||
discount = fields.Float(
|
||||
string="Discount (%)",
|
||||
digits='Discount',
|
||||
readonly=False)
|
||||
|
||||
@api.depends('product_id', 'product_tmpl_id')
|
||||
def _compute_product_uom_id(self):
|
||||
for rec in self:
|
||||
if not rec.product_uom_id:
|
||||
rec.product_uom_id = rec.product_id.uom_id if rec.product_id else rec.product_tmpl_id.uom_id
|
||||
|
||||
@api.depends('product_id', 'product_tmpl_id')
|
||||
def _compute_price(self):
|
||||
for rec in self:
|
||||
rec.price = rec.product_id.standard_price if rec.product_id else rec.product_tmpl_id.standard_price if rec.product_tmpl_id else 0.0
|
||||
|
||||
@api.depends('discount', 'price')
|
||||
def _compute_price_discounted(self):
|
||||
for rec in self:
|
||||
product_uom = (rec.product_id or rec.product_tmpl_id).uom_id
|
||||
rec.price_discounted = rec.product_uom_id._compute_price(rec.price, product_uom) * (1 - rec.discount / 100)
|
||||
|
||||
@api.depends('product_id')
|
||||
def _compute_product_tmpl_id(self):
|
||||
for rec in self:
|
||||
if rec.product_id:
|
||||
rec.product_tmpl_id = rec.product_id.product_tmpl_id
|
||||
|
||||
@api.depends('product_id', 'product_tmpl_id', 'product_variant_count')
|
||||
def _compute_product_id(self):
|
||||
for rec in self:
|
||||
if self.env.get('default_product_id'):
|
||||
rec.product_id = self.env.get('default_product_id')
|
||||
|
||||
@api.onchange('product_tmpl_id')
|
||||
def _onchange_product_tmpl_id(self):
|
||||
|
|
@ -97,3 +114,6 @@ class SupplierInfo(models.Model):
|
|||
def write(self, vals):
|
||||
self._sanitize_vals(vals)
|
||||
return super().write(vals)
|
||||
|
||||
def _get_filtered_supplier(self, company_id, product_id, params=False):
|
||||
return self.filtered(lambda s: (not s.company_id or s.company_id.id == company_id.id) and (s.partner_id.active and (not s.product_id or s.product_id == product_id)))
|
||||
|
|
|
|||
|
|
@ -1,37 +1,62 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from random import randint
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.osv import expression
|
||||
from odoo.fields import Domain
|
||||
|
||||
|
||||
class ProductTag(models.Model):
|
||||
_name = 'product.tag'
|
||||
_description = 'Product Tag'
|
||||
_order = 'sequence, id'
|
||||
|
||||
def _get_default_color(self):
|
||||
return randint(1, 11)
|
||||
def _get_default_template_id(self):
|
||||
return self.env['product.template'].browse(self.env.context.get('product_template_id'))
|
||||
|
||||
name = fields.Char('Tag Name', required=True, translate=True)
|
||||
color = fields.Integer('Color', default=_get_default_color)
|
||||
def _get_default_variant_id(self):
|
||||
return self.env['product.product'].browse(self.env.context.get('product_variant_id'))
|
||||
|
||||
product_template_ids = fields.Many2many('product.template', 'product_tag_product_template_rel')
|
||||
product_product_ids = fields.Many2many('product.product', 'product_tag_product_product_rel')
|
||||
name = fields.Char(string="Name", required=True, translate=True)
|
||||
sequence = fields.Integer(default=10)
|
||||
color = fields.Char(string="Color", default='#3C3C3C')
|
||||
product_template_ids = fields.Many2many(
|
||||
string="Product Templates",
|
||||
comodel_name='product.template',
|
||||
relation='product_tag_product_template_rel',
|
||||
default=_get_default_template_id,
|
||||
)
|
||||
product_product_ids = fields.Many2many(
|
||||
string="Product Variants",
|
||||
comodel_name='product.product',
|
||||
relation='product_tag_product_product_rel',
|
||||
domain="[('attribute_line_ids', '!=', False), ('product_tmpl_id', 'not in', product_template_ids)]",
|
||||
default=_get_default_variant_id,
|
||||
)
|
||||
product_ids = fields.Many2many(
|
||||
'product.product', string='All Product Variants using this Tag',
|
||||
compute='_compute_product_ids', search='_search_product_ids'
|
||||
)
|
||||
visible_to_customers = fields.Boolean(
|
||||
string="Visible to customers",
|
||||
help="Whether the tag is displayed to customers.",
|
||||
default=True,
|
||||
)
|
||||
image = fields.Image(string="Image", max_width=200, max_height=200)
|
||||
|
||||
_sql_constraints = [
|
||||
('name_uniq', 'unique (name)', "Tag name already exists !"),
|
||||
]
|
||||
_name_uniq = models.Constraint(
|
||||
'unique (name)',
|
||||
'Tag name already exists!',
|
||||
)
|
||||
|
||||
@api.depends('product_template_ids', 'product_product_ids')
|
||||
def _compute_product_ids(self):
|
||||
for tag in self:
|
||||
tag.product_ids = tag.product_template_ids.product_variant_ids | tag.product_product_ids
|
||||
|
||||
def copy_data(self, default=None):
|
||||
vals_list = super().copy_data(default=default)
|
||||
return [dict(vals, name=self.env._("%s (copy)", tag.name)) for tag, vals in zip(self, vals_list)]
|
||||
|
||||
def _search_product_ids(self, operator, operand):
|
||||
if operator in expression.NEGATIVE_TERM_OPERATORS:
|
||||
return [('product_template_ids.product_variant_ids', operator, operand), ('product_product_ids', operator, operand)]
|
||||
if operator in Domain.NEGATIVE_OPERATORS:
|
||||
return NotImplemented
|
||||
return ['|', ('product_template_ids.product_variant_ids', operator, operand), ('product_product_ids', operator, operand)]
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,47 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class ProductTemplateAttributeExclusion(models.Model):
|
||||
_name = 'product.template.attribute.exclusion'
|
||||
_description = "Product Template Attribute Exclusion"
|
||||
_order = 'product_tmpl_id, id'
|
||||
|
||||
product_template_attribute_value_id = fields.Many2one(
|
||||
comodel_name='product.template.attribute.value',
|
||||
string="Attribute Value",
|
||||
ondelete='cascade',
|
||||
index=True)
|
||||
product_tmpl_id = fields.Many2one(
|
||||
comodel_name='product.template',
|
||||
string="Product Template",
|
||||
ondelete='cascade',
|
||||
required=True,
|
||||
index=True)
|
||||
value_ids = fields.Many2many(
|
||||
comodel_name='product.template.attribute.value',
|
||||
relation='product_attr_exclusion_value_ids_rel',
|
||||
string="Attribute Values",
|
||||
domain="[('product_tmpl_id', '=', product_tmpl_id), ('ptav_active', '=', True)]")
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
exclusions = super().create(vals_list)
|
||||
exclusions.product_tmpl_id._create_variant_ids()
|
||||
return exclusions
|
||||
|
||||
def unlink(self):
|
||||
# Keep a reference to the related templates before the deletion.
|
||||
templates = self.product_tmpl_id
|
||||
res = super().unlink()
|
||||
templates._create_variant_ids()
|
||||
return res
|
||||
|
||||
def write(self, vals):
|
||||
templates = self.env['product.template']
|
||||
if 'product_tmpl_id' in vals:
|
||||
templates = self.product_tmpl_id
|
||||
res = super().write(vals)
|
||||
(templates | self.product_tmpl_id)._create_variant_ids()
|
||||
return res
|
||||
|
|
@ -0,0 +1,283 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import _, api, fields, models, tools
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
from odoo.fields import Command
|
||||
|
||||
|
||||
class ProductTemplateAttributeLine(models.Model):
|
||||
"""Attributes available on product.template with their selected values in a m2m.
|
||||
Used as a configuration model to generate the appropriate product.template.attribute.value"""
|
||||
|
||||
_name = 'product.template.attribute.line'
|
||||
_rec_name = 'attribute_id'
|
||||
_rec_names_search = ['attribute_id', 'value_ids']
|
||||
_description = "Product Template Attribute Line"
|
||||
_order = 'sequence, attribute_id, id'
|
||||
|
||||
active = fields.Boolean(default=True)
|
||||
product_tmpl_id = fields.Many2one(
|
||||
comodel_name='product.template',
|
||||
string="Product Template",
|
||||
ondelete='cascade',
|
||||
required=True,
|
||||
index=True)
|
||||
sequence = fields.Integer("Sequence", default=10)
|
||||
attribute_id = fields.Many2one(
|
||||
comodel_name='product.attribute',
|
||||
string="Attribute",
|
||||
ondelete='restrict',
|
||||
required=True,
|
||||
index=True)
|
||||
value_ids = fields.Many2many(
|
||||
comodel_name='product.attribute.value',
|
||||
relation='product_attribute_value_product_template_attribute_line_rel',
|
||||
string="Values",
|
||||
domain="[('attribute_id', '=', attribute_id)]",
|
||||
ondelete='restrict')
|
||||
value_count = fields.Integer(compute='_compute_value_count', store=True)
|
||||
product_template_value_ids = fields.One2many(
|
||||
comodel_name='product.template.attribute.value',
|
||||
inverse_name='attribute_line_id',
|
||||
string="Product Attribute Values")
|
||||
|
||||
@api.depends('value_ids')
|
||||
def _compute_value_count(self):
|
||||
for record in self:
|
||||
record.value_count = len(record.value_ids)
|
||||
|
||||
@api.onchange('attribute_id')
|
||||
def _onchange_attribute_id(self):
|
||||
if self.attribute_id.create_variant == 'no_variant':
|
||||
self.value_ids = self.env['product.attribute.value'].search([
|
||||
('attribute_id', '=', self.attribute_id.id),
|
||||
])
|
||||
else:
|
||||
self.value_ids = self.value_ids.filtered(
|
||||
lambda pav: pav.attribute_id == self.attribute_id
|
||||
)
|
||||
|
||||
@api.constrains('active', 'value_ids', 'attribute_id')
|
||||
def _check_valid_values(self):
|
||||
for ptal in self:
|
||||
if ptal.active and not ptal.value_ids:
|
||||
raise ValidationError(_(
|
||||
"The attribute %(attribute)s must have at least one value for the product %(product)s.",
|
||||
attribute=ptal.attribute_id.display_name,
|
||||
product=ptal.product_tmpl_id.display_name,
|
||||
))
|
||||
for pav in ptal.value_ids:
|
||||
if pav.attribute_id != ptal.attribute_id:
|
||||
raise ValidationError(_(
|
||||
"On the product %(product)s you cannot associate the value %(value)s"
|
||||
" with the attribute %(attribute)s because they do not match.",
|
||||
product=ptal.product_tmpl_id.display_name,
|
||||
value=pav.display_name,
|
||||
attribute=ptal.attribute_id.display_name,
|
||||
))
|
||||
return True
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
"""Override to:
|
||||
- Activate archived lines having the same configuration (if they exist)
|
||||
instead of creating new lines.
|
||||
- Set up related values and related variants.
|
||||
|
||||
Reactivating existing lines allows to re-use existing variants when
|
||||
possible, keeping their configuration and avoiding duplication.
|
||||
"""
|
||||
create_values = []
|
||||
activated_lines = self.env['product.template.attribute.line']
|
||||
for value in vals_list:
|
||||
vals = dict(value, active=value.get('active', True))
|
||||
# While not ideal for peformance, this search has to be done at each
|
||||
# step to exclude the lines that might have been activated at a
|
||||
# previous step. Since `vals_list` will likely be a small list in
|
||||
# all use cases, this is an acceptable trade-off.
|
||||
archived_ptal = self.search([
|
||||
('active', '=', False),
|
||||
('product_tmpl_id', '=', vals.pop('product_tmpl_id', 0)),
|
||||
('attribute_id', '=', vals.pop('attribute_id', 0)),
|
||||
], limit=1)
|
||||
if archived_ptal:
|
||||
# Write given `vals` in addition of `active` to ensure
|
||||
# `value_ids` or other fields passed to `create` are saved too,
|
||||
# but change the context to avoid updating the values and the
|
||||
# variants until all the expected lines are created/updated.
|
||||
archived_ptal.with_context(update_product_template_attribute_values=False).write(vals)
|
||||
activated_lines += archived_ptal
|
||||
else:
|
||||
create_values.append(value)
|
||||
res = activated_lines + super().create(create_values)
|
||||
if self.env.context.get("create_product_product", True):
|
||||
res._update_product_template_attribute_values()
|
||||
return res
|
||||
|
||||
def write(self, vals):
|
||||
"""Override to:
|
||||
- Add constraints to prevent doing changes that are not supported such
|
||||
as modifying the template or the attribute of existing lines.
|
||||
- Clean up related values and related variants when archiving or when
|
||||
updating `value_ids`.
|
||||
"""
|
||||
values = vals
|
||||
if 'product_tmpl_id' in values:
|
||||
for ptal in self:
|
||||
if ptal.product_tmpl_id.id != values['product_tmpl_id']:
|
||||
raise UserError(_(
|
||||
"You cannot move the attribute %(attribute)s from the product"
|
||||
" %(product_src)s to the product %(product_dest)s.",
|
||||
attribute=ptal.attribute_id.display_name,
|
||||
product_src=ptal.product_tmpl_id.display_name,
|
||||
product_dest=values['product_tmpl_id'],
|
||||
))
|
||||
|
||||
if 'attribute_id' in values:
|
||||
for ptal in self:
|
||||
if ptal.attribute_id.id != values['attribute_id']:
|
||||
raise UserError(_(
|
||||
"On the product %(product)s you cannot transform the attribute"
|
||||
" %(attribute_src)s into the attribute %(attribute_dest)s.",
|
||||
product=ptal.product_tmpl_id.display_name,
|
||||
attribute_src=ptal.attribute_id.display_name,
|
||||
attribute_dest=values['attribute_id'],
|
||||
))
|
||||
# Remove all values while archiving to make sure the line is clean if it
|
||||
# is ever activated again.
|
||||
if not values.get('active', True):
|
||||
values['value_ids'] = [Command.clear()]
|
||||
res = super().write(values)
|
||||
if 'active' in values:
|
||||
self.env.flush_all()
|
||||
self.env['product.template'].invalidate_model(['attribute_line_ids'])
|
||||
# If coming from `create`, no need to update the values and the variants
|
||||
# before all lines are created.
|
||||
if self.env.context.get('update_product_template_attribute_values', True):
|
||||
self._update_product_template_attribute_values()
|
||||
return res
|
||||
|
||||
def unlink(self):
|
||||
"""Override to:
|
||||
- Archive the line if unlink is not possible.
|
||||
- Clean up related values and related variants.
|
||||
|
||||
Archiving is typically needed when the line has values that can't be
|
||||
deleted because they are referenced elsewhere (on a variant that can't
|
||||
be deleted, on a sales order line, ...).
|
||||
"""
|
||||
# Try to remove the values first to remove some potentially blocking
|
||||
# references, which typically works:
|
||||
# - For single value lines because the values are directly removed from
|
||||
# the variants.
|
||||
# - For values that are present on variants that can be deleted.
|
||||
self.product_template_value_ids._only_active().unlink()
|
||||
# Keep a reference to the related templates before the deletion.
|
||||
templates = self.product_tmpl_id
|
||||
# Now delete or archive the lines.
|
||||
ptal_to_archive = self.env['product.template.attribute.line']
|
||||
for ptal in self:
|
||||
try:
|
||||
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
|
||||
super(ProductTemplateAttributeLine, ptal).unlink()
|
||||
except Exception:
|
||||
# We catch all kind of exceptions to be sure that the operation
|
||||
# doesn't fail.
|
||||
ptal_to_archive += ptal
|
||||
ptal_to_archive.action_archive() # only calls write if there are records
|
||||
# For archived lines `_update_product_template_attribute_values` is
|
||||
# implicitly called during the `write` above, but for products that used
|
||||
# unlinked lines `_create_variant_ids` has to be called manually.
|
||||
(templates - ptal_to_archive.product_tmpl_id)._create_variant_ids()
|
||||
return True
|
||||
|
||||
def _update_product_template_attribute_values(self):
|
||||
"""Create or unlink `product.template.attribute.value` for each line in
|
||||
`self` based on `value_ids`.
|
||||
|
||||
The goal is to delete all values that are not in `value_ids`, to
|
||||
activate those in `value_ids` that are currently archived, and to create
|
||||
those in `value_ids` that didn't exist.
|
||||
|
||||
This is a trick for the form view and for performance in general,
|
||||
because we don't want to generate in advance all possible values for all
|
||||
templates, but only those that will be selected.
|
||||
"""
|
||||
ProductTemplateAttributeValue = self.env['product.template.attribute.value']
|
||||
ptav_to_create = []
|
||||
ptav_to_unlink = ProductTemplateAttributeValue
|
||||
for ptal in self:
|
||||
ptav_to_activate = ProductTemplateAttributeValue
|
||||
remaining_pav = set(ptal.value_ids.ids)
|
||||
for ptav in ptal.product_template_value_ids:
|
||||
if ptav.product_attribute_value_id.id not in remaining_pav:
|
||||
# Remove values that existed but don't exist anymore, but
|
||||
# ignore those that are already archived because if they are
|
||||
# archived it means they could not be deleted previously.
|
||||
if ptav.ptav_active:
|
||||
ptav_to_unlink += ptav
|
||||
else:
|
||||
# Activate corresponding values that are currently archived.
|
||||
remaining_pav.remove(ptav.product_attribute_value_id.id)
|
||||
if not ptav.ptav_active:
|
||||
ptav_to_activate += ptav
|
||||
|
||||
ptav_groups = ProductTemplateAttributeValue._read_group([
|
||||
('ptav_active', '=', False),
|
||||
('product_tmpl_id', '=', ptal.product_tmpl_id.id),
|
||||
('attribute_id', '=', ptal.attribute_id.id),
|
||||
('product_attribute_value_id', 'in', list(remaining_pav)),
|
||||
], groupby=["product_attribute_value_id"], aggregates=["id:recordset"])
|
||||
|
||||
for pav, ptav in ptav_groups:
|
||||
ptav = ptav[0]
|
||||
ptav.write({'ptav_active': True, 'attribute_line_id': ptal.id})
|
||||
# If the value was marked for deletion, now keep it.
|
||||
ptav_to_unlink -= ptav
|
||||
remaining_pav.remove(pav.id)
|
||||
|
||||
remaining_pav = self.env['product.attribute.value'].sudo().browse(sorted(remaining_pav))
|
||||
|
||||
for pav in remaining_pav:
|
||||
ptav_to_create.append({
|
||||
'product_attribute_value_id': pav.id,
|
||||
'attribute_line_id': ptal.id,
|
||||
'price_extra': pav.default_extra_price,
|
||||
})
|
||||
# Handle active at each step in case a following line might want to
|
||||
# re-use a value that was archived at a previous step.
|
||||
ptav_to_activate.write({'ptav_active': True})
|
||||
ptav_to_unlink.write({'ptav_active': False})
|
||||
if ptav_to_unlink:
|
||||
ptav_to_unlink.unlink()
|
||||
ProductTemplateAttributeValue.create(ptav_to_create)
|
||||
self.product_tmpl_id._create_variant_ids()
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda ptal: ptal.attribute_id.create_variant != 'no_variant')
|
||||
|
||||
def _is_configurable(self):
|
||||
self.ensure_one()
|
||||
return (
|
||||
len(self.value_ids) >= 2
|
||||
or self.attribute_id.display_type == 'multi'
|
||||
or self.value_ids.is_custom
|
||||
)
|
||||
|
||||
@api.readonly
|
||||
def action_open_attribute_values(self):
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _("Product Variant Values"),
|
||||
'res_model': 'product.template.attribute.value',
|
||||
'view_mode': 'list,form',
|
||||
'domain': [('id', 'in', self.product_template_value_ids.ids)],
|
||||
'views': [
|
||||
(self.env.ref('product.product_template_attribute_value_view_tree').id, 'list'),
|
||||
(self.env.ref('product.product_template_attribute_value_view_form').id, 'form'),
|
||||
],
|
||||
'context': {
|
||||
'search_default_active': 1,
|
||||
'product_invisible': True,
|
||||
},
|
||||
}
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from random import randint
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo.exceptions import UserError, ValidationError
|
||||
from odoo.fields import Command
|
||||
|
||||
|
||||
class ProductTemplateAttributeValue(models.Model):
|
||||
"""Materialized relationship between attribute values
|
||||
and product template generated by the product.template.attribute.line"""
|
||||
|
||||
_name = 'product.template.attribute.value'
|
||||
_description = "Product Template Attribute Value"
|
||||
_order = 'attribute_line_id, product_attribute_value_id, id'
|
||||
|
||||
def _get_default_color(self):
|
||||
return randint(1, 11)
|
||||
|
||||
# Not just `active` because we always want to show the values except in
|
||||
# specific case, as opposed to `active_test`.
|
||||
ptav_active = fields.Boolean(string="Active", default=True)
|
||||
name = fields.Char(string="Value", related="product_attribute_value_id.name")
|
||||
|
||||
# defining fields: the product template attribute line and the product attribute value
|
||||
product_attribute_value_id = fields.Many2one(
|
||||
comodel_name='product.attribute.value',
|
||||
string="Attribute Value",
|
||||
required=True, ondelete='cascade', index=True)
|
||||
attribute_line_id = fields.Many2one(
|
||||
comodel_name='product.template.attribute.line',
|
||||
required=True, ondelete='cascade', index=True)
|
||||
# configuration fields: the price_extra and the exclusion rules
|
||||
price_extra = fields.Float(
|
||||
string="Extra Price",
|
||||
default=0.0,
|
||||
min_display_digits='Product Price',
|
||||
help="Extra price for the variant with this attribute value on sale price."
|
||||
" eg. 200 price extra, 1000 + 200 = 1200.")
|
||||
currency_id = fields.Many2one(related='attribute_line_id.product_tmpl_id.currency_id')
|
||||
|
||||
exclude_for = fields.One2many(
|
||||
comodel_name='product.template.attribute.exclusion',
|
||||
inverse_name='product_template_attribute_value_id',
|
||||
string="Exclude for",
|
||||
help="Make this attribute value not compatible with "
|
||||
"other values of the product or some attribute values of optional and accessory products.")
|
||||
|
||||
# related fields: product template and product attribute
|
||||
product_tmpl_id = fields.Many2one(
|
||||
related='attribute_line_id.product_tmpl_id', store=True, index=True)
|
||||
attribute_id = fields.Many2one(
|
||||
related='attribute_line_id.attribute_id', store=True, index=True)
|
||||
ptav_product_variant_ids = fields.Many2many(
|
||||
comodel_name='product.product', relation='product_variant_combination',
|
||||
string="Related Variants", readonly=True)
|
||||
|
||||
html_color = fields.Char(string="HTML Color Index", related='product_attribute_value_id.html_color')
|
||||
is_custom = fields.Boolean(related='product_attribute_value_id.is_custom')
|
||||
display_type = fields.Selection(related='product_attribute_value_id.display_type')
|
||||
color = fields.Integer(string="Color", default=_get_default_color)
|
||||
image = fields.Image(related='product_attribute_value_id.image')
|
||||
|
||||
_attribute_value_unique = models.Constraint(
|
||||
'unique(attribute_line_id, product_attribute_value_id)',
|
||||
'Each value should be defined only once per attribute per product.',
|
||||
)
|
||||
|
||||
@api.constrains('attribute_line_id', 'product_attribute_value_id')
|
||||
def _check_valid_values(self):
|
||||
for ptav in self:
|
||||
if ptav.ptav_active and ptav.product_attribute_value_id not in ptav.attribute_line_id.value_ids:
|
||||
raise ValidationError(_(
|
||||
"The value %(value)s is not defined for the attribute %(attribute)s"
|
||||
" on the product %(product)s.",
|
||||
value=ptav.product_attribute_value_id.display_name,
|
||||
attribute=ptav.attribute_id.display_name,
|
||||
product=ptav.product_tmpl_id.display_name,
|
||||
))
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
if any('ptav_product_variant_ids' in v for v in vals_list):
|
||||
# Force write on this relation from `product.product` to properly
|
||||
# trigger `_compute_combination_indices`.
|
||||
raise UserError(_("You cannot update related variants from the values. Please update related values from the variants."))
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, vals):
|
||||
values = vals
|
||||
if 'ptav_product_variant_ids' in values:
|
||||
# Force write on this relation from `product.product` to properly
|
||||
# trigger `_compute_combination_indices`.
|
||||
raise UserError(_("You cannot update related variants from the values. Please update related values from the variants."))
|
||||
pav_in_values = 'product_attribute_value_id' in values
|
||||
product_in_values = 'product_tmpl_id' in values
|
||||
if pav_in_values or product_in_values:
|
||||
for ptav in self:
|
||||
if pav_in_values and ptav.product_attribute_value_id.id != values['product_attribute_value_id']:
|
||||
raise UserError(_(
|
||||
"You cannot change the value of the value %(value)s set on product %(product)s.",
|
||||
value=ptav.display_name,
|
||||
product=ptav.product_tmpl_id.display_name,
|
||||
))
|
||||
if product_in_values and ptav.product_tmpl_id.id != values['product_tmpl_id']:
|
||||
raise UserError(_(
|
||||
"You cannot change the product of the value %(value)s set on product %(product)s.",
|
||||
value=ptav.display_name,
|
||||
product=ptav.product_tmpl_id.display_name,
|
||||
))
|
||||
res = super().write(values)
|
||||
if 'exclude_for' in values:
|
||||
self.product_tmpl_id._create_variant_ids()
|
||||
return res
|
||||
|
||||
def unlink(self):
|
||||
"""Override to:
|
||||
- Clean up the variants that use any of the values in self:
|
||||
- Remove the value from the variant if the value belonged to an
|
||||
attribute line with only one value.
|
||||
- Unlink or archive all related variants.
|
||||
- Archive the value if unlink is not possible.
|
||||
|
||||
Archiving is typically needed when the value is referenced elsewhere
|
||||
(on a variant that can't be deleted, on a sales order line, ...).
|
||||
"""
|
||||
# Directly remove the values from the variants for lines that had single
|
||||
# value (counting also the values that are archived).
|
||||
single_values = self.filtered(lambda ptav: len(ptav.attribute_line_id.product_template_value_ids) == 1)
|
||||
for ptav in single_values:
|
||||
ptav.ptav_product_variant_ids.write({
|
||||
'product_template_attribute_value_ids': [Command.unlink(ptav.id)],
|
||||
})
|
||||
# Try to remove the variants before deleting to potentially remove some
|
||||
# blocking references.
|
||||
self.ptav_product_variant_ids._unlink_or_archive()
|
||||
# Now delete or archive the values.
|
||||
ptav_to_archive = self.env['product.template.attribute.value']
|
||||
for ptav in self:
|
||||
try:
|
||||
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
|
||||
super(ProductTemplateAttributeValue, ptav).unlink()
|
||||
except Exception:
|
||||
# We catch all kind of exceptions to be sure that the operation
|
||||
# doesn't fail.
|
||||
ptav_to_archive += ptav
|
||||
ptav_to_archive.write({'ptav_active': False})
|
||||
return True
|
||||
|
||||
@api.depends('attribute_id')
|
||||
def _compute_display_name(self):
|
||||
"""Override because in general the name of the value is confusing if it
|
||||
is displayed without the name of the corresponding attribute.
|
||||
Eg. on exclusion rules form
|
||||
"""
|
||||
for value in self:
|
||||
value.display_name = f"{value.attribute_id.name}: {value.name}"
|
||||
|
||||
def _only_active(self):
|
||||
return self.filtered(lambda ptav: ptav.ptav_active)
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda ptav: ptav.attribute_id.create_variant != 'no_variant')
|
||||
|
||||
def _ids2str(self):
|
||||
return ','.join([str(i) for i in sorted(self.ids)])
|
||||
|
||||
def _get_combination_name(self):
|
||||
"""Exclude values from single value lines or from no_variant attributes."""
|
||||
ptavs = self._without_no_variant_attributes().with_prefetch(self._prefetch_ids)
|
||||
ptavs = ptavs._filter_single_value_lines().with_prefetch(self._prefetch_ids)
|
||||
return ", ".join([ptav.name for ptav in ptavs])
|
||||
|
||||
def _filter_single_value_lines(self):
|
||||
"""Return `self` with values from single value lines filtered out
|
||||
depending on the active state of all the values in `self`.
|
||||
|
||||
If any value in `self` is archived, archived values are also taken into
|
||||
account when checking for single values.
|
||||
This allows to display the correct name for archived variants.
|
||||
|
||||
If all values in `self` are active, only active values are taken into
|
||||
account when checking for single values.
|
||||
This allows to display the correct name for active combinations.
|
||||
"""
|
||||
only_active = all(ptav.ptav_active for ptav in self)
|
||||
return self.filtered(lambda ptav: not ptav._is_from_single_value_line(only_active))
|
||||
|
||||
def _is_from_single_value_line(self, only_active=True):
|
||||
"""Return whether `self` is from a single value line, counting also
|
||||
archived values if `only_active` is False.
|
||||
"""
|
||||
self.ensure_one()
|
||||
all_values = self.attribute_line_id.product_template_value_ids
|
||||
if only_active:
|
||||
all_values = all_values._only_active()
|
||||
return len(all_values) == 1
|
||||
32
odoo-bringout-oca-ocb-product/product/models/product_uom.py
Normal file
32
odoo-bringout-oca-ocb-product/product/models/product_uom.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
|
||||
from odoo import _, api, fields, models
|
||||
from odoo.exceptions import ValidationError
|
||||
|
||||
|
||||
class ProductUom(models.Model):
|
||||
_name = 'product.uom'
|
||||
_description = 'Link between products and their UoMs'
|
||||
_rec_name = 'barcode'
|
||||
|
||||
uom_id = fields.Many2one('uom.uom', 'Unit', required=True, index=True, ondelete='cascade')
|
||||
product_id = fields.Many2one('product.product', 'Product', required=True, index=True, ondelete='cascade')
|
||||
barcode = fields.Char(index='btree_not_null', required=True, copy=False)
|
||||
company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.company)
|
||||
|
||||
_barcode_uniq = models.Constraint('unique(barcode)', 'A barcode can only be assigned to one packaging.')
|
||||
|
||||
@api.constrains('barcode')
|
||||
def _check_barcode_uniqueness(self):
|
||||
""" With GS1 nomenclature, products and packagings use the same pattern. Therefore, we need
|
||||
to ensure the uniqueness between products' barcodes and packagings' ones"""
|
||||
domain = [('barcode', 'in', [b for b in self.mapped('barcode') if b])]
|
||||
if self.env['product.product'].search_count(domain, limit=1):
|
||||
raise ValidationError(_("A product already uses the barcode"))
|
||||
|
||||
def _compute_display_name(self):
|
||||
if not self.env.context.get('show_variant_name'):
|
||||
return super()._compute_display_name()
|
||||
for record in self:
|
||||
record.display_name = f"{record.barcode} for: {record.product_id.display_name}"
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models, _
|
||||
from odoo import _, api, models
|
||||
|
||||
|
||||
class ResCompany(models.Model):
|
||||
|
|
@ -9,59 +8,62 @@ class ResCompany(models.Model):
|
|||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
companies = super(ResCompany, self).create(vals_list)
|
||||
ProductPricelist = self.env['product.pricelist']
|
||||
for new_company in companies:
|
||||
pricelist = ProductPricelist.search([
|
||||
('currency_id', '=', new_company.currency_id.id),
|
||||
('company_id', '=', False)
|
||||
], limit=1)
|
||||
if not pricelist:
|
||||
params = {'currency': new_company.currency_id.name}
|
||||
pricelist = ProductPricelist.create({
|
||||
'name': _("Default %(currency)s pricelist") % params,
|
||||
'currency_id': new_company.currency_id.id,
|
||||
})
|
||||
self.env['ir.property']._set_default(
|
||||
'property_product_pricelist',
|
||||
'res.partner',
|
||||
pricelist,
|
||||
new_company,
|
||||
)
|
||||
companies = super().create(vals_list)
|
||||
companies._activate_or_create_pricelists()
|
||||
return companies
|
||||
|
||||
def write(self, values):
|
||||
# When we modify the currency of the company, we reflect the change on the list0 pricelist, if
|
||||
# that pricelist is not used by another company. Otherwise, we create a new pricelist for the
|
||||
# given currency.
|
||||
ProductPricelist = self.env['product.pricelist']
|
||||
currency_id = values.get('currency_id')
|
||||
main_pricelist = self.env.ref('product.list0', False)
|
||||
if currency_id and main_pricelist:
|
||||
nb_companies = self.search_count([])
|
||||
for company in self:
|
||||
existing_pricelist = ProductPricelist.search(
|
||||
[('company_id', 'in', (False, company.id)),
|
||||
('currency_id', 'in', (currency_id, company.currency_id.id))])
|
||||
if existing_pricelist and any(currency_id == x.currency_id.id for x in existing_pricelist):
|
||||
continue
|
||||
if currency_id == company.currency_id.id:
|
||||
continue
|
||||
currency_match = main_pricelist.currency_id == company.currency_id
|
||||
company_match = (main_pricelist.company_id == company or
|
||||
(main_pricelist.company_id.id is False and nb_companies == 1))
|
||||
if currency_match and company_match:
|
||||
main_pricelist.write({'currency_id': currency_id})
|
||||
else:
|
||||
params = {'currency': self.env['res.currency'].browse(currency_id).name}
|
||||
pricelist = ProductPricelist.create({
|
||||
'name': _("Default %(currency)s pricelist") % params,
|
||||
'currency_id': currency_id,
|
||||
})
|
||||
self.env['ir.property']._set_default(
|
||||
'property_product_pricelist',
|
||||
'res.partner',
|
||||
pricelist,
|
||||
company,
|
||||
)
|
||||
return super(ResCompany, self).write(values)
|
||||
def _activate_or_create_pricelists(self):
|
||||
""" Manage the default pricelists for needed companies. """
|
||||
if self.env.context.get('disable_company_pricelist_creation'):
|
||||
return
|
||||
|
||||
if self.env.user.has_group('product.group_product_pricelist'):
|
||||
companies = self or self.env['res.company'].search([])
|
||||
ProductPricelist = self.env['product.pricelist'].sudo()
|
||||
# Activate existing default pricelists
|
||||
default_pricelists_sudo = ProductPricelist.with_context(active_test=False).search(
|
||||
[('item_ids', '=', False), ('company_id', 'in', companies.ids)]
|
||||
).filtered(lambda pl: pl.currency_id == pl.company_id.currency_id)
|
||||
default_pricelists_sudo.action_unarchive()
|
||||
companies_without_pricelist = companies.filtered(
|
||||
lambda c: c.id not in default_pricelists_sudo.company_id.ids
|
||||
)
|
||||
# Create missing default pricelists
|
||||
ProductPricelist.create([
|
||||
company._get_default_pricelist_vals() for company in companies_without_pricelist
|
||||
])
|
||||
|
||||
def _get_default_pricelist_vals(self):
|
||||
"""Add values to the default pricelist at company creation or activation of the pricelist
|
||||
|
||||
Note: self.ensure_one()
|
||||
|
||||
:rtype: dict
|
||||
"""
|
||||
self.ensure_one()
|
||||
values = {}
|
||||
values.update({
|
||||
'name': _("Default"),
|
||||
'currency_id': self.currency_id.id,
|
||||
'company_id': self.id,
|
||||
'sequence': 10,
|
||||
})
|
||||
return values
|
||||
|
||||
def write(self, vals):
|
||||
"""Delay the automatic creation of pricelists post-company update.
|
||||
|
||||
This makes sure that the pricelist(s) automatically created are created with the right
|
||||
currency.
|
||||
"""
|
||||
if not vals.get('currency_id'):
|
||||
return super().write(vals)
|
||||
|
||||
enabled_pricelists = self.env.user.has_group('product.group_product_pricelist')
|
||||
res = super(
|
||||
ResCompany, self.with_context(disable_company_pricelist_creation=True)
|
||||
).write(vals)
|
||||
if not enabled_pricelists and self.env.user.has_group('product.group_product_pricelist'):
|
||||
self.browse()._activate_or_create_pricelists()
|
||||
|
||||
return res
|
||||
|
|
|
|||
|
|
@ -1,60 +1,43 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo import _, api, fields, models
|
||||
|
||||
|
||||
class ResConfigSettings(models.TransientModel):
|
||||
_inherit = 'res.config.settings'
|
||||
|
||||
group_discount_per_so_line = fields.Boolean("Discounts", implied_group='product.group_discount_per_so_line')
|
||||
group_uom = fields.Boolean("Units of Measure", implied_group='uom.group_uom')
|
||||
group_uom = fields.Boolean("Units of Measure & Packagings", implied_group='uom.group_uom')
|
||||
group_product_variant = fields.Boolean("Variants", implied_group='product.group_product_variant')
|
||||
module_sale_product_matrix = fields.Boolean("Sales Grid Entry")
|
||||
module_loyalty = fields.Boolean("Promotions, Coupons, Gift Card & Loyalty Program")
|
||||
group_stock_packaging = fields.Boolean('Product Packagings',
|
||||
implied_group='product.group_stock_packaging')
|
||||
group_product_pricelist = fields.Boolean("Pricelists",
|
||||
implied_group='product.group_product_pricelist')
|
||||
group_sale_pricelist = fields.Boolean("Advanced Pricelists",
|
||||
implied_group='product.group_sale_pricelist',
|
||||
help="""Allows to manage different prices based on rules per category of customers.
|
||||
Example: 10% for retailers, promotion of 5 EUR on this product, etc.""")
|
||||
product_pricelist_setting = fields.Selection([
|
||||
('basic', 'Multiple prices per product'),
|
||||
('advanced', 'Advanced price rules (discounts, formulas)')
|
||||
], default='basic', string="Pricelists Method", config_parameter='product.product_pricelist_setting',
|
||||
help="Multiple prices: Pricelists with fixed price rules by product,\nAdvanced rules: enables advanced price rules for pricelists.")
|
||||
product_weight_in_lbs = fields.Selection([
|
||||
('0', 'Kilograms'),
|
||||
('1', 'Pounds'),
|
||||
('0', 'Kilograms (kg)'),
|
||||
('1', 'Pounds (lb)'),
|
||||
], 'Weight unit of measure', config_parameter='product.weight_in_lbs', default='0')
|
||||
product_volume_volume_in_cubic_feet = fields.Selection([
|
||||
('0', 'Cubic Meters'),
|
||||
('1', 'Cubic Feet'),
|
||||
('0', 'Cubic Meters (m³)'),
|
||||
('1', 'Cubic Feet (ft³)'),
|
||||
], 'Volume unit of measure', config_parameter='product.volume_in_cubic_feet', default='0')
|
||||
|
||||
@api.onchange('group_product_variant')
|
||||
def _onchange_group_product_variant(self):
|
||||
"""The product Configurator requires the product variants activated.
|
||||
If the user disables the product variants -> disable the product configurator as well"""
|
||||
if self.module_sale_product_matrix and not self.group_product_variant:
|
||||
self.module_sale_product_matrix = False
|
||||
|
||||
@api.onchange('group_product_pricelist')
|
||||
def _onchange_group_sale_pricelist(self):
|
||||
if not self.group_product_pricelist and self.group_sale_pricelist:
|
||||
self.group_sale_pricelist = False
|
||||
|
||||
@api.onchange('product_pricelist_setting')
|
||||
def _onchange_product_pricelist_setting(self):
|
||||
if self.product_pricelist_setting == 'basic':
|
||||
self.group_sale_pricelist = False
|
||||
else:
|
||||
self.group_sale_pricelist = True
|
||||
if not self.group_product_pricelist:
|
||||
active_pricelist = self.env['product.pricelist'].sudo().search_count(
|
||||
[('active', '=', True)], limit=1
|
||||
)
|
||||
if active_pricelist:
|
||||
return {
|
||||
'warning': {
|
||||
'message': _("You are deactivating the pricelist feature. "
|
||||
"Every active pricelist will be archived.")
|
||||
}}
|
||||
|
||||
def set_values(self):
|
||||
had_group_pl = self.default_get(['group_product_pricelist'])['group_product_pricelist']
|
||||
super().set_values()
|
||||
if not self.group_discount_per_so_line:
|
||||
pl = self.env['product.pricelist'].search([('discount_policy', '=', 'without_discount')])
|
||||
pl.write({'discount_policy': 'with_discount'})
|
||||
|
||||
if self.group_product_pricelist and not had_group_pl:
|
||||
self.env['res.company']._activate_or_create_pricelists()
|
||||
elif not self.group_product_pricelist:
|
||||
self.env['product.pricelist'].sudo().search([]).action_archive()
|
||||
|
|
|
|||
|
|
@ -10,5 +10,16 @@ class ResCurrency(models.Model):
|
|||
def _activate_group_multi_currency(self):
|
||||
# for Sale/ POS - Multi currency flows require pricelists
|
||||
super()._activate_group_multi_currency()
|
||||
group_user = self.env.ref('base.group_user').sudo()
|
||||
group_user._apply_group(self.env.ref('product.group_product_pricelist'))
|
||||
if not self.env.user.has_group('product.group_product_pricelist'):
|
||||
group_user = self.env.ref('base.group_user').sudo()
|
||||
group_user._apply_group(self.env.ref('product.group_product_pricelist'))
|
||||
self.env['res.company']._activate_or_create_pricelists()
|
||||
|
||||
def write(self, vals):
|
||||
""" Archive pricelist when the linked currency is archived. """
|
||||
res = super().write(vals)
|
||||
|
||||
if self and 'active' in vals and not vals['active']:
|
||||
self.env['product.pricelist'].search([('currency_id', 'in', self.ids)]).action_archive()
|
||||
|
||||
return res
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
|
@ -7,43 +6,46 @@ from odoo import api, fields, models
|
|||
class ResPartner(models.Model):
|
||||
_inherit = 'res.partner'
|
||||
|
||||
# NOT A REAL PROPERTY !!!!
|
||||
# when the specific_property_product_pricelist is not defined
|
||||
# the fallback value may be computed with 2 ir.config_parameter
|
||||
# in self.env['product.pricelist']._get_partner_pricelist_multi
|
||||
# 1. res.partner.property_product_pricelist_{company_id} # fallback for current company
|
||||
# 2. res.partner.property_product_pricelist # fallback for all companies
|
||||
property_product_pricelist = fields.Many2one(
|
||||
comodel_name='product.pricelist',
|
||||
string="Pricelist",
|
||||
compute='_compute_product_pricelist',
|
||||
inverse="_inverse_product_pricelist",
|
||||
company_dependent=False,
|
||||
company_dependent=False, # behave like company dependent field but is not company_dependent
|
||||
domain=lambda self: [('company_id', 'in', (self.env.company.id, False))],
|
||||
help="This pricelist will be used, instead of the default one, for sales to the current partner")
|
||||
help="Used for sales to the current partner",
|
||||
)
|
||||
|
||||
@api.depends('country_id')
|
||||
@api.depends_context('company')
|
||||
# the specific pricelist to compute property_product_pricelist
|
||||
# this company dependent field shouldn't have any fallback in ir.default
|
||||
specific_property_product_pricelist = fields.Many2one(
|
||||
comodel_name='product.pricelist',
|
||||
company_dependent=True,
|
||||
)
|
||||
|
||||
@api.depends('country_id', 'specific_property_product_pricelist')
|
||||
@api.depends_context('company', 'country_code')
|
||||
def _compute_product_pricelist(self):
|
||||
res = self.env['product.pricelist']._get_partner_pricelist_multi(self.ids)
|
||||
res = self.env['product.pricelist']._get_partner_pricelist_multi(self._ids)
|
||||
for partner in self:
|
||||
partner.property_product_pricelist = res.get(partner._origin.id)
|
||||
partner.property_product_pricelist = res.get(partner.id)
|
||||
|
||||
def _inverse_product_pricelist(self):
|
||||
defaults = self.env['product.pricelist']._get_country_pricelist_multi(self.country_id.ids)
|
||||
for partner in self:
|
||||
pls = self.env['product.pricelist'].search(
|
||||
[('country_group_ids.country_ids.code', '=', partner.country_id and partner.country_id.code or False)],
|
||||
limit=1
|
||||
)
|
||||
default_for_country = pls
|
||||
actual = self.env['ir.property']._get(
|
||||
'property_product_pricelist',
|
||||
'res.partner',
|
||||
'res.partner,%s' % partner.id)
|
||||
default_for_country = defaults.get(partner.country_id.id)
|
||||
actual = partner.specific_property_product_pricelist
|
||||
# update at each change country, and so erase old pricelist
|
||||
if partner.property_product_pricelist or (actual and default_for_country and default_for_country.id != actual.id):
|
||||
# keep the company of the current user before sudo
|
||||
self.env['ir.property']._set_multi(
|
||||
'property_product_pricelist',
|
||||
partner._name,
|
||||
{partner.id: partner.property_product_pricelist or default_for_country.id},
|
||||
default_value=default_for_country.id
|
||||
)
|
||||
partner.specific_property_product_pricelist = False if partner.property_product_pricelist.id == default_for_country.id else partner.property_product_pricelist.id
|
||||
|
||||
def _commercial_fields(self):
|
||||
return super()._commercial_fields() + ['property_product_pricelist']
|
||||
def _synced_commercial_fields(self):
|
||||
return [
|
||||
*super()._synced_commercial_fields(),
|
||||
'specific_property_product_pricelist',
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,21 +1,30 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models, _
|
||||
from odoo import models, fields, _
|
||||
from odoo.fields import Domain
|
||||
|
||||
|
||||
class UoM(models.Model):
|
||||
class UomUom(models.Model):
|
||||
_inherit = 'uom.uom'
|
||||
|
||||
@api.onchange('rounding')
|
||||
def _onchange_rounding(self):
|
||||
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
|
||||
if self.rounding < 1.0 / 10.0**precision:
|
||||
return {'warning': {
|
||||
'title': _('Warning!'),
|
||||
'message': _(
|
||||
"This rounding precision is higher than the Decimal Accuracy"
|
||||
" (%s digits).\nThis may cause inconsistencies in computations.\n"
|
||||
"Please set a precision between %s and 1."
|
||||
) % (precision, 1.0 / 10.0**precision),
|
||||
}}
|
||||
def _domain_product_uoms(self):
|
||||
domain = []
|
||||
if self.env.context.get("product_id"):
|
||||
domain.append(Domain('product_id', '=', self.env.context['product_id']))
|
||||
if self.env.context.get("product_ids"):
|
||||
domain.append(Domain('product_id', 'in', self.env.context['product_ids']))
|
||||
return Domain.OR(domain) if domain else Domain.TRUE
|
||||
|
||||
product_uom_ids = fields.One2many('product.uom', 'uom_id', string='Barcodes', domain=_domain_product_uoms)
|
||||
|
||||
def action_open_packaging_barcodes(self):
|
||||
self.ensure_one()
|
||||
return {
|
||||
'type': 'ir.actions.act_window',
|
||||
'name': _('Packaging Barcodes'),
|
||||
'res_model': 'product.uom',
|
||||
'view_mode': 'list',
|
||||
'view_id': self.env.ref('product.product_uom_list_view').id,
|
||||
'domain': [('uom_id', '=', self.id)],
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue