| 1 |
|
| 2 |
|
| 3 |
import base64 |
| 4 |
import gzip |
| 5 |
import uuid |
| 6 |
|
| 7 |
from dateutil.relativedelta import relativedelta |
| 8 |
from werkzeug.urls import url_encode, url_parse |
| 9 |
|
| 10 |
from odoo import SUPERUSER_ID, api, fields, models |
| 11 |
from odoo.exceptions import ValidationError |
| 12 |
from odoo.fields import Domain |
| 13 |
from odoo.http import request |
| 14 |
from odoo.tools import float_is_zero, float_round, urls |
| 15 |
|
| 16 |
from odoo.addons.website_sale import const, utils |
| 17 |
|
| 18 |
|
| 19 |
class ProductFeed(models.Model): |
| 20 |
_name = 'product.feed' |
| 21 |
_inherit = ['mail.thread'] |
| 22 |
_description = "Product Feed" |
| 23 |
|
| 24 |
name = fields.Char(required=True) |
| 25 |
website_id = fields.Many2one('website', required=True) |
| 26 |
pricelist_id = fields.Many2one( |
| 27 |
'product.pricelist', |
| 28 |
help="Specify a pricelist to localize the feed with a specific currency." |
| 29 |
" If not set, the default website pricelist will be used." |
| 30 |
"\nNote that the pricelist must be selectable on the website.", |
| 31 |
domain="[('website_id', 'in', (False, website_id)), ('selectable', '=', True)]", |
| 32 |
) |
| 33 |
lang_id = fields.Many2one( |
| 34 |
'res.lang', |
| 35 |
string="Language", |
| 36 |
help="Select the language to translate product names, descriptions," |
| 37 |
" and other text in the feed.", |
| 38 |
compute='_compute_lang_id', |
| 39 |
precompute=True, |
| 40 |
store=True, |
| 41 |
readonly=False, |
| 42 |
required=True, |
| 43 |
domain="[('id', 'in', website_lang_ids)]", |
| 44 |
) |
| 45 |
website_lang_ids = fields.Many2many(related='website_id.language_ids') |
| 46 |
product_category_ids = fields.Many2many('product.public.category', string="Categories") |
| 47 |
target = fields.Selection( |
| 48 |
selection=[ |
| 49 |
('gmc', "Google Merchant Center"), |
| 50 |
], |
| 51 |
required=True, |
| 52 |
default='gmc', |
| 53 |
) |
| 54 |
access_token = fields.Char( |
| 55 |
readonly=True, |
| 56 |
required=True, |
| 57 |
default=lambda _: uuid.uuid4().hex, |
| 58 |
copy=False, |
| 59 |
) |
| 60 |
url = fields.Char(compute='_compute_url') |
| 61 |
|
| 62 |
last_notification_date = fields.Date() |
| 63 |
|
| 64 |
|
| 65 |
feed_cache = fields.Binary(compute='_compute_feed_cache', store=True, readonly=True) |
| 66 |
cache_expiry = fields.Datetime(readonly=True, required=True, default=fields.Datetime.now) |
| 67 |
|
| 68 |
@api.depends('target') |
| 69 |
def _compute_url(self): |
| 70 |
"""Compute the full feed url.""" |
| 71 |
for feed in self: |
| 72 |
match feed.target: |
| 73 |
case 'gmc': |
| 74 |
path = '/gmc.xml' |
| 75 |
case _: |
| 76 |
raise NotImplementedError |
| 77 |
|
| 78 |
feed.url = urls.urljoin( |
| 79 |
feed.website_id.get_base_url(), |
| 80 |
f'{path}?feed_id={feed.id}&access_token={feed.access_token}', |
| 81 |
) |
| 82 |
|
| 83 |
@api.depends('website_id') |
| 84 |
def _compute_lang_id(self): |
| 85 |
for feed in self.filtered(lambda f: not f.lang_id): |
| 86 |
feed.lang_id = feed.website_id.default_lang_id |
| 87 |
|
| 88 |
@api.depends( |
| 89 |
'website_id', 'pricelist_id', 'lang_id', 'product_category_ids' |
| 90 |
) |
| 91 |
def _compute_feed_cache(self): |
| 92 |
"""Invalidate cache on feed parameter changes.""" |
| 93 |
self.action_invalidate_cache() |
| 94 |
|
| 95 |
@api.constrains('product_category_ids', 'website_id') |
| 96 |
def _check_product_limit(self): |
| 97 |
"""Add a soft limit on the number of products a feed can contain. |
| 98 |
|
| 99 |
A strong limit of 6000 is applied during the feed rendering phase. |
| 100 |
""" |
| 101 |
for feed in self: |
| 102 |
product_count = feed.env['product.product'].search_count( |
| 103 |
feed._get_feed_product_domain(), limit=const.PRODUCT_FEED_SOFT_LIMIT + 1 |
| 104 |
) |
| 105 |
if product_count > const.PRODUCT_FEED_SOFT_LIMIT: |
| 106 |
raise ValidationError(feed.env._( |
| 107 |
"A single feed cannot contain more than %(limit)s products." |
| 108 |
" Please separate products with Categories.", |
| 109 |
limit=f"{const.PRODUCT_FEED_SOFT_LIMIT:,}", |
| 110 |
)) |
| 111 |
|
| 112 |
def action_invalidate_cache(self): |
| 113 |
self.cache_expiry = fields.Datetime.now() - relativedelta(days=1) |
| 114 |
|
| 115 |
return { |
| 116 |
'type': 'ir.actions.client', |
| 117 |
'tag': 'display_notification', |
| 118 |
'params': { |
| 119 |
'type': 'success', |
| 120 |
'message': self.env._("Feed cache successfully reset."), |
| 121 |
}, |
| 122 |
} |
| 123 |
|
| 124 |
def _render_and_cache_compressed_gmc_feed(self): |
| 125 |
"""Render and cache the Google Merchant Center feed. |
| 126 |
|
| 127 |
This method ensures that the feed is rendered only once per day and caches the result. If |
| 128 |
the feed parameters change, the cache is invalidated, and the feed is re-rendered. |
| 129 |
|
| 130 |
:raises LockError: If the feed is already being rendered by another request. |
| 131 |
:return: The rendered feed compressed using gzip. |
| 132 |
:rtype: bytes |
| 133 |
""" |
| 134 |
self.ensure_one() |
| 135 |
|
| 136 |
if not self.feed_cache or self.cache_expiry < fields.Datetime.now(): |
| 137 |
|
| 138 |
self.lock_for_update() |
| 139 |
gmc_xml = self._render_gmc_feed() |
| 140 |
compressed_gmc_xml = gzip.compress(gmc_xml.encode()) |
| 141 |
|
| 142 |
|
| 143 |
self.feed_cache = base64.b64encode(compressed_gmc_xml) |
| 144 |
self.cache_expiry = fields.Datetime.today() + relativedelta(days=1) |
| 145 |
return compressed_gmc_xml |
| 146 |
|
| 147 |
return base64.b64decode(self.feed_cache) |
| 148 |
|
| 149 |
def _render_gmc_feed(self): |
| 150 |
"""Render the Google Merchant Center feed. |
| 151 |
|
| 152 |
See also https://support.google.com/merchants/answer/7052112 for the XML format. |
| 153 |
|
| 154 |
:return: The rendered XML feed. |
| 155 |
:rtype: str |
| 156 |
""" |
| 157 |
self.ensure_one() |
| 158 |
|
| 159 |
|
| 160 |
self = self.with_context(lang=self.lang_id.code) |
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
if self.pricelist_id: |
| 165 |
request.pricelist = self.pricelist_id |
| 166 |
|
| 167 |
homepage_url = self.website_id.homepage_url or '/' |
| 168 |
website_homepage = self.website_id._get_website_pages( |
| 169 |
Domain([('url', '=', homepage_url), ('website_id', '!=', False)]), limit=1 |
| 170 |
) |
| 171 |
|
| 172 |
gmc_data = { |
| 173 |
'title': website_homepage.website_meta_title or self.website_id.name, |
| 174 |
'link': urls.urljoin( |
| 175 |
self.website_id.get_base_url(), |
| 176 |
self.env['ir.http']._url_lang(homepage_url, lang_code=self.lang_id.code), |
| 177 |
), |
| 178 |
'description': website_homepage.website_meta_description or self.website_id, |
| 179 |
'items': self._prepare_gmc_items(), |
| 180 |
} |
| 181 |
|
| 182 |
return self.env['ir.ui.view'].sudo()._render_template( |
| 183 |
'website_sale.gmc_xml', gmc_data, |
| 184 |
) |
| 185 |
|
| 186 |
def _prepare_gmc_items(self): |
| 187 |
"""Prepare Google Merchant Center items' fields. |
| 188 |
|
| 189 |
See Google's (https://support.google.com/merchants/answer/7052112) documentation for more |
| 190 |
information about each field. |
| 191 |
|
| 192 |
:return: a dictionary for each product in this recordset. |
| 193 |
:rtype: list[dict] |
| 194 |
""" |
| 195 |
products = self._get_feed_products() |
| 196 |
base_url = self.website_id.get_base_url() |
| 197 |
|
| 198 |
def format_product_link(url_): |
| 199 |
if self.pricelist_id: |
| 200 |
parsed_url = url_parse(url_) |
| 201 |
query = parsed_url.decode_query() |
| 202 |
query['pricelist'] = self.pricelist_id.id |
| 203 |
url_ = parsed_url._replace(query=url_encode(query)).to_url() |
| 204 |
return urls.urljoin( |
| 205 |
base_url, self.env['ir.http']._url_lang(url_, lang_code=self.lang_id.code) |
| 206 |
) |
| 207 |
|
| 208 |
return { |
| 209 |
product: { |
| 210 |
'id': product.default_code or product.id, |
| 211 |
'title': product.with_context(display_default_code=False).display_name, |
| 212 |
'description': product.website_meta_description or product.description_sale, |
| 213 |
'link': format_product_link(product.website_url), |
| 214 |
**self._prepare_gmc_identifier(product), |
| 215 |
**self._prepare_gmc_image_links(product, base_url), |
| 216 |
**price_info, |
| 217 |
**self._prepare_gmc_stock_info(product), |
| 218 |
**self._prepare_gmc_additional_info(product), |
| 219 |
} |
| 220 |
for product in products |
| 221 |
if product._is_variant_possible() |
| 222 |
and (price_info := self._prepare_gmc_price_info(product)) |
| 223 |
} |
| 224 |
|
| 225 |
def _get_feed_product_domain(self): |
| 226 |
product_domain = self.website_id._get_basic_feed_product_domain() |
| 227 |
if self.product_category_ids: |
| 228 |
product_domain &= Domain('public_categ_ids', 'child_of', self.product_category_ids.ids) |
| 229 |
|
| 230 |
return product_domain |
| 231 |
|
| 232 |
def _get_feed_products(self): |
| 233 |
product_domain = self._get_feed_product_domain() |
| 234 |
|
| 235 |
products = self.env['product.product'].search( |
| 236 |
product_domain, limit=const.PRODUCT_FEED_HARD_LIMIT |
| 237 |
) |
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
if len(products) > (const.PRODUCT_FEED_SOFT_LIMIT + const.PRODUCT_FEED_HARD_LIMIT) / 2: |
| 242 |
today = fields.Date.today() |
| 243 |
if ( |
| 244 |
not self.last_notification_date |
| 245 |
or relativedelta(today, self.last_notification_date).weeks > 0 |
| 246 |
): |
| 247 |
self._notify_website_manager( |
| 248 |
subject=self.env._("GMC: Product Limit Exceeded"), |
| 249 |
body=self.env._( |
| 250 |
"The feed %(feed_name)s contains more than %(limit)s products," |
| 251 |
" which may not be fully updated. Consider refining the feed by adjusting" |
| 252 |
" the product categories.", |
| 253 |
feed_name=self.display_name, |
| 254 |
limit=f"{const.PRODUCT_FEED_SOFT_LIMIT:,}", |
| 255 |
), |
| 256 |
) |
| 257 |
self.last_notification_date = today |
| 258 |
|
| 259 |
return products |
| 260 |
|
| 261 |
def _prepare_gmc_identifier(self, product): |
| 262 |
"""Prepare the product identifiers for Google Merchant Center. |
| 263 |
|
| 264 |
:return: The barcode of the product as GTIN |
| 265 |
:rtype: dict |
| 266 |
""" |
| 267 |
if product.barcode: |
| 268 |
return {'gtin': product.barcode, 'identifier_exists': 'yes'} |
| 269 |
return {'identifier_exists': 'no'} |
| 270 |
|
| 271 |
def _prepare_gmc_image_links(self, product, base_url): |
| 272 |
"""Prepare the product image links for Google Merchant Center. |
| 273 |
|
| 274 |
:return: The main product image link, and the extra images. No videos. |
| 275 |
:rtype: dict |
| 276 |
""" |
| 277 |
return { |
| 278 |
|
| 279 |
'image_link': ( |
| 280 |
urls.urljoin(base_url, product._get_image_1920_url()) if product.image_128 else '' |
| 281 |
), |
| 282 |
|
| 283 |
'additional_image_link': [ |
| 284 |
urls.urljoin(base_url, url) for url in product._get_extra_image_1920_urls()[:10] |
| 285 |
], |
| 286 |
} |
| 287 |
|
| 288 |
def _prepare_gmc_price_info(self, product): |
| 289 |
"""Prepare price-related information for Google Merchant Center. |
| 290 |
|
| 291 |
Note: If the product is flagged to prevent zero price sales, an empty dictionary is |
| 292 |
returned. |
| 293 |
|
| 294 |
:return: A dictionary containing nothing if the product is "prevent zero price sale", or: |
| 295 |
- List price, |
| 296 |
- Sale price (if applicable), and |
| 297 |
- Comparison prices (e.g., $100 / ml) if "Product Reference Price" is enabled. |
| 298 |
:rtype: dict |
| 299 |
""" |
| 300 |
price_context = product._get_product_price_context( |
| 301 |
product.product_template_attribute_value_ids |
| 302 |
) |
| 303 |
combination_info = product.with_context( |
| 304 |
**price_context, |
| 305 |
).product_tmpl_id._get_additionnal_combination_info( |
| 306 |
product, |
| 307 |
quantity=1.0, |
| 308 |
uom=product.uom_id, |
| 309 |
date=fields.Date.context_today(self), |
| 310 |
website=self.website_id, |
| 311 |
) |
| 312 |
if combination_info['prevent_zero_price_sale']: |
| 313 |
return {} |
| 314 |
|
| 315 |
price_info = { |
| 316 |
'price': utils.gmc_format_price( |
| 317 |
combination_info['list_price'], combination_info['currency'], |
| 318 |
), |
| 319 |
} |
| 320 |
|
| 321 |
if combination_info['has_discounted_price']: |
| 322 |
price_info['sale_price'] = utils.gmc_format_price( |
| 323 |
combination_info['price'], combination_info['currency'], |
| 324 |
) |
| 325 |
start_date = combination_info['discount_start_date'] |
| 326 |
end_date = combination_info['discount_end_date'] |
| 327 |
if start_date and end_date: |
| 328 |
price_info['sale_price_effective_date'] = '/'.join( |
| 329 |
map(utils.gmc_format_date, (start_date, end_date)), |
| 330 |
) |
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
if ( |
| 340 |
combination_info.get('base_unit_name') |
| 341 |
and product.base_unit_count |
| 342 |
and (match := const.GMC_BASE_MEASURE.match( |
| 343 |
combination_info['base_unit_name'].strip().lower() |
| 344 |
)) |
| 345 |
): |
| 346 |
base_count, base_unit = match['base_count'] or '1', match['base_unit'] |
| 347 |
count = product.base_unit_count * int(base_count) |
| 348 |
if ( |
| 349 |
base_unit in const.GMC_SUPPORTED_UOM |
| 350 |
and not float_is_zero(count, precision_digits=2) |
| 351 |
): |
| 352 |
price_info['unit_pricing_measure'] = ( |
| 353 |
f'{float_round(count, precision_digits=2)}{base_unit}' |
| 354 |
) |
| 355 |
price_info['unit_pricing_base_measure'] = f'{base_count}{base_unit}' |
| 356 |
|
| 357 |
return price_info |
| 358 |
|
| 359 |
def _prepare_gmc_stock_info(self, _product): |
| 360 |
"""Intended to be overridden in stock.""" |
| 361 |
return {'availability': 'in_stock'} |
| 362 |
|
| 363 |
def _prepare_gmc_additional_info(self, product): |
| 364 |
additional_info = { |
| 365 |
'product_detail': [ |
| 366 |
(attr.attribute_id.name, attr.name) |
| 367 |
for attr in product.product_template_attribute_value_ids |
| 368 |
], |
| 369 |
'is_bundle': 'yes' if product.type == 'combo' else 'no', |
| 370 |
'product_type': [ |
| 371 |
category.replace('/', '>') |
| 372 |
for category in ( |
| 373 |
|
| 374 |
product.public_categ_ids.sorted('sequence').mapped('display_name')[:5] |
| 375 |
) |
| 376 |
], |
| 377 |
'custom_label': [ |
| 378 |
(f'custom_label_{i}', tag_name) |
| 379 |
for i, tag_name in enumerate( |
| 380 |
|
| 381 |
product.all_product_tag_ids.sorted('sequence').mapped('name')[:5] |
| 382 |
) |
| 383 |
], |
| 384 |
} |
| 385 |
|
| 386 |
|
| 387 |
if len(product.product_tmpl_id.product_variant_ids) > 1: |
| 388 |
additional_info['item_group_id'] = product.product_tmpl_id.id |
| 389 |
|
| 390 |
return additional_info |
| 391 |
|
| 392 |
def _notify_website_manager(self, **kwargs): |
| 393 |
"""Send a notification to the website manager using OdooBot. |
| 394 |
|
| 395 |
This method wraps around `message_notify` to notify the manager of the feed's website. |
| 396 |
|
| 397 |
:param dict kwargs: Additional arguments passed to `message_notify`. |
| 398 |
:return: The created `mail.message` record. |
| 399 |
:rtype: mail.message |
| 400 |
""" |
| 401 |
return self.with_user(SUPERUSER_ID).message_notify( |
| 402 |
partner_ids=self.website_id.salesperson_id.partner_id.ids, **kwargs |
| 403 |
) |