| 1 |
|
| 2 |
|
| 3 |
from collections import defaultdict |
| 4 |
|
| 5 |
from odoo import _, api, fields, models |
| 6 |
from odoo.exceptions import ValidationError |
| 7 |
from odoo.tools import float_round |
| 8 |
|
| 9 |
|
| 10 |
class ProductTemplate(models.Model): |
| 11 |
_inherit = 'product.template' |
| 12 |
_check_company_auto = True |
| 13 |
|
| 14 |
service_type = fields.Selection( |
| 15 |
selection=[('manual', "Manually set quantities on order")], |
| 16 |
string="Track Service", |
| 17 |
compute='_compute_service_type', store=True, readonly=False, precompute=True, |
| 18 |
help="Manually set quantities on order: Invoice based on the manually entered quantity, without creating an analytic account.\n" |
| 19 |
"Timesheets on contract: Invoice based on the tracked hours on the related timesheet.\n" |
| 20 |
"Create a task and track hours: Create a task on the sales order validation and track the work hours.") |
| 21 |
sale_line_warn_msg = fields.Text(string="Sales Order Line Warning") |
| 22 |
expense_policy = fields.Selection( |
| 23 |
selection=[ |
| 24 |
('no', "No"), |
| 25 |
('cost', "At cost"), |
| 26 |
('sales_price', "Sales price"), |
| 27 |
], |
| 28 |
string="Re-Invoice Costs", default='no', |
| 29 |
compute='_compute_expense_policy', store=True, readonly=False, |
| 30 |
help="Validated expenses, vendor bills, or stock pickings (set up to track costs) can be invoiced to the customer at either cost or sales price.") |
| 31 |
visible_expense_policy = fields.Boolean( |
| 32 |
string="Re-Invoice Policy visible", compute='_compute_visible_expense_policy') |
| 33 |
sales_count = fields.Float( |
| 34 |
string="Sold", compute='_compute_sales_count', digits='Product Unit') |
| 35 |
invoice_policy = fields.Selection( |
| 36 |
selection=[ |
| 37 |
('order', "Ordered quantities"), |
| 38 |
('delivery', "Delivered quantities"), |
| 39 |
], |
| 40 |
string="Invoicing Policy", |
| 41 |
compute='_compute_invoice_policy', |
| 42 |
precompute=True, |
| 43 |
store=True, |
| 44 |
readonly=False, |
| 45 |
tracking=True, |
| 46 |
help="Ordered Quantity: Invoice quantities ordered by the customer.\n" |
| 47 |
"Delivered Quantity: Invoice quantities delivered to the customer.") |
| 48 |
optional_product_ids = fields.Many2many( |
| 49 |
comodel_name='product.template', |
| 50 |
relation='product_optional_rel', |
| 51 |
column1='src_id', |
| 52 |
column2='dest_id', |
| 53 |
string="Optional Products", |
| 54 |
help="Optional Products are suggested " |
| 55 |
"whenever the customer hits *Add to Cart* (cross-sell strategy, " |
| 56 |
"e.g. for computers: warranty, software, etc.).", |
| 57 |
check_company=True) |
| 58 |
|
| 59 |
@api.depends('invoice_policy', 'sale_ok', 'service_tracking') |
| 60 |
def _compute_product_tooltip(self): |
| 61 |
super()._compute_product_tooltip() |
| 62 |
|
| 63 |
def _prepare_tooltip(self): |
| 64 |
tooltip = super()._prepare_tooltip() |
| 65 |
if not self.sale_ok: |
| 66 |
return tooltip |
| 67 |
|
| 68 |
invoicing_tooltip = self._prepare_invoicing_tooltip() |
| 69 |
|
| 70 |
tooltip = f'{tooltip} {invoicing_tooltip}' if tooltip else invoicing_tooltip |
| 71 |
|
| 72 |
if self.type == 'service': |
| 73 |
additional_tooltip = self._prepare_service_tracking_tooltip() |
| 74 |
tooltip = f'{tooltip} {additional_tooltip}' if additional_tooltip else tooltip |
| 75 |
|
| 76 |
return tooltip |
| 77 |
|
| 78 |
def _prepare_invoicing_tooltip(self): |
| 79 |
if self.invoice_policy == 'delivery' and self.type != 'consu': |
| 80 |
return _("Invoice after delivery, based on quantities delivered, not ordered.") |
| 81 |
elif self.invoice_policy == 'order' and self.type == 'service': |
| 82 |
return _("Invoice ordered quantities as soon as this service is sold.") |
| 83 |
return "" |
| 84 |
|
| 85 |
def _prepare_service_tracking_tooltip(self): |
| 86 |
return "" |
| 87 |
|
| 88 |
@api.depends('sale_ok') |
| 89 |
def _compute_service_tracking(self): |
| 90 |
super()._compute_service_tracking() |
| 91 |
self.filtered(lambda pt: not pt.sale_ok).service_tracking = 'no' |
| 92 |
|
| 93 |
@api.depends('purchase_ok') |
| 94 |
def _compute_visible_expense_policy(self): |
| 95 |
visibility = self.env.user.has_group('analytic.group_analytic_accounting') |
| 96 |
for product_template in self: |
| 97 |
product_template.visible_expense_policy = visibility and product_template.purchase_ok |
| 98 |
|
| 99 |
@api.depends('sale_ok') |
| 100 |
def _compute_expense_policy(self): |
| 101 |
self.filtered(lambda t: not t.sale_ok).expense_policy = 'no' |
| 102 |
|
| 103 |
@api.depends('product_variant_ids.sales_count') |
| 104 |
def _compute_sales_count(self): |
| 105 |
for product in self: |
| 106 |
product.sales_count = product.uom_id.round(sum(p.sales_count for p in product.with_context(active_test=False).product_variant_ids)) |
| 107 |
|
| 108 |
@api.constrains('company_id') |
| 109 |
def _check_sale_product_company(self): |
| 110 |
"""Ensure the product is not being restricted to a single company while |
| 111 |
having been sold in another one in the past, as this could cause issues.""" |
| 112 |
products_by_compagny = defaultdict(lambda: self.env['product.template']) |
| 113 |
for product in self: |
| 114 |
if not product.product_variant_ids or not product.company_id: |
| 115 |
|
| 116 |
|
| 117 |
continue |
| 118 |
products_by_compagny[product.company_id] |= product |
| 119 |
|
| 120 |
for target_company, products in products_by_compagny.items(): |
| 121 |
subquery_products = self.env['product.product'].sudo().with_context(active_test=False)._search([('product_tmpl_id', 'in', products.ids)]) |
| 122 |
so_lines = self.env['sale.order.line'].sudo().search_read( |
| 123 |
[('product_id', 'in', subquery_products), '!', ('company_id', 'child_of', target_company.id)], |
| 124 |
fields=['id', 'product_id']) |
| 125 |
if so_lines: |
| 126 |
used_products = [sol['product_id'][1] for sol in so_lines] |
| 127 |
raise ValidationError(_('The following products cannot be restricted to the company' |
| 128 |
' %(company)s because they have already been used in quotations or ' |
| 129 |
'sales orders in another company:\n%(used_products)s\n' |
| 130 |
'You can archive these products and recreate them ' |
| 131 |
'with your company restriction instead, or leave them as ' |
| 132 |
'shared product.', company=target_company.name, used_products=', '.join(used_products))) |
| 133 |
|
| 134 |
@api.readonly |
| 135 |
def action_view_sales(self): |
| 136 |
action = self.env['ir.actions.actions']._for_xml_id('sale.report_all_channels_sales_action') |
| 137 |
action['domain'] = [('product_tmpl_id', 'in', self.ids)] |
| 138 |
action['context'] = { |
| 139 |
'pivot_measures': ['product_uom_qty'], |
| 140 |
'active_id': self.env.context.get('active_id'), |
| 141 |
'active_model': 'sale.report', |
| 142 |
'search_default_Sales': 1, |
| 143 |
'search_default_filter_order_date': 1, |
| 144 |
'search_default_group_by_date': 1, |
| 145 |
} |
| 146 |
return action |
| 147 |
|
| 148 |
@api.onchange('type') |
| 149 |
def _onchange_type(self): |
| 150 |
res = super()._onchange_type() |
| 151 |
if self._origin and self.sales_count > 0: |
| 152 |
res['warning'] = { |
| 153 |
'title': _("Warning"), |
| 154 |
'message': _("You cannot change the product's type because it is already used in sales orders.") |
| 155 |
} |
| 156 |
return res |
| 157 |
|
| 158 |
@api.depends('type') |
| 159 |
def _compute_service_type(self): |
| 160 |
self.filtered(lambda t: t.type == 'consu' or not t.service_type).service_type = 'manual' |
| 161 |
|
| 162 |
@api.depends('type') |
| 163 |
def _compute_invoice_policy(self): |
| 164 |
self.filtered(lambda t: t.type == 'consu' or not t.invoice_policy).invoice_policy = 'order' |
| 165 |
|
| 166 |
def _get_backend_root_menu_ids(self): |
| 167 |
return super()._get_backend_root_menu_ids() + [self.env.ref('sale.sale_menu_root').id] |
| 168 |
|
| 169 |
@api.model |
| 170 |
def get_import_templates(self): |
| 171 |
res = super(ProductTemplate, self).get_import_templates() |
| 172 |
if self.env.context.get('sale_multi_pricelist_product_template'): |
| 173 |
if self.env.user.has_group('product.group_product_pricelist'): |
| 174 |
return [{ |
| 175 |
'label': _("Import Template for Products"), |
| 176 |
'template': '/product/static/xls/product_template.xls' |
| 177 |
}] |
| 178 |
return res |
| 179 |
|
| 180 |
@api.model |
| 181 |
def _get_incompatible_types(self): |
| 182 |
return [] |
| 183 |
|
| 184 |
@api.constrains(lambda self: self._get_incompatible_types()) |
| 185 |
def _check_incompatible_types(self): |
| 186 |
incompatible_types = self._get_incompatible_types() |
| 187 |
if len(incompatible_types) < 2: |
| 188 |
return |
| 189 |
fields = self.env['ir.model.fields'].sudo().search_read( |
| 190 |
[('model', '=', 'product.template'), ('name', 'in', incompatible_types)], |
| 191 |
['name', 'field_description']) |
| 192 |
field_descriptions = {v['name']: v['field_description'] for v in fields} |
| 193 |
field_list = incompatible_types + ['name'] |
| 194 |
values = self.read(field_list) |
| 195 |
for val in values: |
| 196 |
incompatible_fields = [f for f in incompatible_types if val[f]] |
| 197 |
if len(incompatible_fields) > 1: |
| 198 |
raise ValidationError(_( |
| 199 |
"The product (%(product)s) has incompatible values: %(value_list)s", |
| 200 |
product=val['name'], |
| 201 |
value_list=[field_descriptions[v] for v in incompatible_fields], |
| 202 |
)) |
| 203 |
|
| 204 |
def get_single_product_variant(self): |
| 205 |
""" Method used by the product configurator to check if the product is configurable or not. |
| 206 |
|
| 207 |
We need to open the product configurator if the product: |
| 208 |
- is configurable (see has_configurable_attributes) |
| 209 |
- has optional products """ |
| 210 |
res = super().get_single_product_variant() |
| 211 |
if res.get('product_id', False): |
| 212 |
has_optional_products = False |
| 213 |
for optional_product in self.product_variant_id.optional_product_ids: |
| 214 |
if optional_product.has_dynamic_attributes() or optional_product._get_possible_variants( |
| 215 |
self.product_variant_id.product_template_attribute_value_ids |
| 216 |
): |
| 217 |
has_optional_products = True |
| 218 |
break |
| 219 |
res.update({ |
| 220 |
'has_optional_products': has_optional_products, |
| 221 |
'is_combo': self.type == 'combo', |
| 222 |
}) |
| 223 |
return res |
| 224 |
|
| 225 |
@api.model |
| 226 |
def _get_saleable_tracking_types(self): |
| 227 |
"""Return list of salealbe service_tracking types. |
| 228 |
|
| 229 |
:rtype: list |
| 230 |
""" |
| 231 |
return ['no'] |
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
@api.model |
| 238 |
def _get_configurator_display_price( |
| 239 |
self, product_or_template, quantity, date, currency, pricelist, **kwargs |
| 240 |
): |
| 241 |
""" Return the specified product's display price, to be used by the product and combo |
| 242 |
configurators. |
| 243 |
|
| 244 |
This is a hook meant to customize the display price computation in overriding modules. |
| 245 |
|
| 246 |
:param product.product|product.template product_or_template: The product for which to get |
| 247 |
the price. |
| 248 |
:param int quantity: The quantity of the product. |
| 249 |
:param datetime date: The date to use to compute the price. |
| 250 |
:param res.currency currency: The currency to use to compute the price. |
| 251 |
:param product.pricelist pricelist: The pricelist to use to compute the price. |
| 252 |
:param dict kwargs: Locally unused data passed to `_get_configurator_price`. |
| 253 |
:rtype: tuple(float, int or False) |
| 254 |
:return: The specified product's display price (and the applied pricelist rule) |
| 255 |
""" |
| 256 |
return self._get_configurator_price( |
| 257 |
product_or_template, quantity, date, currency, pricelist, **kwargs |
| 258 |
) |
| 259 |
|
| 260 |
@api.model |
| 261 |
def _get_configurator_price( |
| 262 |
self, product_or_template, quantity, date, currency, pricelist, **kwargs |
| 263 |
): |
| 264 |
""" Return the specified product's price, to be used by the product and combo configurators. |
| 265 |
|
| 266 |
This is a hook meant to customize the price computation in overriding modules. |
| 267 |
|
| 268 |
This hook has been extracted from `_get_configurator_display_price` because the price |
| 269 |
computation can be overridden in 2 ways: |
| 270 |
|
| 271 |
- Either by transforming super's price (e.g. in `website_sale`, we apply taxes to the |
| 272 |
price), |
| 273 |
- Or by computing a different price (e.g. in `sale_subscription`, we ignore super when |
| 274 |
computing subscription prices). |
| 275 |
In some cases, the order of the overrides matters, which is why we need 2 separate methods |
| 276 |
(e.g. in `website_sale_subscription`, we must compute the subscription price before applying |
| 277 |
taxes). |
| 278 |
|
| 279 |
:param product.product|product.template product_or_template: The product for which to get |
| 280 |
the price. |
| 281 |
:param int quantity: The quantity of the product. |
| 282 |
:param datetime date: The date to use to compute the price. |
| 283 |
:param res.currency currency: The currency to use to compute the price. |
| 284 |
:param product.pricelist pricelist: The pricelist to use to compute the price. |
| 285 |
:param dict kwargs: Locally unused data passed to `_get_product_price`. |
| 286 |
:rtype: tuple(float, int or False) |
| 287 |
:return: The specified product's price (and the applied pricelist rule) |
| 288 |
""" |
| 289 |
return pricelist._get_product_price_rule( |
| 290 |
product_or_template, quantity=quantity, currency=currency, date=date, **kwargs |
| 291 |
) |
| 292 |
|
| 293 |
@api.model |
| 294 |
def _get_additional_configurator_data( |
| 295 |
self, product_or_template, date, currency, pricelist, *, uom=None, **kwargs |
| 296 |
): |
| 297 |
"""Return additional data about the specified product. |
| 298 |
|
| 299 |
This is a hook meant to append module-specific data in overriding modules. |
| 300 |
|
| 301 |
:param product.product|product.template product_or_template: The product for which to get |
| 302 |
additional data. |
| 303 |
:param datetime date: The date to use to compute prices. |
| 304 |
:param res.currency currency: The currency to use to compute prices. |
| 305 |
:param product.pricelist pricelist: The pricelist to use to compute prices. |
| 306 |
:param uom.uom uom: The uom to use to compute prices. |
| 307 |
:param dict kwargs: Locally unused data passed to overrides. |
| 308 |
:rtype: dict |
| 309 |
:return: A dict containing additional data about the specified product. |
| 310 |
""" |
| 311 |
return {} |