Debian Codegraph @

addons/website_sale/models/product_template.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import logging
4 from collections import defaultdict
5
6 from werkzeug import urls
7
8 from odoo import _, api, fields, models
9 from odoo.fields import Domain
10 from odoo.http import request
11 from odoo.tools import float_is_zero, is_html_empty
12 from odoo.tools.sql import SQL, column_exists, create_column
13 from odoo.tools.translate import html_translate
14
15 from odoo.addons.website.models import ir_http
16 from odoo.addons.website.tools import text_from_html
17 from odoo.addons.website_sale.const import SHOP_PATH
18
19 # A delimiter that users aren't likely to search for in product codes.
20 RARE_DELIMITER = '\u241E'
21
22 _logger = logging.getLogger(__name__)
23
24
25 def get_translated_field_gist_index(registry, column_name):
26 if not registry.has_trigram:
27 return ""
28 if registry.has_unaccent:
29 return f"USING GIST(unaccent((JSONB_PATH_QUERY_ARRAY({column_name}, '$.*'::jsonpath))::text) gist_trgm_ops)"
30 return f"USING GIST((JSONB_PATH_QUERY_ARRAY({column_name}, '$.*'::jsonpath)::text) gist_trgm_ops)"
31
32
33 class ProductTemplate(models.Model):
34 _name = 'product.template'
35 _inherit = [
36 'rating.mixin',
37 'product.template',
38 'website.seo.metadata',
39 'website.published.multi.mixin',
40 'website.searchable.mixin',
41 ]
42 _mail_post_access = 'read'
43 _check_company_auto = True
44
45 #=== DEFAULT METHODS ===#
46
47 @api.model
48 def _default_website_sequence(self):
49 """ We want new product to be the last (highest seq).
50 Every product should ideally have an unique sequence.
51 Default sequence (10000) should only be used for DB first product.
52 As we don't resequence the whole tree (as `sequence` does), this field
53 might have negative value.
54 """
55 self.env.cr.execute('SELECT MAX(website_sequence) FROM %s' % self._table)
56 max_sequence = self.env.cr.fetchone()[0]
57 if max_sequence is None:
58 return 10000
59 return max_sequence + 5
60
61 #=== FIELDS ===#
62
63 website_description = fields.Html(
64 string="Description for the website",
65 translate=html_translate,
66 sanitize_overridable=True,
67 sanitize_attributes=False,
68 sanitize_form=False,
69 index='trigram',
70 )
71 description_ecommerce = fields.Html(
72 string="eCommerce Description",
73 translate=html_translate,
74 sanitize_overridable=True,
75 sanitize_attributes=False,
76 sanitize_form=False,
77 )
78
79 alternative_product_ids = fields.Many2many(
80 string="Alternative Products",
81 comodel_name='product.template',
82 relation='product_alternative_rel',
83 column1='src_id', column2='dest_id',
84 check_company=True,
85 help="Suggest alternatives to your customer (upsell strategy)."
86 " Those products show up on the product page.",
87 )
88 accessory_product_ids = fields.Many2many(
89 string="Accessory Products",
90 comodel_name='product.product',
91 relation='product_accessory_rel',
92 column1='src_id', column2='dest_id',
93 check_company=True,
94 help="Accessories show up when the customer reviews the cart before payment"
95 " (cross-sell strategy).",
96 )
97
98 website_size_x = fields.Integer(string="Size X", default=1)
99 website_size_y = fields.Integer(string="Size Y", default=1)
100 website_ribbon_id = fields.Many2one(string="Ribbon", comodel_name='product.ribbon')
101 website_sequence = fields.Integer(
102 string="Website Sequence",
103 help="Determine the display order in the Website E-commerce",
104 default=_default_website_sequence,
105 copy=False,
106 index=True,
107 )
108 public_categ_ids = fields.Many2many(
109 string="Website Product Category",
110 help="The product will be available in each mentioned eCommerce category. Go to Shop > Edit"
111 " Click on the page and enable 'Categories' to view all eCommerce categories.",
112 comodel_name='product.public.category',
113 relation='product_public_category_product_template_rel',
114 )
115
116 publish_date = fields.Datetime(
117 string="Publish Date",
118 compute='_compute_publish_date',
119 store=True,
120 required=True,
121 default=fields.Datetime.now,
122 )
123
124 product_template_image_ids = fields.One2many(
125 string="Extra Product Media",
126 comodel_name='product.image',
127 inverse_name='product_tmpl_id',
128 copy=True,
129 )
130
131 base_unit_count = fields.Float(
132 string="Base Unit Count",
133 help="Display base unit price on your eCommerce pages. Set to 0 to hide it for this product.",
134 compute='_compute_base_unit_count',
135 inverse='_set_base_unit_count',
136 store=True,
137 required=True,
138 default=0,
139 )
140 base_unit_id = fields.Many2one(
141 string="Custom Unit of Measure",
142 help="Define a custom unit to display in the price per unit of measure field.",
143 comodel_name='website.base.unit',
144 compute='_compute_base_unit_id',
145 inverse='_set_base_unit_id',
146 store=True,
147 )
148 base_unit_price = fields.Monetary(string="Price Per Unit", compute="_compute_base_unit_price")
149 base_unit_name = fields.Char(
150 compute='_compute_base_unit_name',
151 help="Displays the custom unit for the products if defined or the selected unit of measure"
152 " otherwise.",
153 )
154
155 compare_list_price = fields.Monetary(
156 string="Compare to Price",
157 help="Add a strikethrough price to your /shop and product pages for comparison purposes."
158 "It will not be displayed if pricelists apply.",
159 )
160 variants_default_code = fields.Char(
161 compute='_compute_variants_default_code',
162 store=True,
163 index='trigram',
164 help="Technical field to enhance performance when looking up default code of product"
165 "variants (LIKE/ILIKE)",
166 )
167 description = fields.Html(index='trigram')
168 description_sale = fields.Text(index='trigram')
169
170 # === INDEXES === #
171
172 # We need gist indexes for similarity check in ecommerce fuzzy search.
173 _name_gist_idx = models.Index(lambda registry: get_translated_field_gist_index(registry, "name"))
174 _description_gist_idx = models.Index(lambda registry: get_translated_field_gist_index(registry, "description"))
175 _description_sale_gist_idx = models.Index(lambda registry: get_translated_field_gist_index(registry, "description_sale"))
176 _default_code_gist_idx = models.Index(
177 lambda registry: 'USING GIST(unaccent(default_code) gist_trgm_ops)'
178 if registry.has_trigram and registry.has_unaccent
179 else ('USING GIST(default_code gist_trgm_ops)' if registry.has_trigram else '')
180 )
181
182 def _auto_init(self):
183 """Override _auto_init to prevent MemoryError on ecommerce installation in dbs with lots of products"""
184 if not column_exists(self.env.cr, 'product_template', 'variants_default_code'):
185 create_column(self.env.cr, 'product_template', 'variants_default_code', 'varchar')
186 self.env.cr.execute(SQL(
187 """
188 UPDATE product_template
189 SET variants_default_code = variants.default_codes
190 FROM (
191 SELECT pt.id AS template_id,
192 STRING_AGG(pv.default_code, %s) AS default_codes
193 FROM product_template pt
194 JOIN product_product pv ON pv.product_tmpl_id = pt.id
195 WHERE pv.default_code IS NOT NULL
196 GROUP BY pt.id
197 ) AS variants
198 WHERE product_template.id = variants.template_id
199 """, RARE_DELIMITER))
200 return super()._auto_init()
201
202 #=== COMPUTE METHODS ===#
203
204 @api.depends('is_published')
205 def _compute_publish_date(self):
206 """Set `publish_date` to the moment of (re-)publishing."""
207 self.filtered('is_published').publish_date = fields.Datetime.now()
208
209 @api.depends('product_variant_ids', 'product_variant_ids.base_unit_count')
210 def _compute_base_unit_count(self):
211 self.base_unit_count = 0
212 for template in self.filtered(lambda template: len(template.product_variant_ids) == 1):
213 template.base_unit_count = template.product_variant_ids.base_unit_count
214
215 def _set_base_unit_count(self):
216 for template in self:
217 if len(template.product_variant_ids) == 1:
218 template.product_variant_ids.base_unit_count = template.base_unit_count
219
220 @api.depends('product_variant_ids', 'product_variant_ids.base_unit_count')
221 def _compute_base_unit_id(self):
222 self.base_unit_id = self.env['website.base.unit']
223 for template in self.filtered(lambda template: len(template.product_variant_ids) == 1):
224 template.base_unit_id = template.product_variant_ids.base_unit_id
225
226 def _set_base_unit_id(self):
227 for template in self:
228 if len(template.product_variant_ids) == 1:
229 template.product_variant_ids.base_unit_id = template.base_unit_id
230
231 def _get_base_unit_price(self, price):
232 self.ensure_one()
233 return self.base_unit_count and price / self.base_unit_count
234
235 @api.depends('list_price', 'base_unit_count')
236 def _compute_base_unit_price(self):
237 for template in self:
238 template.base_unit_price = template._get_base_unit_price(template.list_price)
239
240 @api.depends('uom_name', 'base_unit_id.name')
241 def _compute_base_unit_name(self):
242 for template in self:
243 template.base_unit_name = template.base_unit_id.name or template.uom_name
244
245 def _compute_website_url(self):
246 super()._compute_website_url()
247 for product in self:
248 if product.id:
249 product.website_url = "/shop/%s" % self.env['ir.http']._slug(product)
250
251 @api.depends('product_variant_ids.default_code')
252 def _compute_variants_default_code(self):
253 for template in self:
254 template.variants_default_code = RARE_DELIMITER.join(
255 template.product_variant_ids.filtered('default_code').mapped('default_code')
256 )
257
258 #=== CRUD METHODS ===#
259
260 def write(self, vals):
261 # Clear empty ecommerce description content to avoid side-effects on product pages
262 # when there is no content to display anyway.
263 if (
264 (description_ecommerce := vals.get('description_ecommerce'))
265 and is_html_empty(description_ecommerce)
266 and not ('media_iframe_video' in description_ecommerce or 'data-embedded' in description_ecommerce) # don't remove "empty" video div
267 ):
268 vals['description_ecommerce'] = ''
269 return super().write(vals)
270
271 #=== BUSINESS METHODS ===#
272
273 def _prepare_variant_values(self, combination):
274 variant_dict = super()._prepare_variant_values(combination)
275 variant_dict['base_unit_count'] = self.base_unit_count
276 return variant_dict
277
278 def _get_website_accessory_product(self):
279 domain = Domain(self.env['website'].sale_product_domain())
280 if not self.env.user._is_internal():
281 domain &= Domain('is_published', '=', True)
282 return self.accessory_product_ids.filtered_domain(domain)
283
284 def _get_website_alternative_product(self):
285 domain = self.env['website'].sale_product_domain()
286 return self.alternative_product_ids.filtered_domain(domain)
287
288 def _has_no_variant_attributes(self):
289 """Return whether this `product.template` has at least one no_variant
290 attribute.
291
292 :return: True if at least one no_variant attribute, False otherwise
293 :rtype: bool
294 """
295 self.ensure_one()
296 return any(a.create_variant == 'no_variant' for a in self.valid_product_template_attribute_line_ids.attribute_id)
297
298 def _has_is_custom_values(self):
299 self.ensure_one()
300 """Return whether this `product.template` has at least one is_custom
301 attribute value.
302
303 :return: True if at least one is_custom attribute value, False otherwise
304 :rtype: bool
305 """
306 return any(v.is_custom for v in self.valid_product_template_attribute_line_ids.product_template_value_ids._only_active())
307
308 def _get_possible_variants_sorted(self, parent_combination=None):
309 """Return the sorted recordset of variants that are possible.
310
311 The order is based on the order of the attributes and their values.
312
313 See `_get_possible_variants` for the limitations of this method with
314 dynamic or no_variant attributes, and also for a warning about
315 performances.
316
317 :param parent_combination: combination from which `self` is an
318 optional or accessory product
319 :type parent_combination: recordset `product.template.attribute.value`
320
321 :return: the sorted variants that are possible
322 :rtype: recordset of `product.product`
323 """
324 self.ensure_one()
325
326 def _sort_key_attribute_value(value):
327 # if you change this order, keep it in sync with _order from `product.attribute`
328 return (value.attribute_id.sequence, value.attribute_id.id)
329
330 def _sort_key_variant(variant):
331 """
332 We assume all variants will have the same attributes, with only one value for each.
333 - first level sort: same as "product.attribute"._order
334 - second level sort: same as "product.attribute.value"._order
335 """
336 keys = []
337 for attribute in variant.product_template_attribute_value_ids.sorted(_sort_key_attribute_value):
338 # if you change this order, keep it in sync with _order from `product.attribute.value`
339 keys.append(attribute.product_attribute_value_id.sequence)
340 keys.append(attribute.id)
341 return keys
342
343 return self._get_possible_variants(parent_combination).sorted(_sort_key_variant)
344
345 def _get_previewed_attribute_values(self, category=None, product_query_params=None):
346 """Compute previewed product attribute values for each product in the recordset.
347
348 :return: the previewed attribute values per product
349 :rtype: dict
350 """
351 res = defaultdict(dict)
352 show_count = 20
353 for template in self:
354 previewed_ptal = next((
355 p for p in template.attribute_line_ids
356 if p.attribute_id.preview_variants != 'hidden'
357 ), None)
358 if previewed_ptal:
359 previewed_ptavs = [
360 ptav
361 for ptav in previewed_ptal.product_template_value_ids
362 if ptav.ptav_active and ptav.ptav_product_variant_ids
363 ]
364
365 if len(previewed_ptavs) > 1:
366 previewed_ptavs_data = []
367 for ptav in previewed_ptavs[:show_count]:
368 matching_variant = min(ptav.ptav_product_variant_ids, key=lambda p: p.id)
369 variant_query_params = {
370 **(product_query_params or {}),
371 'attribute_values': str(ptav.product_attribute_value_id.id)
372 }
373 previewed_ptavs_data.append({
374 'ptav': ptav,
375 'variant_image_url': self.env['website'].image_url(matching_variant, 'image_512'),
376 'variant_url': template._get_product_url(category, variant_query_params),
377 })
378
379 res[template.id] = {
380 'ptavs_data': previewed_ptavs_data,
381 'hidden_ptavs_count': max(0, len(previewed_ptavs) - show_count)
382 }
383 return res
384
385 def _get_sales_prices(self, website):
386 if not self:
387 return {}
388
389 pricelist = request.pricelist
390 currency = website.currency_id
391 fiscal_position_sudo = request.fiscal_position
392 date = fields.Date.context_today(self)
393
394 pricelist_prices = pricelist._compute_price_rule(self, 1.0)
395 comparison_prices_enabled = self.env['res.groups']._is_feature_enabled(
396 'website_sale.group_product_price_comparison'
397 )
398
399 res = {}
400 for template in self:
401 pricelist_price, pricelist_rule_id = pricelist_prices[template.id]
402
403 product_taxes = template.sudo().taxes_id._filter_taxes_by_company(self.env.company)
404 taxes = fiscal_position_sudo.map_tax(product_taxes)
405
406 base_price = None
407 template_price_vals = {
408 'price_reduce': self._apply_taxes_to_price(
409 pricelist_price, currency, product_taxes, taxes, template, website=website,
410 ),
411 }
412 pricelist_item = template.env['product.pricelist.item'].browse(pricelist_rule_id)
413 if pricelist_item._show_discount_on_shop():
414 pricelist_base_price = pricelist_item._compute_price_before_discount(
415 product=template,
416 quantity=1.0,
417 date=date,
418 uom=template.uom_id,
419 currency=currency,
420 )
421 if currency.compare_amounts(pricelist_base_price, pricelist_price) == 1:
422 base_price = pricelist_base_price
423 template_price_vals['base_price'] = self._apply_taxes_to_price(
424 base_price, currency, product_taxes, taxes, template, website=website,
425 )
426
427 if not base_price and comparison_prices_enabled and template.compare_list_price:
428 template_price_vals['base_price'] = template.currency_id._convert(
429 template.compare_list_price,
430 currency,
431 self.env.company,
432 date,
433 round=False,
434 )
435
436 res[template.id] = template_price_vals
437
438 return res
439
440 def _can_be_added_to_cart(self):
441 """
442 Pre-check to `_is_add_to_cart_possible` to know if product can be sold.
443 """
444 self.ensure_one()
445 return bool(self.filtered_domain(self.env['website']._product_domain()))
446
447 def _is_add_to_cart_possible(self, parent_combination=None):
448 """
449 It's possible to add to cart (potentially after configuration) if
450 there is at least one possible combination.
451
452 :param parent_combination: the combination from which `self` is an
453 optional or accessory product.
454 :type parent_combination: recordset `product.template.attribute.value`
455
456 :return: True if it's possible to add to cart, else False
457 :rtype: bool
458 """
459 self.ensure_one()
460 if not self.active or not self._can_be_added_to_cart():
461 # for performance: avoid calling `_get_possible_combinations`
462 return False
463 return next(self._get_possible_combinations(parent_combination), False) is not False
464
465 def _get_combination_info(
466 self, combination=False, product_id=False, add_qty=1.0, uom_id=False, only_template=False,
467 ):
468 """Return info about a given combination.
469
470 Note: this method does not take into account whether the combination is
471 actually possible.
472
473 :param combination: recordset of `product.template.attribute.value`
474
475 :param int product_id: `product.product` id. If no `combination`
476 is set, the method will try to load the variant `product_id` if
477 it exists instead of finding a variant based on the combination.
478
479 If there is no combination, that means we definitely want a
480 variant and not something that will have no_variant set.
481
482 :param float add_qty: the quantity for which to get the info,
483 indeed some pricelist rules might depend on it.
484 :param int|None uom_id: the uom for which to get the info, as an `uom.uom` id.
485
486 :param only_template: boolean, if set to True, get the info for the
487 template only: ignore combination and don't try to find variant
488
489 :return: dict with product/combination info:
490
491 - product_id: the variant id matching the combination (if it exists)
492
493 - product_template_id: the current template id
494
495 - display_name: the name of the combination
496
497 - price: the computed price of the combination, take the catalog
498 price if no pricelist is given
499
500 - price_extra: the computed extra price of the combination
501
502 - list_price: the catalog price of the combination, but this is
503 not the "real" list_price, it has price_extra included (so
504 it's actually more closely related to `lst_price`), and it
505 is converted to the pricelist currency (if given)
506
507 - has_discounted_price: True if the pricelist discount policy says
508 the price does not include the discount and there is actually a
509 discount applied (price < list_price), else False
510 """
511 self.ensure_one()
512
513 combination = combination or self.env['product.template.attribute.value']
514 website = request.website.with_context(self.env.context)
515 uom = self.env['uom.uom'].browse(uom_id) or self.uom_id
516
517 if not product_id and not combination and not only_template:
518 combination = self._get_first_possible_combination()
519
520 if only_template:
521 product = self.env['product.product']
522 elif product_id:
523 product = self.env['product.product'].browse(product_id)
524 if (combination - product.product_template_attribute_value_ids):
525 # If the combination is not fully represented in the given product
526 # make sure to fetch the right product for the given combination
527 product = self._get_variant_for_combination(combination)
528 else:
529 product = self._get_variant_for_combination(combination)
530
531 product_or_template = product or self
532 combination = combination or product.product_template_attribute_value_ids
533
534 display_name = product_or_template.with_context(display_default_code=False).display_name
535 if not product:
536 combination_name = combination._get_combination_name()
537 if combination_name:
538 display_name = f"{display_name} ({combination_name})"
539
540 price_context = product_or_template._get_product_price_context(combination)
541 product_or_template = product_or_template.with_context(**price_context)
542
543 combination_info = {
544 'combination': combination,
545 'product_id': product.id,
546 'product_template_id': self.id,
547 'display_name': display_name,
548 'is_combination_possible': self._is_combination_possible(combination=combination),
549
550 **self._get_additionnal_combination_info(
551 product_or_template=product_or_template,
552 quantity=add_qty or 1.0,
553 uom=uom,
554 date=fields.Date.context_today(self),
555 website=website,
556 )
557 }
558
559 if website.google_analytics_key:
560 combination_info['product_tracking_info'] = self._get_google_analytics_data(
561 product,
562 combination_info,
563 )
564
565 if (
566 product_or_template.type == 'combo'
567 and website.show_line_subtotals_tax_selection == 'tax_included'
568 and not all(
569 tax.price_include
570 for tax
571 in product_or_template.sudo().combo_ids.combo_item_ids.product_id.taxes_id
572 )
573 ):
574 combination_info['tax_disclaimer'] = _(
575 "Final price may vary based on selection. Tax will be calculated at checkout."
576 )
577
578 return combination_info
579
580 def _get_additionnal_combination_info(self, product_or_template, quantity, uom, date, website):
581 """Compute additional combination info, based on given parameters.
582
583 :param product_or_template: `product.product` or `product.template` record
584 as variant values must take precedence over template values (when we have a variant)
585 :param float quantity: requested quantity
586 :param uom: `uom.uom` record
587 :param date date: today's date, avoids useless calls to today/context_today and harmonize
588 behavior
589 :param website: `website` record holding the current website of the request (if any),
590 or the contextual website (tests, ...)
591 :returns: additional product/template information
592 :rtype: dict
593 """
594 pricelist = request.pricelist.with_context(self.env.context)
595 currency = website.currency_id.with_context(self.env.context)
596
597 # Pricelist price doesn't have to be converted
598 pricelist_price, pricelist_rule_id = pricelist._get_product_price_rule(
599 product=product_or_template,
600 quantity=quantity,
601 uom=uom,
602 currency=currency,
603 )
604
605 price_before_discount = pricelist_price
606 pricelist_item = self.env['product.pricelist.item'].browse(pricelist_rule_id)
607 if pricelist_item._show_discount_on_shop():
608 price_before_discount = pricelist_item._compute_price_before_discount(
609 product=product_or_template,
610 quantity=quantity or 1.0,
611 date=date,
612 uom=uom,
613 currency=currency,
614 )
615
616 has_discounted_price = currency.compare_amounts(price_before_discount, pricelist_price) == 1
617 combination_info = {
618 'list_price': max(pricelist_price, price_before_discount),
619 'price': pricelist_price,
620 'has_discounted_price': has_discounted_price,
621 'discount_start_date': pricelist_item.date_start,
622 'discount_end_date': pricelist_item.date_end,
623 }
624
625 if (
626 not has_discounted_price
627 and product_or_template.compare_list_price
628 and self.env['res.groups']._is_feature_enabled(
629 'website_sale.group_product_price_comparison'
630 )
631 ):
632 # TODO VCR comparison price only depends on the product template, but is shown/hidden
633 # depending on product price, should be removed from combination info in the future
634 combination_info['compare_list_price'] = product_or_template.currency_id._convert(
635 from_amount=product_or_template.compare_list_price,
636 to_currency=currency,
637 company=self.env.company,
638 date=date,
639 round=False,
640 )
641
642 # Apply taxes
643 product_taxes = product_or_template.sudo().taxes_id._filter_taxes_by_company(self.env.company)
644 taxes = self.env['account.tax']
645 if product_taxes:
646 taxes = request.fiscal_position.map_tax(product_taxes)
647 # We do not apply taxes on the compare_list_price value because it's meant to be
648 # a strict value displayed as is.
649 for price_key in ('price', 'list_price'):
650 combination_info[price_key] = self._apply_taxes_to_price(
651 combination_info[price_key],
652 currency,
653 product_taxes,
654 taxes,
655 product_or_template,
656 website=website,
657 )
658
659 combination_info.update({
660 'prevent_zero_price_sale': website.prevent_zero_price_sale and float_is_zero(
661 combination_info['price'],
662 precision_rounding=currency.rounding,
663 ),
664
665 # additional info to simplify overrides
666 'currency': currency, # displayed currency
667 'date': date,
668 'product_taxes': product_taxes, # taxes before fpos mapping
669 'taxes': taxes, # taxes after fpos mapping
670 })
671
672 if self.env['res.groups']._is_feature_enabled('website_sale.group_show_uom_price'):
673 price_per_product_uom = uom._compute_price(
674 price=combination_info['price'], to_unit=self.uom_id
675 )
676 combination_info.update({
677 'base_unit_name': product_or_template.base_unit_name,
678 'base_unit_price': product_or_template._get_base_unit_price(price_per_product_uom),
679 })
680
681 if combination_info['prevent_zero_price_sale']:
682 # If price is zero and prevent_zero_price_sale is enabled we don't want to send any
683 # price information regarding the product
684 combination_info['compare_list_price'] = 0
685
686 return combination_info
687
688 @api.model
689 def _apply_taxes_to_price(
690 self, price, currency, product_taxes, taxes, product_or_template,
691 website=None,
692 ):
693 website = website or self.env['website'].get_current_website()
694 price = self.env['product.product']._get_tax_included_unit_price_from_price(
695 price,
696 product_taxes,
697 product_taxes_after_fp=taxes,
698 )
699 show_tax = website.show_line_subtotals_tax_selection
700 tax_display = 'total_excluded' if show_tax == 'tax_excluded' else 'total_included'
701
702 # The list_price is always the price of one.
703 return taxes.compute_all(
704 price, currency, 1, product_or_template, self.env.user.partner_id
705 )[tax_display]
706
707 def create_product_variant(self, product_template_attribute_value_ids):
708 """ Create if necessary and possible and return the id of the product
709 variant matching the given combination for this template.
710
711 Note AWA: Known "exploit" issues with this method:
712
713 - This method could be used by an unauthenticated user to generate a
714 lot of useless variants. Unfortunately, after discussing the
715 matter with ODO, there's no easy and user-friendly way to block
716 that behavior.
717 We would have to use captcha/server actions to clean/... that
718 are all not user-friendly/overkill mechanisms.
719
720 - This method could be used to try to guess what product variant ids
721 are created in the system and what product template ids are
722 configured as "dynamic", but that does not seem like a big deal.
723
724 The error messages are identical on purpose to avoid giving too much
725 information to a potential attacker:
726
727 - returning 0 when failing
728 - returning the variant id whether it already existed or not
729
730 :param product_template_attribute_value_ids: the combination for which
731 to get or create variant
732
733 :type product_template_attribute_value_ids: list of id
734 of `product.template.attribute.value`
735
736 :return: id of the product variant matching the combination or 0
737 :rtype: int
738 """
739 combination = self.env['product.template.attribute.value'].browse(
740 product_template_attribute_value_ids)
741
742 return self._create_product_variant(combination, log_warning=True).id or 0
743
744 def _get_image_holder(self):
745 """Returns the holder of the image to use as default representation.
746 If the product template has an image it is the product template,
747 otherwise if the product has variants it is the first variant
748
749 :return: this product template or the first product variant
750 :rtype: recordset of 'product.template' or recordset of 'product.product'
751 """
752 self.ensure_one()
753 if self.image_128:
754 return self
755 variant = self.env['product.product'].browse(self._get_first_possible_variant_id())
756 # if the variant has no image anyway, spare some queries by using template
757 return variant if variant.image_variant_128 else self
758
759 def _get_suitable_image_size(self, columns, x_size, y_size):
760 if x_size == 1 and y_size == 1 and columns >= 3:
761 return 'image_512'
762 return 'image_1024'
763
764 def _init_column(self, column_name):
765 # to avoid generating a single default website_sequence when installing the module,
766 # we need to set the default row by row for this column
767 if column_name == "website_sequence":
768 _logger.debug("Table '%s': setting default value of new column %s to unique values for each row", self._table, column_name)
769 self.env.cr.execute("SELECT id FROM %s WHERE website_sequence IS NULL" % self._table)
770 prod_tmpl_ids = self.env.cr.dictfetchall()
771 max_seq = self._default_website_sequence()
772 query = f"""
773 UPDATE {self._table}
774 SET website_sequence = p.web_seq
775 FROM (VALUES %s) AS p(p_id, web_seq)
776 WHERE id = p.p_id
777 """
778 values_args = [(prod_tmpl['id'], max_seq + i * 5) for i, prod_tmpl in enumerate(prod_tmpl_ids)]
779 self.env.cr.execute_values(query, values_args)
780 else:
781 super()._init_column(column_name)
782
783 def set_sequence_top(self):
784 min_sequence = self.sudo().search([], order='website_sequence ASC', limit=1)
785 self.website_sequence = min_sequence.website_sequence - 5
786
787 def set_sequence_bottom(self):
788 max_sequence = self.sudo().search([], order='website_sequence DESC', limit=1)
789 self.website_sequence = max_sequence.website_sequence + 5
790
791 def set_sequence_up(self):
792 previous_product_tmpl = self.sudo().search([
793 ('website_sequence', '<', self.website_sequence),
794 ('website_published', '=', self.website_published),
795 ], order='website_sequence DESC', limit=1)
796 if previous_product_tmpl:
797 previous_product_tmpl.website_sequence, self.website_sequence = self.website_sequence, previous_product_tmpl.website_sequence
798 else:
799 self.set_sequence_top()
800
801 def set_sequence_down(self):
802 next_prodcut_tmpl = self.search([
803 ('website_sequence', '>', self.website_sequence),
804 ('website_published', '=', self.website_published),
805 ], order='website_sequence ASC', limit=1)
806 if next_prodcut_tmpl:
807 next_prodcut_tmpl.website_sequence, self.website_sequence = self.website_sequence, next_prodcut_tmpl.website_sequence
808 else:
809 return self.set_sequence_bottom()
810
811 def _default_website_meta(self):
812 res = super()._default_website_meta()
813 res['default_opengraph']['og:description'] = res['default_twitter']['twitter:description'] = self.description_sale
814 res['default_opengraph']['og:title'] = res['default_twitter']['twitter:title'] = self.name
815 res['default_opengraph']['og:image'] = res['default_twitter']['twitter:image'] = self.env['website'].image_url(self, 'image_1024')
816 res['default_meta_description'] = self.description_sale
817 return res
818
819 @api.model
820 def _get_alternative_product_filter(self):
821 return self.env.ref('website_sale.dynamic_filter_cross_selling_alternative_products').id
822
823 @api.model
824 def _get_product_types_allow_zero_price(self):
825 """
826 Returns a list of service_tracking (`product.template.service_tracking`) that can ignore the
827 `prevent_zero_price_sale` rule when buying products on a website.
828 """
829 return []
830
831 # ---------------------------------------------------------
832 # Rating Mixin API
833 # ---------------------------------------------------------
834
835 def _rating_domain(self):
836 """ Only take the published rating into account to compute avg and count """
837 return super()._rating_domain() & Domain('is_internal', '=', False)
838
839 def _get_images(self):
840 """Return a list of records implementing `image.mixin` to
841 display on the carousel on the website for this template.
842
843 This returns a list and not a recordset because the records might be
844 from different models (template and image).
845
846 It contains in this order: the main image of the template and the
847 Template Extra Images.
848 """
849 self.ensure_one()
850 return [self] + list(self.product_template_image_ids)
851
852 def _get_attribute_value_domain(self, attribute_value_dict):
853 return [
854 [('attribute_line_ids.value_ids', 'in', attribute_value_ids)]
855 for attribute_value_ids in attribute_value_dict.values()
856 ]
857
858 @api.model
859 def _search_get_detail(self, website, order, options):
860 with_image = options['displayImage']
861 with_description = options['displayDescription']
862 with_category = options['displayExtraLink']
863 with_price = options['displayDetail']
864 domains = [website.sale_product_domain()]
865 category = options.get('category')
866 tags = options.get('tags')
867 min_price = options.get('min_price')
868 max_price = options.get('max_price')
869 attribute_value_dict = options.get('attribute_value_dict')
870 if category:
871 domains.append([('public_categ_ids', 'child_of', self.env['ir.http']._unslug(category)[1])])
872 if tags:
873 if isinstance(tags, str):
874 tags = tags.split(',')
875 tags = list(map(int, tags)) # Convert list of strings to list of integers
876 domains.append(Domain.OR([
877 Domain('product_tag_ids', 'in', tags),
878 Domain('product_variant_ids.additional_product_tag_ids', 'in', tags),
879 ]))
880 if min_price:
881 domains.append([('list_price', '>=', min_price)])
882 if max_price:
883 domains.append([('list_price', '<=', max_price)])
884 if attribute_value_dict:
885 domains.extend(self._get_attribute_value_domain(attribute_value_dict))
886 search_fields = ['name', 'default_code', 'variants_default_code']
887 fetch_fields = ['id', 'name', 'website_url']
888 mapping = {
889 'name': {'name': 'name', 'type': 'text', 'match': True},
890 'default_code': {'name': 'default_code', 'type': 'text', 'match': True},
891 'product_variant_ids.default_code': {'name': 'product_variant_ids.default_code', 'type': 'text', 'match': True},
892 'website_url': {'name': 'website_url', 'type': 'text', 'truncate': False},
893 }
894 if with_image:
895 mapping['image_url'] = {'name': 'image_url', 'type': 'html'}
896 if with_description:
897 # Internal note is not part of the rendering.
898 search_fields.append('description')
899 fetch_fields.append('description')
900 search_fields.append('description_sale')
901 fetch_fields.append('description_sale')
902 mapping['description'] = {'name': 'description_sale', 'type': 'text', 'match': True}
903 if with_price:
904 mapping['detail'] = {'name': 'price', 'type': 'html', 'display_currency': options['display_currency']}
905 mapping['detail_strike'] = {'name': 'list_price', 'type': 'html', 'display_currency': options['display_currency']}
906 if with_category:
907 mapping['extra_link'] = {'name': 'category', 'type': 'html'}
908 return {
909 'model': 'product.template',
910 'base_domain': domains,
911 'search_fields': search_fields,
912 'fetch_fields': fetch_fields,
913 'mapping': mapping,
914 'icon': 'fa-shopping-cart',
915 }
916
917 def _search_render_results(self, fetch_fields, mapping, icon, limit):
918 with_image = 'image_url' in mapping
919 with_category = 'extra_link' in mapping
920 with_price = 'detail' in mapping
921 results_data = super()._search_render_results(fetch_fields, mapping, icon, limit)
922 current_website = self.env['website'].get_current_website()
923 for product, data in zip(self, results_data):
924 categ_ids = product.public_categ_ids.filtered(lambda c: not c.website_id or c.website_id == current_website)
925 if with_price:
926 combination_info = product._get_combination_info(only_template=True)
927 data['price'], list_price = self._search_render_results_prices(
928 mapping, combination_info
929 )
930 if list_price:
931 data['list_price'] = list_price
932
933 if with_image:
934 data['image_url'] = '/web/image/product.template/%s/image_128' % data['id']
935 if with_category and categ_ids:
936 data['category'] = self.env['ir.ui.view'].sudo()._render_template(
937 "website_sale.product_category_extra_link",
938 {
939 'categories': categ_ids,
940 'slug': self.env['ir.http']._slug,
941 'shop_path': SHOP_PATH,
942 }
943 )
944 return results_data
945
946 def _search_render_results_prices(self, mapping, combination_info):
947 if combination_info.get('prevent_zero_price_sale'):
948 return None, None
949
950 monetary_options = {'display_currency': mapping['detail']['display_currency']}
951 price = self.env['ir.qweb.field.monetary'].value_to_html(
952 combination_info['price'], monetary_options
953 )
954 list_price = None
955 if combination_info['has_discounted_price']:
956 list_price = self.env['ir.qweb.field.monetary'].value_to_html(
957 combination_info['list_price'], monetary_options
958 )
959 if combination_info.get('compare_list_price'):
960 list_price = self.env['ir.qweb.field.monetary'].value_to_html(
961 combination_info['compare_list_price'], monetary_options
962 )
963
964 return price, list_price
965
966 def _get_google_analytics_data(self, product, combination_info):
967 self.ensure_one()
968 return {
969 'item_id': product.barcode or product.id,
970 'item_name': combination_info['display_name'],
971 'item_category': self.categ_id.name,
972 'currency': combination_info['currency'].name,
973 'price': combination_info['list_price'],
974 }
975
976 def _get_contextual_pricelist(self):
977 """ Override to fallback on website current pricelist """
978 pricelist = super()._get_contextual_pricelist()
979 if request and request.is_frontend and not pricelist:
980 return request.pricelist
981 return pricelist
982
983 def _website_show_quick_add(self):
984 self.ensure_one()
985 if not self.filtered_domain(self.env['website']._product_domain()):
986 return False
987 return not request.website.prevent_zero_price_sale or self._get_contextual_price()
988
989 @api.model
990 def _get_configurator_display_price(
991 self, product_or_template, quantity, date, currency, pricelist, **kwargs
992 ):
993 """ Override of `sale` to apply taxes.
994
995 :param product.product|product.template product_or_template: The product for which to get
996 the price.
997 :param int quantity: The quantity of the product.
998 :param datetime date: The date to use to compute the price.
999 :param res.currency currency: The currency to use to compute the price.
1000 :param product.pricelist pricelist: The pricelist to use to compute the price.
1001 :param dict kwargs: Locally unused data passed to `super`.
1002 :rtype: tuple(float, int or False)
1003 :return: The specified product's display price (and the applied pricelist rule)
1004 """
1005 price, pricelist_rule_id = super()._get_configurator_display_price(
1006 product_or_template, quantity, date, currency, pricelist, **kwargs
1007 )
1008
1009 if website := ir_http.get_request_website():
1010 product_taxes = product_or_template.sudo().taxes_id._filter_taxes_by_company(
1011 self.env.company
1012 )
1013 if product_taxes:
1014 taxes = request.fiscal_position.map_tax(product_taxes)
1015 return self._apply_taxes_to_price(
1016 price, currency, product_taxes, taxes, product_or_template, website=website
1017 ), pricelist_rule_id
1018 return price, pricelist_rule_id
1019
1020 def _to_markup_data(self, website):
1021 """ Generate JSON-LD markup data for the current product template.
1022
1023 If the template has multiple variants, the https://schema.org/ProductGroup schema is used.
1024 Otherwise, the markup data generation is delegated to the variant to use the
1025 https://schema.org/Product schema.
1026
1027 :param website website: The current website.
1028 :return: The JSON-LD markup data.
1029 :rtype: dict
1030 """
1031 self.ensure_one()
1032
1033 if self.product_variant_count == 1:
1034 return self.product_variant_id._to_markup_data(website)
1035
1036 # perf: temporal solution to avoid slowness when product have many variants and pricelist rules
1037 limit = self.env['ir.config_parameter'].sudo().get_param('website_sale.markup_data_limit_variants', False)
1038 if limit:
1039 product_variant_ids = self.product_variant_ids[:int(limit)]
1040 else:
1041 product_variant_ids = self.product_variant_ids
1042
1043 base_url = website.get_base_url()
1044 markup_data = {
1045 '@context': 'https://schema.org/',
1046 '@type': 'ProductGroup',
1047 'name': self.name,
1048 'image': f'{base_url}{website.image_url(self, "image_1920")}',
1049 'url': f'{base_url}{self.website_url}',
1050 'hasVariant': [product._to_markup_data(website) for product in product_variant_ids]
1051 }
1052 if self.description_ecommerce:
1053 markup_data['description'] = text_from_html(self.description_ecommerce)
1054 return markup_data
1055
1056 def _get_ribbon(self, price_vals=None, auto_assign_ribbons=None, variant=None):
1057 """Return the ribbon to display for the current template.
1058
1059 It'll be either the ribbon set on the first variant, or the template, or the first
1060 applicable ribbon in the automatically assigned ribbons.
1061
1062 :param dict price_vals: price values for the current product
1063 :param auto_assign_ribbons: automatically assigned recordsets, as a `product.ribbon`
1064 recordset
1065 :param product.product variant: if any, the displayed variant whose ribbon we're looking
1066 for.
1067
1068 :returns: the ribbon to display, if there is one.
1069 :rtype: `product.ribbon` recordset
1070 """
1071 variant = variant or self.product_variant_id
1072 ribbon = variant.sudo().variant_ribbon_id or self.sudo().website_ribbon_id
1073 if not ribbon:
1074 # The None check ensures that we do not recompute the ribbons when no ribbons were
1075 # previously found.
1076 if auto_assign_ribbons is None:
1077 # On product page, the auto_assign_ribbons are not provided.
1078 auto_assign_ribbons = self.env['product.ribbon'].search_fetch([
1079 ('assign', '!=', 'manual'),
1080 ])
1081 for rb in auto_assign_ribbons:
1082 if rb._is_applicable_for(variant, price_vals):
1083 return rb
1084
1085 return ribbon
1086
1087 def _get_access_action(self, access_uid=None, force_website=False):
1088 """ Instead of the classic form view, redirect to website if it is published. """
1089 self.ensure_one()
1090 if force_website or (self.website_published and self.env.user.share):
1091 return {
1092 "type": "ir.actions.act_url",
1093 "url": self.website_url,
1094 "target": "self",
1095 "target_type": "public",
1096 }
1097 return super()._get_access_action(access_uid=access_uid, force_website=force_website)
1098
1099 @api.model
1100 def _allow_publish_rating_stats(self):
1101 return True
1102
1103 def _get_product_url(self, category=None, query_params=None, grouped_attributes_values=None):
1104 self.ensure_one()
1105 slug = self.env['ir.http']._slug
1106
1107 url = (category and f'/shop/{slug(category)}/{slug(self)}') or self.website_url
1108
1109 query_params = query_params or {}
1110 if grouped_attributes_values:
1111 product_grouped_values = self.attribute_line_ids.value_ids.grouped('attribute_id')
1112 available_pav_ids = [
1113 next(v.id for v in pavs if v in product_grouped_values[pa])
1114 for pa, pavs in grouped_attributes_values.items()
1115 if pa in product_grouped_values
1116 ]
1117 available_pav_ids.sort()
1118 query_params['attribute_values'] = ','.join(str(i) for i in available_pav_ids)
1119
1120 if query_params:
1121 url = f'{url}?{urls.url_encode(query_params)}'
1122
1123 return url