mirror of
https://github.com/bringout/oca-ocb-sale.git
synced 2026-04-27 00:32:05 +02:00
Initial commit: Sale packages
This commit is contained in:
commit
14e3d26998
6469 changed files with 2479670 additions and 0 deletions
24
odoo-bringout-oca-ocb-product/product/models/__init__.py
Normal file
24
odoo-bringout-oca-ocb-product/product/models/__init__.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
# flake8: noqa: F401
|
||||
|
||||
# don't try to be a good boy and sort imports alphabetically.
|
||||
# `product.template` should be initialised before `product.product`
|
||||
from . import product_template
|
||||
from . import product_product
|
||||
|
||||
from . import decimal_precision
|
||||
from . import product_attribute
|
||||
from . import product_category
|
||||
from . import product_packaging
|
||||
from . import product_pricelist
|
||||
from . import product_pricelist_item
|
||||
from . import product_supplierinfo
|
||||
from . import product_tag
|
||||
from . import res_company
|
||||
from . import res_config_settings
|
||||
from . import res_country_group
|
||||
from . import res_currency
|
||||
from . import res_partner
|
||||
from . import uom_uom
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,40 @@
|
|||
# -*- 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,644 @@
|
|||
# -*- 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
|
||||
|
||||
|
||||
class ProductAttribute(models.Model):
|
||||
_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)')],
|
||||
default='always',
|
||||
string="Variants Creation Mode",
|
||||
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.""",
|
||||
required=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.")
|
||||
|
||||
@api.depends('product_tmpl_ids')
|
||||
def _compute_number_related_products(self):
|
||||
for pa in self:
|
||||
pa.number_related_products = len(pa.product_tmpl_ids)
|
||||
|
||||
@api.depends('attribute_line_ids.active', 'attribute_line_ids.product_tmpl_id')
|
||||
def _compute_products(self):
|
||||
for pa in self:
|
||||
pa.with_context(active_test=False).product_tmpl_ids = pa.attribute_line_ids.product_tmpl_id
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda pa: pa.create_variant != 'no_variant')
|
||||
|
||||
def write(self, vals):
|
||||
"""Override to make sure attribute type can't be changed if it's used on
|
||||
a product template.
|
||||
|
||||
This is important to prevent because changing the type would make
|
||||
existing combinations invalid without recomputing them, and recomputing
|
||||
them might take too long and we don't want to change products without
|
||||
the user knowing about it."""
|
||||
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')))
|
||||
)
|
||||
invalidate = 'sequence' in vals and any(record.sequence != vals['sequence'] for record in self)
|
||||
res = super(ProductAttribute, self).write(vals)
|
||||
if invalidate:
|
||||
# prefetched o2m have to be resequenced
|
||||
# (eg. product.template: attribute_line_ids)
|
||||
self.env.flush_all()
|
||||
self.env.invalidate_all()
|
||||
return res
|
||||
|
||||
@api.ondelete(at_uninstall=False)
|
||||
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
|
||||
))
|
||||
|
||||
def _without_no_variant_attributes(self):
|
||||
return self.filtered(lambda pav: pav.attribute_id.create_variant != 'no_variant')
|
||||
|
||||
|
||||
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):
|
||||
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,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
|
||||
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
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
# -*- 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 UserError, ValidationError
|
||||
|
||||
|
||||
class ProductCategory(models.Model):
|
||||
_name = "product.category"
|
||||
_description = "Product Category"
|
||||
_parent_name = "parent_id"
|
||||
_parent_store = True
|
||||
_rec_name = 'complete_name'
|
||||
_order = 'complete_name'
|
||||
|
||||
name = fields.Char('Name', index='trigram', required=True)
|
||||
complete_name = fields.Char(
|
||||
'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)
|
||||
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)")
|
||||
|
||||
@api.depends('name', 'parent_id.complete_name')
|
||||
def _compute_complete_name(self):
|
||||
for category in self:
|
||||
if category.parent_id:
|
||||
category.complete_name = '%s / %s' % (category.parent_id.complete_name, category.name)
|
||||
else:
|
||||
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)
|
||||
for categ in self:
|
||||
product_count = 0
|
||||
for sub_categ_id in categ.search([('id', 'child_of', categ.ids)]).ids:
|
||||
product_count += group_data.get(sub_categ_id, 0)
|
||||
categ.product_count = product_count
|
||||
|
||||
@api.constrains('parent_id')
|
||||
def _check_category_recursion(self):
|
||||
if not self._check_recursion():
|
||||
raise ValidationError(_('You cannot create recursive categories.'))
|
||||
|
||||
@api.model
|
||||
def name_create(self, name):
|
||||
return self.create({'name': name}).name_get()[0]
|
||||
|
||||
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.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))
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
# -*- 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
|
||||
|
|
@ -0,0 +1,291 @@
|
|||
# -*- 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 UserError
|
||||
|
||||
|
||||
class Pricelist(models.Model):
|
||||
_name = "product.pricelist"
|
||||
_description = "Pricelist"
|
||||
_rec_names_search = ['name', 'currency_id'] # TODO check if should be removed
|
||||
_order = "sequence asc, id desc"
|
||||
|
||||
def _default_currency_id(self):
|
||||
return self.env.company.currency_id.id
|
||||
|
||||
name = fields.Char(string="Pricelist Name", required=True, translate=True)
|
||||
|
||||
active = fields.Boolean(
|
||||
string="Active",
|
||||
default=True,
|
||||
help="If unchecked, it will allow you to hide the pricelist without removing it.")
|
||||
sequence = fields.Integer(default=16)
|
||||
|
||||
currency_id = fields.Many2one(
|
||||
comodel_name='res.currency',
|
||||
default=_default_currency_id,
|
||||
required=True)
|
||||
|
||||
company_id = fields.Many2one(
|
||||
comodel_name='res.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)
|
||||
|
||||
item_ids = fields.One2many(
|
||||
comodel_name='product.pricelist.item',
|
||||
inverse_name='pricelist_id',
|
||||
string="Pricelist Rules",
|
||||
copy=True)
|
||||
|
||||
def name_get(self):
|
||||
return [(pricelist.id, '%s (%s)' % (pricelist.name, pricelist.currency_id.name)) for pricelist in self]
|
||||
|
||||
def _get_products_price(self, products, quantity, uom=None, date=False, **kwargs):
|
||||
"""Compute the pricelist prices for the specified products, qty & uom.
|
||||
|
||||
Note: self.ensure_one()
|
||||
|
||||
:returns: dict{product_id: product price}, considering the current pricelist
|
||||
:rtype: dict
|
||||
"""
|
||||
self.ensure_one()
|
||||
return {
|
||||
product_id: res_tuple[0]
|
||||
for product_id, res_tuple in self._compute_price_rule(
|
||||
products,
|
||||
quantity,
|
||||
uom=uom,
|
||||
date=date,
|
||||
**kwargs
|
||||
).items()
|
||||
}
|
||||
|
||||
def _get_product_price(self, product, quantity, uom=None, date=False, **kwargs):
|
||||
"""Compute the pricelist price for the specified product, qty & uom.
|
||||
|
||||
Note: self.ensure_one()
|
||||
|
||||
:returns: unit price of the product, considering pricelist rules
|
||||
:rtype: float
|
||||
"""
|
||||
self.ensure_one()
|
||||
return self._compute_price_rule(
|
||||
product, quantity, uom=uom, date=date, **kwargs
|
||||
)[product.id][0]
|
||||
|
||||
def _get_product_price_rule(self, product, quantity, uom=None, date=False, **kwargs):
|
||||
"""Compute the pricelist price & rule for the specified product, qty & uom.
|
||||
|
||||
Note: self.ensure_one()
|
||||
|
||||
: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]
|
||||
|
||||
def _get_product_rule(self, product, quantity, uom=None, date=False, **kwargs):
|
||||
"""Compute the pricelist price & rule for the specified product, qty & uom.
|
||||
|
||||
Note: self.ensure_one()
|
||||
|
||||
: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]
|
||||
|
||||
def _compute_price_rule(self, products, qty, uom=None, date=False, **kwargs):
|
||||
""" Low-level method - Mono pricelist, multi products
|
||||
Returns: dict{product_id: (price, suitable_rule) for the given pricelist}
|
||||
|
||||
:param products: recordset of products (product.product/product.template)
|
||||
:param float qty: quantity of products requested (in given uom)
|
||||
: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
|
||||
|
||||
:returns: product_id: (price, pricelist_rule)
|
||||
:rtype: dict
|
||||
"""
|
||||
self.ensure_one()
|
||||
|
||||
if not products:
|
||||
return {}
|
||||
|
||||
if not date:
|
||||
# Used to fetch pricelist rules and currency rates
|
||||
date = fields.Datetime.now()
|
||||
|
||||
# Fetch all rules potentially matching specified products/templates/categories and date
|
||||
rules = self._get_applicable_rules(products, date, **kwargs)
|
||||
|
||||
results = {}
|
||||
for product in products:
|
||||
suitable_rule = self.env['product.pricelist.item']
|
||||
|
||||
product_uom = product.uom_id
|
||||
target_uom = uom or product_uom # If no uom is specified, fall back on the product uom
|
||||
|
||||
# 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)
|
||||
else:
|
||||
qty_in_product_uom = qty
|
||||
|
||||
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)
|
||||
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._get_applicable_rules_domain(products=products, date=date, **kwargs)
|
||||
)
|
||||
|
||||
def _get_applicable_rules_domain(self, products, date, **kwargs):
|
||||
if products._name == 'product.template':
|
||||
templates_domain = ('product_tmpl_id', 'in', products.ids)
|
||||
products_domain = ('product_id.product_tmpl_id', 'in', products.ids)
|
||||
else:
|
||||
templates_domain = ('product_tmpl_id', 'in', products.product_tmpl_id.ids)
|
||||
products_domain = ('product_id', 'in', products.ids)
|
||||
|
||||
return [
|
||||
('pricelist_id', '=', self.id),
|
||||
'|', ('categ_id', '=', False), ('categ_id', 'parent_of', products.categ_id.ids),
|
||||
'|', ('product_tmpl_id', '=', False), templates_domain,
|
||||
'|', ('product_id', '=', False), products_domain,
|
||||
'|', ('date_start', '=', False), ('date_start', '<=', date),
|
||||
'|', ('date_end', '=', False), ('date_end', '>=', date),
|
||||
]
|
||||
|
||||
# Multi pricelists price|rule computation
|
||||
def _price_get(self, product, qty, **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()}
|
||||
|
||||
def _compute_price_rule_multi(self, products, qty, 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:
|
||||
pricelists = self.search([])
|
||||
else:
|
||||
pricelists = self
|
||||
results = {}
|
||||
for pricelist in pricelists:
|
||||
subres = pricelist._compute_price_rule(products, qty, uom=uom, date=date, **kwargs)
|
||||
for product_id, price in subres.items():
|
||||
results.setdefault(product_id, {})
|
||||
results[product_id][pricelist.id] = price
|
||||
return results
|
||||
|
||||
# res.partner.property_product_pricelist field computation
|
||||
@api.model
|
||||
def _get_partner_pricelist_multi(self, partner_ids):
|
||||
""" Retrieve the applicable pricelist for given partners in a given company.
|
||||
|
||||
It will return the first found pricelist in this order:
|
||||
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
|
||||
|
||||
:param int company_id: if passed, used for looking up properties,
|
||||
instead of current user's company
|
||||
:return: a dict {partner_id: pricelist}
|
||||
"""
|
||||
# `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)
|
||||
|
||||
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
|
||||
|
||||
return result
|
||||
|
||||
def _get_partner_pricelist_multi_search_domain_hook(self, company_id):
|
||||
return [
|
||||
('active', '=', True),
|
||||
('company_id', 'in', [company_id, False]),
|
||||
]
|
||||
|
||||
def _get_partner_pricelist_multi_filter_hook(self):
|
||||
return self.filtered('active')
|
||||
|
||||
@api.model
|
||||
def get_import_templates(self):
|
||||
return [{
|
||||
'label': _('Import Template for Pricelists'),
|
||||
'template': '/product/static/xls/product_pricelist.xls'
|
||||
}]
|
||||
|
||||
@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([
|
||||
('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'))
|
||||
))
|
||||
|
|
@ -0,0 +1,438 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.tools import format_datetime, formatLang
|
||||
|
||||
|
||||
class PricelistItem(models.Model):
|
||||
_name = "product.pricelist.item"
|
||||
_description = "Pricelist Rule"
|
||||
_order = "applied_on, min_quantity desc, categ_id desc, id desc"
|
||||
_check_company_auto = True
|
||||
|
||||
def _default_pricelist_id(self):
|
||||
return self.env['product.pricelist'].search([
|
||||
'|', ('company_id', '=', False),
|
||||
('company_id', '=', self.env.company.id)], limit=1)
|
||||
|
||||
pricelist_id = fields.Many2one(
|
||||
comodel_name='product.pricelist',
|
||||
string="Pricelist",
|
||||
index=True, ondelete='cascade',
|
||||
required=True,
|
||||
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)
|
||||
|
||||
date_start = fields.Datetime(
|
||||
string="Start Date",
|
||||
help="Starting datetime for the pricelist item validation\n"
|
||||
"The displayed value depends on the timezone set in your preferences.")
|
||||
date_end = fields.Datetime(
|
||||
string="End Date",
|
||||
help="Ending datetime for the pricelist item validation\n"
|
||||
"The displayed value depends on the timezone set in your preferences.")
|
||||
|
||||
min_quantity = fields.Float(
|
||||
string="Min. Quantity",
|
||||
default=0,
|
||||
digits='Product Unit of Measure',
|
||||
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.")
|
||||
|
||||
applied_on = fields.Selection(
|
||||
selection=[
|
||||
('3_global', "All Products"),
|
||||
('2_product_category', "Product Category"),
|
||||
('1_product', "Product"),
|
||||
('0_product_variant', "Product Variant"),
|
||||
],
|
||||
string="Apply On",
|
||||
default='3_global',
|
||||
required=True,
|
||||
help="Pricelist Item applicable on selected option")
|
||||
|
||||
categ_id = fields.Many2one(
|
||||
comodel_name='product.category',
|
||||
string="Product 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,
|
||||
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,
|
||||
help="Specify a product if this rule only applies to one product. Keep empty otherwise.")
|
||||
|
||||
base = fields.Selection(
|
||||
selection=[
|
||||
('list_price', 'Sales Price'),
|
||||
('standard_price', 'Cost'),
|
||||
('pricelist', 'Other Pricelist'),
|
||||
],
|
||||
string="Based on",
|
||||
default='list_price',
|
||||
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.")
|
||||
base_pricelist_id = fields.Many2one('product.pricelist', 'Other Pricelist', check_company=True)
|
||||
|
||||
compute_price = fields.Selection(
|
||||
selection=[
|
||||
('fixed', "Fixed Price"),
|
||||
('percentage', "Discount"),
|
||||
('formula', "Formula"),
|
||||
],
|
||||
index=True, default='fixed', required=True)
|
||||
|
||||
fixed_price = fields.Float(string="Fixed Price", digits='Product Price')
|
||||
percent_price = fields.Float(
|
||||
string="Percentage Price",
|
||||
help="You can apply a mark-up by setting a negative discount.")
|
||||
|
||||
price_discount = fields.Float(
|
||||
string="Price Discount",
|
||||
default=0,
|
||||
digits=(16, 2),
|
||||
help="You can apply a mark-up by setting a negative discount.")
|
||||
price_round = fields.Float(
|
||||
string="Price Rounding",
|
||||
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")
|
||||
price_surcharge = fields.Float(
|
||||
string="Price Surcharge",
|
||||
digits='Product Price',
|
||||
help="Specify the fixed amount to add or subtract (if negative) to the amount calculated with the discount.")
|
||||
|
||||
price_min_margin = fields.Float(
|
||||
string="Min. Price Margin",
|
||||
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',
|
||||
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',
|
||||
help="Explicit rule name for this pricelist line.")
|
||||
price = fields.Char(
|
||||
string="Price",
|
||||
compute='_compute_name_and_price',
|
||||
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):
|
||||
for item in self:
|
||||
if item.categ_id and item.applied_on == '2_product_category':
|
||||
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)
|
||||
elif item.product_id and item.applied_on == '0_product_variant':
|
||||
item.name = _("Variant: %s") % (item.product_id.display_name)
|
||||
else:
|
||||
item.name = _("All Products")
|
||||
|
||||
if item.compute_price == 'fixed':
|
||||
item.price = formatLang(
|
||||
item.env, item.fixed_price, monetary=True, dp="Product Price", currency_obj=item.currency_id)
|
||||
elif item.compute_price == 'percentage':
|
||||
item.price = _("%s %% discount", item.percent_price)
|
||||
else:
|
||||
item.price = _("%(percentage)s %% discount and %(price)s surcharge", percentage=item.price_discount, price=item.price_surcharge)
|
||||
|
||||
@api.depends_context('lang')
|
||||
@api.depends('compute_price', 'price_discount', 'price_surcharge', 'base', 'price_round')
|
||||
def _compute_rule_tip(self):
|
||||
base_selection_vals = {elem[0]: elem[1] for elem in self._fields['base']._description_selection(self.env)}
|
||||
self.rule_tip = False
|
||||
for item in self:
|
||||
if item.compute_price != 'formula':
|
||||
continue
|
||||
base_amount = 100
|
||||
discount_factor = (100 - item.price_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)
|
||||
item.rule_tip = _(
|
||||
"%(base)s with a %(discount)s %% discount 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,
|
||||
surcharge=surcharge,
|
||||
amount=tools.format_amount(item.env, 100, item.currency_id),
|
||||
discount_charge=discount_factor,
|
||||
price_surcharge=surcharge,
|
||||
total_amount=tools.format_amount(
|
||||
item.env, discounted_price + item.price_surcharge, item.currency_id),
|
||||
)
|
||||
|
||||
#=== CONSTRAINT METHODS ===#
|
||||
|
||||
@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'))
|
||||
|
||||
@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)))
|
||||
return True
|
||||
|
||||
@api.constrains('price_min_margin', 'price_max_margin')
|
||||
def _check_margin(self):
|
||||
if any(item.price_min_margin > item.price_max_margin for item in self):
|
||||
raise ValidationError(_('The minimum margin should be lower than the maximum margin.'))
|
||||
|
||||
@api.constrains('product_id', 'product_tmpl_id', 'categ_id')
|
||||
def _check_product_consistency(self):
|
||||
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:
|
||||
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:
|
||||
raise ValidationError(_("Please specify the product variant for which this rule should be applied"))
|
||||
|
||||
#=== ONCHANGE METHODS ===#
|
||||
|
||||
@api.onchange('compute_price')
|
||||
def _onchange_compute_price(self):
|
||||
if self.compute_price != 'fixed':
|
||||
self.fixed_price = 0.0
|
||||
if self.compute_price != 'percentage':
|
||||
self.percent_price = 0.0
|
||||
if self.compute_price != 'formula':
|
||||
self.update({
|
||||
'base': 'list_price',
|
||||
'price_discount': 0.0,
|
||||
'price_surcharge': 0.0,
|
||||
'price_round': 0.0,
|
||||
'price_min_margin': 0.0,
|
||||
'price_max_margin': 0.0,
|
||||
})
|
||||
|
||||
@api.onchange('product_id')
|
||||
def _onchange_product_id(self):
|
||||
has_product_id = self.filtered('product_id')
|
||||
for item in has_product_id:
|
||||
item.product_tmpl_id = item.product_id.product_tmpl_id
|
||||
if self.env.context.get('default_applied_on', False) == '1_product':
|
||||
# If a product variant is specified, apply on variants instead
|
||||
# Reset if product variant is removed
|
||||
has_product_id.update({'applied_on': '0_product_variant'})
|
||||
(self - has_product_id).update({'applied_on': '1_product'})
|
||||
|
||||
@api.onchange('product_tmpl_id')
|
||||
def _onchange_product_tmpl_id(self):
|
||||
has_tmpl_id = self.filtered('product_tmpl_id')
|
||||
for item in has_tmpl_id:
|
||||
if item.product_id and item.product_id.product_tmpl_id != item.product_tmpl_id:
|
||||
item.product_id = None
|
||||
|
||||
@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')
|
||||
template_rules = (self-variants_rules).filtered('product_tmpl_id')
|
||||
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'})
|
||||
|
||||
@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."))
|
||||
|
||||
#=== CRUD METHODS ===#
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for values in vals_list:
|
||||
if not values.get('applied_on'):
|
||||
values['applied_on'] = (
|
||||
'0_product_variant' if values.get('product_id') else
|
||||
'1_product' if values.get('product_tmpl_id') else
|
||||
'2_product_category' if values.get('categ_id') else
|
||||
'3_global'
|
||||
)
|
||||
|
||||
# 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))
|
||||
elif applied_on == '2_product_category':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None))
|
||||
elif applied_on == '1_product':
|
||||
values.update(dict(product_id=None, categ_id=None))
|
||||
elif applied_on == '0_product_variant':
|
||||
values.update(dict(categ_id=None))
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, values):
|
||||
if values.get('applied_on', False):
|
||||
# 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))
|
||||
elif applied_on == '2_product_category':
|
||||
values.update(dict(product_id=None, product_tmpl_id=None))
|
||||
elif applied_on == '1_product':
|
||||
values.update(dict(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."))
|
||||
|
||||
#=== BUSINESS METHODS ===#
|
||||
|
||||
def _is_applicable_for(self, product, qty_in_product_uom):
|
||||
"""Check whether the current rule is valid for the given product & qty.
|
||||
|
||||
Note: self.ensure_one()
|
||||
|
||||
:param product: product record (product.product/product.template)
|
||||
:param float qty_in_product_uom: quantity, expressed in product UoM
|
||||
:returns: Whether rules is valid or not
|
||||
:rtype: bool
|
||||
"""
|
||||
self.ensure_one()
|
||||
product.ensure_one()
|
||||
res = True
|
||||
|
||||
is_product_template = product._name == 'product.template'
|
||||
if self.min_quantity and qty_in_product_uom < self.min_quantity:
|
||||
res = False
|
||||
|
||||
elif self.applied_on == "2_product_category":
|
||||
if (
|
||||
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
|
||||
|
||||
return res
|
||||
|
||||
def _compute_price(self, product, quantity, uom, date, currency=None):
|
||||
"""Compute the unit price of a product in the context of a pricelist application.
|
||||
|
||||
: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 currency: pricelist currency (for the specific case where self is empty)
|
||||
|
||||
:returns: price according to pricelist rule, expressed in pricelist currency
|
||||
:rtype: float
|
||||
"""
|
||||
product.ensure_one()
|
||||
uom.ensure_one()
|
||||
|
||||
currency = currency or self.currency_id
|
||||
currency.ensure_one()
|
||||
|
||||
# Pricelist specific values are specified according to product UoM
|
||||
# and must be multiplied according to the factor between uoms
|
||||
product_uom = product.uom_id
|
||||
if product_uom != uom:
|
||||
convert = lambda p: product_uom._compute_price(p, uom)
|
||||
else:
|
||||
convert = lambda p: p
|
||||
|
||||
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)
|
||||
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)
|
||||
# complete formula
|
||||
price_limit = base_price
|
||||
price = (base_price - (base_price * (self.price_discount / 100))) or 0.0
|
||||
if self.price_round:
|
||||
price = tools.float_round(price, precision_rounding=self.price_round)
|
||||
|
||||
if self.price_surcharge:
|
||||
price += convert(self.price_surcharge)
|
||||
|
||||
if self.price_min_margin:
|
||||
price = max(price, price_limit + convert(self.price_min_margin))
|
||||
|
||||
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)
|
||||
|
||||
return price
|
||||
|
||||
def _compute_base_price(self, product, quantity, uom, date, target_currency):
|
||||
""" Compute the base price for a given rule
|
||||
|
||||
: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
|
||||
|
||||
:returns: base price, expressed in provided pricelist currency
|
||||
:rtype: float
|
||||
"""
|
||||
target_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, 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
|
||||
716
odoo-bringout-oca-ocb-product/product/models/product_product.py
Normal file
716
odoo-bringout-oca-ocb-product/product/models/product_product.py
Normal file
|
|
@ -0,0 +1,716 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
import re
|
||||
from collections import defaultdict
|
||||
|
||||
from odoo import api, fields, models, tools, _
|
||||
from odoo.exceptions import ValidationError
|
||||
from odoo.osv import expression
|
||||
from odoo.tools import float_compare
|
||||
|
||||
|
||||
class ProductProduct(models.Model):
|
||||
_name = "product.product"
|
||||
_description = "Product Variant"
|
||||
_inherits = {'product.template': 'product_tmpl_id'}
|
||||
_inherit = ['mail.thread', 'mail.activity.mixin']
|
||||
_order = 'priority desc, default_code, name, id'
|
||||
|
||||
# price_extra: catalog extra value only, sum of variant extra attributes
|
||||
price_extra = fields.Float(
|
||||
'Variant Price Extra', compute='_compute_product_price_extra',
|
||||
digits='Product Price',
|
||||
help="This is the sum of the extra price of all attributes")
|
||||
# lst_price: catalog value + extra, context dependent (uom)
|
||||
lst_price = fields.Float(
|
||||
'Sales Price', compute='_compute_product_lst_price',
|
||||
digits='Product Price', inverse='_set_product_lst_price',
|
||||
help="The sale price is managed from the product template. Click on the 'Configure Variants' button to set the extra attribute prices.")
|
||||
|
||||
default_code = fields.Char('Internal Reference', index=True)
|
||||
code = fields.Char('Reference', compute='_compute_product_code')
|
||||
partner_ref = fields.Char('Customer Ref', compute='_compute_partner_ref')
|
||||
|
||||
active = fields.Boolean(
|
||||
'Active', default=True,
|
||||
help="If unchecked, it will allow you to hide the product without removing it.")
|
||||
product_tmpl_id = fields.Many2one(
|
||||
'product.template', 'Product Template',
|
||||
auto_join=True, index=True, ondelete="cascade", required=True)
|
||||
barcode = fields.Char(
|
||||
'Barcode', copy=False, index='btree_not_null',
|
||||
help="International Article Number used for product identification.")
|
||||
product_template_attribute_value_ids = fields.Many2many('product.template.attribute.value', relation='product_variant_combination', string="Attribute Values", ondelete='restrict')
|
||||
product_template_variant_value_ids = fields.Many2many('product.template.attribute.value', relation='product_variant_combination',
|
||||
domain=[('attribute_line_id.value_count', '>', 1)], string="Variant Values", ondelete='restrict')
|
||||
combination_indices = fields.Char(compute='_compute_combination_indices', store=True, index=True)
|
||||
is_product_variant = fields.Boolean(compute='_compute_is_product_variant')
|
||||
|
||||
standard_price = fields.Float(
|
||||
'Cost', company_dependent=True,
|
||||
digits='Product Price',
|
||||
groups="base.group_user",
|
||||
help="""In Standard Price & AVCO: value of the product (automatically computed in AVCO).
|
||||
In FIFO: value of the next unit that will leave the stock (automatically computed).
|
||||
Used to value the product when the purchase cost is not known (e.g. inventory adjustment).
|
||||
Used to compute margins on sale orders.""")
|
||||
volume = fields.Float('Volume', digits='Volume')
|
||||
weight = fields.Float('Weight', digits='Stock Weight')
|
||||
|
||||
pricelist_item_count = fields.Integer("Number of price rules", compute="_compute_variant_item_count")
|
||||
|
||||
packaging_ids = fields.One2many(
|
||||
'product.packaging', 'product_id', 'Product Packages',
|
||||
help="Gives the different ways to package the same product.")
|
||||
|
||||
additional_product_tag_ids = fields.Many2many('product.tag', 'product_tag_product_product_rel')
|
||||
all_product_tag_ids = fields.Many2many('product.tag', compute='_compute_all_product_tag_ids', search='_search_all_product_tag_ids')
|
||||
|
||||
# all image fields are base64 encoded and PIL-supported
|
||||
|
||||
# all image_variant fields are technical and should not be displayed to the user
|
||||
image_variant_1920 = fields.Image("Variant Image", max_width=1920, max_height=1920)
|
||||
|
||||
# resized fields stored (as attachment) for performance
|
||||
image_variant_1024 = fields.Image("Variant Image 1024", related="image_variant_1920", max_width=1024, max_height=1024, store=True)
|
||||
image_variant_512 = fields.Image("Variant Image 512", related="image_variant_1920", max_width=512, max_height=512, store=True)
|
||||
image_variant_256 = fields.Image("Variant Image 256", related="image_variant_1920", max_width=256, max_height=256, store=True)
|
||||
image_variant_128 = fields.Image("Variant Image 128", related="image_variant_1920", max_width=128, max_height=128, store=True)
|
||||
can_image_variant_1024_be_zoomed = fields.Boolean("Can Variant Image 1024 be zoomed", compute='_compute_can_image_variant_1024_be_zoomed', store=True)
|
||||
|
||||
# Computed fields that are used to create a fallback to the template if
|
||||
# necessary, it's recommended to display those fields to the user.
|
||||
image_1920 = fields.Image("Image", compute='_compute_image_1920', inverse='_set_image_1920')
|
||||
image_1024 = fields.Image("Image 1024", compute='_compute_image_1024')
|
||||
image_512 = fields.Image("Image 512", compute='_compute_image_512')
|
||||
image_256 = fields.Image("Image 256", compute='_compute_image_256')
|
||||
image_128 = fields.Image("Image 128", compute='_compute_image_128')
|
||||
can_image_1024_be_zoomed = fields.Boolean("Can Image 1024 be zoomed", compute='_compute_can_image_1024_be_zoomed')
|
||||
|
||||
@api.depends('image_variant_1920', 'image_variant_1024')
|
||||
def _compute_can_image_variant_1024_be_zoomed(self):
|
||||
for record in self:
|
||||
record.can_image_variant_1024_be_zoomed = record.image_variant_1920 and tools.is_image_size_above(record.image_variant_1920, record.image_variant_1024)
|
||||
|
||||
def _set_template_field(self, template_field, variant_field):
|
||||
for record in self:
|
||||
if (
|
||||
# We are trying to remove a field from the variant even though it is already
|
||||
# not set on the variant, remove it from the template instead.
|
||||
(not record[template_field] and not record[variant_field])
|
||||
# We are trying to add a field to the variant, but the template field is
|
||||
# not set, write on the template instead.
|
||||
or (record[template_field] and not record.product_tmpl_id[template_field])
|
||||
# There is only one variant, always write on the template.
|
||||
or self.search_count([
|
||||
('product_tmpl_id', '=', record.product_tmpl_id.id),
|
||||
('active', '=', True),
|
||||
]) <= 1
|
||||
):
|
||||
record[variant_field] = False
|
||||
record.product_tmpl_id[template_field] = record[template_field]
|
||||
else:
|
||||
record[variant_field] = record[template_field]
|
||||
|
||||
@api.depends("create_date", "write_date", "product_tmpl_id.create_date", "product_tmpl_id.write_date")
|
||||
def _compute_concurrency_field(self):
|
||||
# Intentionally not calling super() to involve all fields explicitly
|
||||
for record in self:
|
||||
record[self.CONCURRENCY_CHECK_FIELD] = max(filter(None, (
|
||||
record.product_tmpl_id.write_date or record.product_tmpl_id.create_date,
|
||||
record.write_date or record.create_date or fields.Datetime.now(),
|
||||
)))
|
||||
|
||||
def _compute_image_1920(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_1920 = record.image_variant_1920 or record.product_tmpl_id.image_1920
|
||||
|
||||
def _set_image_1920(self):
|
||||
return self._set_template_field('image_1920', 'image_variant_1920')
|
||||
|
||||
def _compute_image_1024(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_1024 = record.image_variant_1024 or record.product_tmpl_id.image_1024
|
||||
|
||||
def _compute_image_512(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_512 = record.image_variant_512 or record.product_tmpl_id.image_512
|
||||
|
||||
def _compute_image_256(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_256 = record.image_variant_256 or record.product_tmpl_id.image_256
|
||||
|
||||
def _compute_image_128(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.image_128 = record.image_variant_128 or record.product_tmpl_id.image_128
|
||||
|
||||
def _compute_can_image_1024_be_zoomed(self):
|
||||
"""Get the image from the template if no image is set on the variant."""
|
||||
for record in self:
|
||||
record.can_image_1024_be_zoomed = record.can_image_variant_1024_be_zoomed if record.image_variant_1920 else record.product_tmpl_id.can_image_1024_be_zoomed
|
||||
|
||||
def _get_placeholder_filename(self, field):
|
||||
image_fields = ['image_%s' % size for size in [1920, 1024, 512, 256, 128]]
|
||||
if field in image_fields:
|
||||
return 'product/static/img/placeholder.png'
|
||||
return super()._get_placeholder_filename(field)
|
||||
|
||||
def init(self):
|
||||
"""Ensure there is at most one active variant for each combination.
|
||||
|
||||
There could be no variant for a combination if using dynamic attributes.
|
||||
"""
|
||||
self.env.cr.execute("CREATE UNIQUE INDEX IF NOT EXISTS product_product_combination_unique ON %s (product_tmpl_id, combination_indices) WHERE active is true"
|
||||
% self._table)
|
||||
|
||||
@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"""
|
||||
all_barcode = [b for b in self.mapped('barcode') if b]
|
||||
domain = [('barcode', 'in', all_barcode)]
|
||||
matched_products = self.sudo().search(domain, order='id')
|
||||
if len(matched_products) > len(all_barcode): # It means that you find more than `self` -> there are duplicates
|
||||
products_by_barcode = defaultdict(list)
|
||||
for product in matched_products:
|
||||
products_by_barcode[product.barcode].append(product)
|
||||
|
||||
duplicates_as_str = "\n".join(
|
||||
_("- Barcode \"%s\" already assigned to product(s): %s", barcode, ", ".join(p.display_name for p in products))
|
||||
for barcode, products in products_by_barcode.items() if len(products) > 1
|
||||
)
|
||||
raise ValidationError(_("Barcode(s) already assigned:\n\n%s", duplicates_as_str))
|
||||
|
||||
if self.env['product.packaging'].search(domain, order="id", limit=1):
|
||||
raise ValidationError(_("A packaging already uses the barcode"))
|
||||
|
||||
def _get_invoice_policy(self):
|
||||
return False
|
||||
|
||||
@api.depends('product_template_attribute_value_ids')
|
||||
def _compute_combination_indices(self):
|
||||
for product in self:
|
||||
product.combination_indices = product.product_template_attribute_value_ids._ids2str()
|
||||
|
||||
def _compute_is_product_variant(self):
|
||||
self.is_product_variant = True
|
||||
|
||||
@api.onchange('lst_price')
|
||||
def _set_product_lst_price(self):
|
||||
for product in self:
|
||||
if self._context.get('uom'):
|
||||
value = self.env['uom.uom'].browse(self._context['uom'])._compute_price(product.lst_price, product.uom_id)
|
||||
else:
|
||||
value = product.lst_price
|
||||
value -= product.price_extra
|
||||
product.write({'list_price': value})
|
||||
|
||||
@api.depends("product_template_attribute_value_ids.price_extra")
|
||||
def _compute_product_price_extra(self):
|
||||
for product in self:
|
||||
product.price_extra = sum(product.product_template_attribute_value_ids.mapped('price_extra'))
|
||||
|
||||
@api.depends('list_price', 'price_extra')
|
||||
@api.depends_context('uom')
|
||||
def _compute_product_lst_price(self):
|
||||
to_uom = None
|
||||
if 'uom' in self._context:
|
||||
to_uom = self.env['uom.uom'].browse(self._context['uom'])
|
||||
|
||||
for product in self:
|
||||
if to_uom:
|
||||
list_price = product.uom_id._compute_price(product.list_price, to_uom)
|
||||
else:
|
||||
list_price = product.list_price
|
||||
product.lst_price = list_price + product.price_extra
|
||||
|
||||
@api.depends_context('partner_id')
|
||||
def _compute_product_code(self):
|
||||
read_access = self.env['ir.model.access'].check('product.supplierinfo', 'read', False)
|
||||
for product in self:
|
||||
product.code = product.default_code
|
||||
if read_access:
|
||||
for supplier_info in product.seller_ids:
|
||||
if supplier_info.partner_id.id == product._context.get('partner_id'):
|
||||
if supplier_info.product_id and supplier_info.product_id != product:
|
||||
# Supplier info specific for another variant.
|
||||
continue
|
||||
product.code = supplier_info.product_code or product.default_code
|
||||
if product == supplier_info.product_id:
|
||||
# Supplier info specific for this variant.
|
||||
break
|
||||
|
||||
@api.depends_context('partner_id')
|
||||
def _compute_partner_ref(self):
|
||||
for product in self:
|
||||
for supplier_info in product.seller_ids:
|
||||
if supplier_info.partner_id.id == product._context.get('partner_id'):
|
||||
product_name = supplier_info.product_name or product.default_code or product.name
|
||||
product.partner_ref = '%s%s' % (product.code and '[%s] ' % product.code or '', product_name)
|
||||
break
|
||||
else:
|
||||
product.partner_ref = product.display_name
|
||||
|
||||
def _compute_variant_item_count(self):
|
||||
for product in self:
|
||||
domain = ['|',
|
||||
'&', ('product_tmpl_id', '=', product.product_tmpl_id.id), ('applied_on', '=', '1_product'),
|
||||
'&', ('product_id', '=', product.id), ('applied_on', '=', '0_product_variant')]
|
||||
product.pricelist_item_count = self.env['product.pricelist.item'].search_count(domain)
|
||||
|
||||
@api.depends('product_tag_ids', 'additional_product_tag_ids')
|
||||
def _compute_all_product_tag_ids(self):
|
||||
for product in self:
|
||||
product.all_product_tag_ids = product.product_tag_ids | product.additional_product_tag_ids
|
||||
|
||||
def _search_all_product_tag_ids(self, operator, operand):
|
||||
if operator in expression.NEGATIVE_TERM_OPERATORS:
|
||||
return [('product_tag_ids', operator, operand), ('additional_product_tag_ids', operator, operand)]
|
||||
return ['|', ('product_tag_ids', operator, operand), ('additional_product_tag_ids', operator, operand)]
|
||||
|
||||
@api.onchange('uom_id')
|
||||
def _onchange_uom_id(self):
|
||||
if self.uom_id:
|
||||
self.uom_po_id = self.uom_id.id
|
||||
|
||||
@api.onchange('uom_po_id')
|
||||
def _onchange_uom(self):
|
||||
if self.uom_id and self.uom_po_id and self.uom_id.category_id != self.uom_po_id.category_id:
|
||||
self.uom_po_id = self.uom_id
|
||||
|
||||
@api.onchange('default_code')
|
||||
def _onchange_default_code(self):
|
||||
if not self.default_code:
|
||||
return
|
||||
|
||||
domain = [('default_code', '=', self.default_code)]
|
||||
if self.id.origin:
|
||||
domain.append(('id', '!=', self.id.origin))
|
||||
|
||||
if self.env['product.product'].search(domain, limit=1):
|
||||
return {'warning': {
|
||||
'title': _("Note:"),
|
||||
'message': _("The Internal Reference '%s' already exists.", self.default_code),
|
||||
}}
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for vals in vals_list:
|
||||
self.product_tmpl_id._sanitize_vals(vals)
|
||||
products = super(ProductProduct, self.with_context(create_product_product=True)).create(vals_list)
|
||||
# `_get_variant_id_for_combination` depends on existing variants
|
||||
self.clear_caches()
|
||||
return products
|
||||
|
||||
def write(self, values):
|
||||
self.product_tmpl_id._sanitize_vals(values)
|
||||
res = super(ProductProduct, self).write(values)
|
||||
if 'product_template_attribute_value_ids' in values:
|
||||
# `_get_variant_id_for_combination` depends on `product_template_attribute_value_ids`
|
||||
self.clear_caches()
|
||||
elif 'active' in values:
|
||||
# `_get_first_possible_variant_id` depends on variants active state
|
||||
self.clear_caches()
|
||||
return res
|
||||
|
||||
def unlink(self):
|
||||
unlink_products = self.env['product.product']
|
||||
unlink_templates = self.env['product.template']
|
||||
self.packaging_ids.unlink()
|
||||
for product in self:
|
||||
# If there is an image set on the variant and no image set on the
|
||||
# template, move the image to the template.
|
||||
if product.image_variant_1920 and not product.product_tmpl_id.image_1920:
|
||||
product.product_tmpl_id.image_1920 = product.image_variant_1920
|
||||
# Check if product still exists, in case it has been unlinked by unlinking its template
|
||||
if not product.exists():
|
||||
continue
|
||||
# Check if the product is last product of this template...
|
||||
other_products = self.search([('product_tmpl_id', '=', product.product_tmpl_id.id), ('id', '!=', product.id)])
|
||||
# ... and do not delete product template if it's configured to be created "on demand"
|
||||
if not other_products and not product.product_tmpl_id.has_dynamic_attributes():
|
||||
unlink_templates |= product.product_tmpl_id
|
||||
unlink_products |= product
|
||||
res = super(ProductProduct, unlink_products).unlink()
|
||||
# delete templates after calling super, as deleting template could lead to deleting
|
||||
# products due to ondelete='cascade'
|
||||
unlink_templates.unlink()
|
||||
# `_get_variant_id_for_combination` depends on existing variants
|
||||
self.clear_caches()
|
||||
return res
|
||||
|
||||
def _filter_to_unlink(self, check_access=True):
|
||||
return self
|
||||
|
||||
def _unlink_or_archive(self, check_access=True):
|
||||
"""Unlink or archive products.
|
||||
Try in batch as much as possible because it is much faster.
|
||||
Use dichotomy when an exception occurs.
|
||||
"""
|
||||
|
||||
# Avoid access errors in case the products is shared amongst companies
|
||||
# but the underlying objects are not. If unlink fails because of an
|
||||
# AccessError (e.g. while recomputing fields), the 'write' call will
|
||||
# fail as well for the same reason since the field has been set to
|
||||
# recompute.
|
||||
if check_access:
|
||||
self.check_access_rights('unlink')
|
||||
self.check_access_rule('unlink')
|
||||
self.check_access_rights('write')
|
||||
self.check_access_rule('write')
|
||||
self = self.sudo()
|
||||
to_unlink = self._filter_to_unlink()
|
||||
to_archive = self - to_unlink
|
||||
to_archive.write({'active': False})
|
||||
self = to_unlink
|
||||
|
||||
try:
|
||||
with self.env.cr.savepoint(), tools.mute_logger('odoo.sql_db'):
|
||||
self.unlink()
|
||||
except Exception:
|
||||
# We catch all kind of exceptions to be sure that the operation
|
||||
# doesn't fail.
|
||||
if len(self) > 1:
|
||||
self[:len(self) // 2]._unlink_or_archive(check_access=False)
|
||||
self[len(self) // 2:]._unlink_or_archive(check_access=False)
|
||||
else:
|
||||
if self.active:
|
||||
# Note: this can still fail if something is preventing
|
||||
# from archiving.
|
||||
# This is the case from existing stock reordering rules.
|
||||
self.write({'active': False})
|
||||
|
||||
@api.returns('self', lambda value: value.id)
|
||||
def copy(self, default=None):
|
||||
"""Variants are generated depending on the configuration of attributes
|
||||
and values on the template, so copying them does not make sense.
|
||||
|
||||
For convenience the template is copied instead and its first variant is
|
||||
returned.
|
||||
"""
|
||||
# copy variant is disabled in https://github.com/odoo/odoo/pull/38303
|
||||
# this returns the first possible combination of variant to make it
|
||||
# works for now, need to be fixed to return product_variant_id if it's
|
||||
# possible in the future
|
||||
template = self.product_tmpl_id.copy(default=default)
|
||||
return template.product_variant_id or template._create_first_product_variant()
|
||||
|
||||
@api.model
|
||||
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
|
||||
# TDE FIXME: strange
|
||||
if self._context.get('search_default_categ_id'):
|
||||
args = args.copy()
|
||||
args.append((('categ_id', 'child_of', self._context['search_default_categ_id'])))
|
||||
return super(ProductProduct, self)._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid)
|
||||
|
||||
@api.depends_context('display_default_code', 'seller_id')
|
||||
def _compute_display_name(self):
|
||||
# `display_name` is calling `name_get()`` which is overidden on product
|
||||
# to depend on `display_default_code` and `seller_id`
|
||||
return super()._compute_display_name()
|
||||
|
||||
def name_get(self):
|
||||
# TDE: this could be cleaned a bit I think
|
||||
|
||||
def _name_get(d):
|
||||
name = d.get('name', '')
|
||||
code = self._context.get('display_default_code', True) and d.get('default_code', False) or False
|
||||
if code:
|
||||
name = '[%s] %s' % (code,name)
|
||||
return (d['id'], name)
|
||||
|
||||
partner_id = self._context.get('partner_id')
|
||||
if partner_id:
|
||||
partner_ids = [partner_id, self.env['res.partner'].browse(partner_id).commercial_partner_id.id]
|
||||
else:
|
||||
partner_ids = []
|
||||
company_id = self.env.context.get('company_id')
|
||||
|
||||
# all user don't have access to seller and partner
|
||||
# check access and use superuser
|
||||
self.check_access_rights("read")
|
||||
self.check_access_rule("read")
|
||||
|
||||
result = []
|
||||
|
||||
# Prefetch the fields used by the `name_get`, so `browse` doesn't fetch other fields
|
||||
# Use `load=False` to not call `name_get` for the `product_tmpl_id`
|
||||
# Use `prefetch_fields=False` to ensure that product.template fields are not prefetched
|
||||
self.sudo().with_context(prefetch_fields=False).read(['name', 'default_code', 'product_tmpl_id'], load=False)
|
||||
|
||||
product_template_ids = self.sudo().mapped('product_tmpl_id').ids
|
||||
|
||||
if partner_ids:
|
||||
supplier_info = self.env['product.supplierinfo'].sudo().search([
|
||||
('product_tmpl_id', 'in', product_template_ids),
|
||||
('partner_id', 'in', partner_ids),
|
||||
])
|
||||
# Prefetch the fields used by the `name_get`, so `browse` doesn't fetch other fields
|
||||
# Use `load=False` to not call `name_get` for the `product_tmpl_id` and `product_id`
|
||||
supplier_info.sudo().read(['product_tmpl_id', 'product_id', 'product_name', 'product_code'], load=False)
|
||||
supplier_info_by_template = {}
|
||||
for r in supplier_info:
|
||||
supplier_info_by_template.setdefault(r.product_tmpl_id, []).append(r)
|
||||
for product in self.sudo():
|
||||
variant = product.product_template_attribute_value_ids._get_combination_name()
|
||||
|
||||
name = variant and "%s (%s)" % (product.name, variant) or product.name
|
||||
sellers = self.env['product.supplierinfo'].sudo().browse(self.env.context.get('seller_id')) or []
|
||||
if not sellers and partner_ids:
|
||||
product_supplier_info = supplier_info_by_template.get(product.product_tmpl_id, [])
|
||||
sellers = [x for x in product_supplier_info if x.product_id and x.product_id == product]
|
||||
if not sellers:
|
||||
sellers = [x for x in product_supplier_info if not x.product_id]
|
||||
# Filter out sellers based on the company. This is done afterwards for a better
|
||||
# code readability. At this point, only a few sellers should remain, so it should
|
||||
# not be a performance issue.
|
||||
if company_id:
|
||||
sellers = [x for x in sellers if x.company_id.id in [company_id, False]]
|
||||
if sellers:
|
||||
for s in sellers:
|
||||
seller_variant = s.product_name and (
|
||||
variant and "%s (%s)" % (s.product_name, variant) or s.product_name
|
||||
) or False
|
||||
mydict = {
|
||||
'id': product.id,
|
||||
'name': seller_variant or name,
|
||||
'default_code': s.product_code or product.default_code,
|
||||
}
|
||||
temp = _name_get(mydict)
|
||||
if temp not in result:
|
||||
result.append(temp)
|
||||
else:
|
||||
mydict = {
|
||||
'id': product.id,
|
||||
'name': name,
|
||||
'default_code': product.default_code,
|
||||
}
|
||||
result.append(_name_get(mydict))
|
||||
return result
|
||||
|
||||
@api.model
|
||||
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
|
||||
if not args:
|
||||
args = []
|
||||
if name:
|
||||
positive_operators = ['=', 'ilike', '=ilike', 'like', '=like']
|
||||
product_ids = []
|
||||
if operator in positive_operators:
|
||||
product_ids = list(self._search([('default_code', '=', name)] + args, limit=limit, access_rights_uid=name_get_uid))
|
||||
if not product_ids:
|
||||
product_ids = list(self._search([('barcode', '=', name)] + args, limit=limit, access_rights_uid=name_get_uid))
|
||||
if not product_ids and operator not in expression.NEGATIVE_TERM_OPERATORS:
|
||||
# Do not merge the 2 next lines into one single search, SQL search performance would be abysmal
|
||||
# on a database with thousands of matching products, due to the huge merge+unique needed for the
|
||||
# OR operator (and given the fact that the 'name' lookup results come from the ir.translation table
|
||||
# Performing a quick memory merge of ids in Python will give much better performance
|
||||
products_query = self._search(args + [('default_code', operator, name)], limit=limit)
|
||||
product_ids = list(products_query)
|
||||
if not limit or len(product_ids) < limit:
|
||||
# we may underrun the limit because of dupes in the results, that's fine
|
||||
limit2 = (limit - len(product_ids)) if limit else False
|
||||
product2_ids = self._search(args + [('name', operator, name), ('id', 'not in', products_query)], limit=limit2, access_rights_uid=name_get_uid)
|
||||
product_ids.extend(product2_ids)
|
||||
elif not product_ids and operator in expression.NEGATIVE_TERM_OPERATORS:
|
||||
domain = expression.OR([
|
||||
['&', ('default_code', operator, name), ('name', operator, name)],
|
||||
['&', ('default_code', '=', False), ('name', operator, name)],
|
||||
])
|
||||
domain = expression.AND([args, domain])
|
||||
product_ids = list(self._search(domain, limit=limit, access_rights_uid=name_get_uid))
|
||||
if not product_ids and operator in positive_operators:
|
||||
ptrn = re.compile(r'(\[(.*?)\])')
|
||||
res = ptrn.search(name)
|
||||
if res:
|
||||
product_ids = list(self._search([('default_code', '=', res.group(2))] + args, limit=limit, access_rights_uid=name_get_uid))
|
||||
# still no results, partner in context: search on supplier info as last hope to find something
|
||||
if not product_ids and self._context.get('partner_id'):
|
||||
suppliers_ids = self.env['product.supplierinfo']._search([
|
||||
('partner_id', '=', self._context.get('partner_id')),
|
||||
'|',
|
||||
('product_code', operator, name),
|
||||
('product_name', operator, name)], access_rights_uid=name_get_uid)
|
||||
if suppliers_ids:
|
||||
product_ids = self._search([('product_tmpl_id.seller_ids', 'in', suppliers_ids)], limit=limit, access_rights_uid=name_get_uid)
|
||||
else:
|
||||
product_ids = self._search(args, limit=limit, access_rights_uid=name_get_uid)
|
||||
return product_ids
|
||||
|
||||
@api.model
|
||||
def view_header_get(self, view_id, view_type):
|
||||
if self._context.get('categ_id'):
|
||||
return _(
|
||||
'Products: %(category)s',
|
||||
category=self.env['product.category'].browse(self.env.context['categ_id']).name,
|
||||
)
|
||||
return super().view_header_get(view_id, view_type)
|
||||
|
||||
def action_open_label_layout(self):
|
||||
action = self.env['ir.actions.act_window']._for_xml_id('product.action_open_label_layout')
|
||||
action['context'] = {'default_product_ids': self.ids}
|
||||
return action
|
||||
|
||||
def open_pricelist_rules(self):
|
||||
self.ensure_one()
|
||||
domain = ['|',
|
||||
'&', ('product_tmpl_id', '=', self.product_tmpl_id.id), ('applied_on', '=', '1_product'),
|
||||
'&', ('product_id', '=', self.id), ('applied_on', '=', '0_product_variant')]
|
||||
return {
|
||||
'name': _('Price Rules'),
|
||||
'view_mode': 'tree,form',
|
||||
'views': [(self.env.ref('product.product_pricelist_item_tree_view_from_product').id, 'tree')],
|
||||
'res_model': 'product.pricelist.item',
|
||||
'type': 'ir.actions.act_window',
|
||||
'target': 'current',
|
||||
'domain': domain,
|
||||
'context': {
|
||||
'default_product_id': self.id,
|
||||
'default_applied_on': '0_product_variant',
|
||||
}
|
||||
}
|
||||
|
||||
def open_product_template(self):
|
||||
""" Utility method used to add an "Open Template" button in product views """
|
||||
self.ensure_one()
|
||||
return {'type': 'ir.actions.act_window',
|
||||
'res_model': 'product.template',
|
||||
'view_mode': 'form',
|
||||
'res_id': self.product_tmpl_id.id,
|
||||
'target': 'new'}
|
||||
|
||||
def _prepare_sellers(self, params=False):
|
||||
return self.seller_ids.filtered(lambda s: s.partner_id.active).sorted(lambda s: (s.sequence, -s.min_qty, s.price, s.id))
|
||||
|
||||
def _get_filtered_sellers(self, partner_id=False, quantity=0.0, date=None, uom_id=False, params=False):
|
||||
self.ensure_one()
|
||||
if date is None:
|
||||
date = fields.Date.context_today(self)
|
||||
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
|
||||
|
||||
sellers_filtered = self._prepare_sellers(params)
|
||||
sellers_filtered = sellers_filtered.filtered(lambda s: not s.company_id or s.company_id.id == self.env.company.id)
|
||||
sellers = self.env['product.supplierinfo']
|
||||
for seller in sellers_filtered:
|
||||
# Set quantity in UoM of seller
|
||||
quantity_uom_seller = quantity
|
||||
if quantity_uom_seller and uom_id and uom_id != seller.product_uom:
|
||||
quantity_uom_seller = uom_id._compute_quantity(quantity_uom_seller, seller.product_uom)
|
||||
|
||||
if seller.date_start and seller.date_start > date:
|
||||
continue
|
||||
if seller.date_end and seller.date_end < date:
|
||||
continue
|
||||
if partner_id and seller.partner_id not in [partner_id, partner_id.parent_id]:
|
||||
continue
|
||||
if quantity is not None and float_compare(quantity_uom_seller, seller.min_qty, precision_digits=precision) == -1:
|
||||
continue
|
||||
if seller.product_id and seller.product_id != self:
|
||||
continue
|
||||
sellers |= seller
|
||||
return sellers
|
||||
|
||||
def _select_seller(self, partner_id=False, quantity=0.0, date=None, uom_id=False, params=False):
|
||||
sellers = self._get_filtered_sellers(partner_id=partner_id, quantity=quantity, date=date, uom_id=uom_id, params=params)
|
||||
res = self.env['product.supplierinfo']
|
||||
for seller in sellers:
|
||||
if not res or res.partner_id == seller.partner_id:
|
||||
res |= seller
|
||||
return res and res.sorted('price')[:1]
|
||||
|
||||
def price_compute(self, price_type, uom=None, currency=None, company=None, date=False):
|
||||
company = company or self.env.company
|
||||
date = date or fields.Date.context_today(self)
|
||||
|
||||
self = self.with_company(company)
|
||||
if price_type == 'standard_price':
|
||||
# standard_price field can only be seen by users in base.group_user
|
||||
# Thus, in order to compute the sale price from the cost for users not in this group
|
||||
# We fetch the standard price as the superuser
|
||||
self = self.sudo()
|
||||
|
||||
prices = dict.fromkeys(self.ids, 0.0)
|
||||
for product in self:
|
||||
price = product[price_type] or 0.0
|
||||
price_currency = product.currency_id
|
||||
if price_type == 'standard_price':
|
||||
price_currency = product.cost_currency_id
|
||||
|
||||
if price_type == 'list_price':
|
||||
price += product.price_extra
|
||||
# we need to add the price from the attributes that do not generate variants
|
||||
# (see field product.attribute create_variant)
|
||||
if self._context.get('no_variant_attributes_price_extra'):
|
||||
# we have a list of price_extra that comes from the attribute values, we need to sum all that
|
||||
price += sum(self._context.get('no_variant_attributes_price_extra'))
|
||||
|
||||
if uom:
|
||||
price = product.uom_id._compute_price(price, uom)
|
||||
|
||||
# Convert from current user company currency to asked one
|
||||
# This is right cause a field cannot be in more than one currency
|
||||
if currency:
|
||||
price = price_currency._convert(price, currency, company, date)
|
||||
|
||||
prices[product.id] = price
|
||||
|
||||
return prices
|
||||
|
||||
@api.model
|
||||
def get_empty_list_help(self, help):
|
||||
self = self.with_context(
|
||||
empty_list_help_document_name=_("product"),
|
||||
)
|
||||
return super(ProductProduct, self).get_empty_list_help(help)
|
||||
|
||||
def get_product_multiline_description_sale(self):
|
||||
""" Compute a multiline description of this product, in the context of sales
|
||||
(do not use for purchases or other display reasons that don't intend to use "description_sale").
|
||||
It will often be used as the default description of a sale order line referencing this product.
|
||||
"""
|
||||
name = self.display_name
|
||||
if self.description_sale:
|
||||
name += '\n' + self.description_sale
|
||||
|
||||
return name
|
||||
|
||||
def _is_variant_possible(self, parent_combination=None):
|
||||
"""Return whether the variant is possible based on its own combination,
|
||||
and optionally a parent combination.
|
||||
|
||||
See `_is_combination_possible` for more information.
|
||||
|
||||
:param parent_combination: combination from which `self` is an
|
||||
optional or accessory product.
|
||||
:type parent_combination: recordset `product.template.attribute.value`
|
||||
|
||||
:return: ẁhether the variant is possible based on its own combination
|
||||
:rtype: bool
|
||||
"""
|
||||
self.ensure_one()
|
||||
return self.product_tmpl_id._is_combination_possible(self.product_template_attribute_value_ids, parent_combination=parent_combination, ignore_no_variant=True)
|
||||
|
||||
def toggle_active(self):
|
||||
""" Archiving related product.template if there is not any more active product.product
|
||||
(and vice versa, unarchiving the related product template if there is now an active product.product) """
|
||||
result = super().toggle_active()
|
||||
# We deactivate product templates which are active with no active variants.
|
||||
tmpl_to_deactivate = self.filtered(lambda product: (product.product_tmpl_id.active
|
||||
and not product.product_tmpl_id.product_variant_ids)).mapped('product_tmpl_id')
|
||||
# We activate product templates which are inactive with active variants.
|
||||
tmpl_to_activate = self.filtered(lambda product: (not product.product_tmpl_id.active
|
||||
and product.product_tmpl_id.product_variant_ids)).mapped('product_tmpl_id')
|
||||
(tmpl_to_deactivate + tmpl_to_activate).toggle_active()
|
||||
return result
|
||||
|
||||
def get_contextual_price(self):
|
||||
return self._get_contextual_price()
|
||||
|
||||
def _get_contextual_price(self):
|
||||
self.ensure_one()
|
||||
return self.product_tmpl_id._get_contextual_price(self)
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models, _
|
||||
|
||||
|
||||
class SupplierInfo(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,
|
||||
check_company=True)
|
||||
product_name = fields.Char(
|
||||
'Vendor Product Name',
|
||||
help="This vendor's product name will be used when printing a request for quotation. Keep empty to use the internal one.")
|
||||
product_code = fields.Char(
|
||||
'Vendor Product Code',
|
||||
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')
|
||||
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.")
|
||||
price = fields.Float(
|
||||
'Price', default=0.0, digits='Product Price',
|
||||
required=True, help="The price to purchase a product")
|
||||
company_id = fields.Many2one(
|
||||
'res.company', 'Company',
|
||||
default=lambda self: self.env.company.id, index=1)
|
||||
currency_id = fields.Many2one(
|
||||
'res.currency', 'Currency',
|
||||
default=lambda self: self.env.company.currency_id.id,
|
||||
required=True)
|
||||
date_start = fields.Date('Start Date', help="Start date for this vendor price")
|
||||
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,
|
||||
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_variant_count = fields.Integer('Variant Count', related='product_tmpl_id.product_variant_count')
|
||||
delay = fields.Integer(
|
||||
'Delivery 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.")
|
||||
|
||||
@api.onchange('product_tmpl_id')
|
||||
def _onchange_product_tmpl_id(self):
|
||||
"""Clear product variant if it no longer matches the product template."""
|
||||
if self.product_id and self.product_id not in self.product_tmpl_id.product_variant_ids:
|
||||
self.product_id = False
|
||||
|
||||
@api.model
|
||||
def get_import_templates(self):
|
||||
return [{
|
||||
'label': _('Import Template for Vendor Pricelists'),
|
||||
'template': '/product/static/xls/product_supplierinfo.xls'
|
||||
}]
|
||||
|
||||
def _sanitize_vals(self, vals):
|
||||
"""Sanitize vals to sync product variant & template on read/write."""
|
||||
# add product's product_tmpl_id if none present in vals
|
||||
if vals.get('product_id') and not vals.get('product_tmpl_id'):
|
||||
product = self.env['product.product'].browse(vals['product_id'])
|
||||
vals['product_tmpl_id'] = product.product_tmpl_id.id
|
||||
|
||||
@api.model_create_multi
|
||||
def create(self, vals_list):
|
||||
for vals in vals_list:
|
||||
self._sanitize_vals(vals)
|
||||
return super().create(vals_list)
|
||||
|
||||
def write(self, vals):
|
||||
self._sanitize_vals(vals)
|
||||
return super().write(vals)
|
||||
37
odoo-bringout-oca-ocb-product/product/models/product_tag.py
Normal file
37
odoo-bringout-oca-ocb-product/product/models/product_tag.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
# -*- 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
|
||||
|
||||
class ProductTag(models.Model):
|
||||
_name = 'product.tag'
|
||||
_description = 'Product Tag'
|
||||
|
||||
def _get_default_color(self):
|
||||
return randint(1, 11)
|
||||
|
||||
name = fields.Char('Tag Name', required=True, translate=True)
|
||||
color = fields.Integer('Color', default=_get_default_color)
|
||||
|
||||
product_template_ids = fields.Many2many('product.template', 'product_tag_product_template_rel')
|
||||
product_product_ids = fields.Many2many('product.product', 'product_tag_product_product_rel')
|
||||
product_ids = fields.Many2many(
|
||||
'product.product', string='All Product Variants using this Tag',
|
||||
compute='_compute_product_ids', search='_search_product_ids'
|
||||
)
|
||||
|
||||
_sql_constraints = [
|
||||
('name_uniq', '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 _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)]
|
||||
return ['|', ('product_template_ids.product_variant_ids', operator, operand), ('product_product_ids', operator, operand)]
|
||||
1353
odoo-bringout-oca-ocb-product/product/models/product_template.py
Normal file
1353
odoo-bringout-oca-ocb-product/product/models/product_template.py
Normal file
File diff suppressed because it is too large
Load diff
67
odoo-bringout-oca-ocb-product/product/models/res_company.py
Normal file
67
odoo-bringout-oca-ocb-product/product/models/res_company.py
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models, _
|
||||
|
||||
|
||||
class ResCompany(models.Model):
|
||||
_inherit = "res.company"
|
||||
|
||||
@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,
|
||||
)
|
||||
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)
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
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_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'),
|
||||
], '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'),
|
||||
], '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
|
||||
|
||||
def set_values(self):
|
||||
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'})
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import fields, models
|
||||
|
||||
|
||||
class ResCountryGroup(models.Model):
|
||||
_inherit = 'res.country.group'
|
||||
|
||||
pricelist_ids = fields.Many2many(
|
||||
comodel_name='product.pricelist',
|
||||
relation='res_country_group_pricelist_rel',
|
||||
column1='res_country_group_id',
|
||||
column2='pricelist_id',
|
||||
string="Pricelists")
|
||||
14
odoo-bringout-oca-ocb-product/product/models/res_currency.py
Normal file
14
odoo-bringout-oca-ocb-product/product/models/res_currency.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import models
|
||||
|
||||
|
||||
class ResCurrency(models.Model):
|
||||
_inherit = 'res.currency'
|
||||
|
||||
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'))
|
||||
49
odoo-bringout-oca-ocb-product/product/models/res_partner.py
Normal file
49
odoo-bringout-oca-ocb-product/product/models/res_partner.py
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class ResPartner(models.Model):
|
||||
_inherit = 'res.partner'
|
||||
|
||||
# NOT A REAL PROPERTY !!!!
|
||||
property_product_pricelist = fields.Many2one(
|
||||
comodel_name='product.pricelist',
|
||||
string="Pricelist",
|
||||
compute='_compute_product_pricelist',
|
||||
inverse="_inverse_product_pricelist",
|
||||
company_dependent=False,
|
||||
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")
|
||||
|
||||
@api.depends('country_id')
|
||||
@api.depends_context('company')
|
||||
def _compute_product_pricelist(self):
|
||||
res = self.env['product.pricelist']._get_partner_pricelist_multi(self.ids)
|
||||
for partner in self:
|
||||
partner.property_product_pricelist = res.get(partner._origin.id)
|
||||
|
||||
def _inverse_product_pricelist(self):
|
||||
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)
|
||||
# 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
|
||||
)
|
||||
|
||||
def _commercial_fields(self):
|
||||
return super()._commercial_fields() + ['property_product_pricelist']
|
||||
21
odoo-bringout-oca-ocb-product/product/models/uom_uom.py
Normal file
21
odoo-bringout-oca-ocb-product/product/models/uom_uom.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import api, models, _
|
||||
|
||||
|
||||
class UoM(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),
|
||||
}}
|
||||
Loading…
Add table
Add a link
Reference in a new issue