You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.3 KiB

  1. # Copyright 2019 Camptocamp SA
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
  3. from odoo import fields, models
  4. from odoo.tools.safe_eval import safe_eval
  5. class AbstractConditionalImage(models.AbstractModel):
  6. _name = 'abstract.conditional.image'
  7. image = fields.Binary(
  8. compute='_compute_image', string="Image",
  9. store=False, readonly=True
  10. )
  11. image_medium = fields.Binary(
  12. compute='_compute_image', string="Image",
  13. store=False, readonly=True
  14. )
  15. image_small = fields.Binary(
  16. compute='_compute_image', string="Image",
  17. store=False, readonly=True
  18. )
  19. @staticmethod
  20. def _compute_selector_test_without_company(image_selector, record):
  21. return bool(
  22. safe_eval(image_selector.selector or "True", {'object': record})
  23. )
  24. @staticmethod
  25. def _compute_selector_test_with_company(image_selector, record):
  26. if (image_selector.company_id == record.company_id or
  27. record.company_id and not image_selector.company_id):
  28. return AbstractConditionalImage\
  29. ._compute_selector_test_without_company(
  30. image_selector, record
  31. )
  32. return False
  33. def _compute_image(self):
  34. if 'company_id' in self._fields:
  35. search_clause = [('model_name', '=', self._name)]
  36. test_method = self._compute_selector_test_with_company
  37. else:
  38. # If inherited object doesn't have a `company_id` field,
  39. # remove the items with a company defined and the related checks
  40. search_clause = [('model_name', '=', self._name),
  41. ('company_id', '=', False)]
  42. test_method = self._compute_selector_test_without_company
  43. image_selectors = self.env['image'].search(
  44. search_clause, order='company_id, selector'
  45. )
  46. for rec in self:
  47. found = None
  48. for image_selector in image_selectors:
  49. if test_method(image_selector, rec):
  50. found = image_selector
  51. break
  52. rec.update({
  53. 'image': found and found.image,
  54. 'image_medium': found and found.image_medium,
  55. 'image_small': found and found.image_small,
  56. })