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.

243 lines
9.7 KiB

  1. # Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
  2. # Copyright 2017 Pedro M. Baeza <pedro.baeza@tecnativa.com>
  3. # License LGPL-3 - See http://www.gnu.org/licenses/lgpl-3.0.html
  4. from odoo import _, api, fields, models, SUPERUSER_ID
  5. from odoo.exceptions import ValidationError
  6. from odoo.tools.safe_eval import safe_eval
  7. class CustomInfoValue(models.Model):
  8. _description = "Custom information value"
  9. _name = "custom.info.value"
  10. _rec_name = 'value'
  11. _order = ("model, res_id, category_sequence, category_id, "
  12. "property_sequence, property_id")
  13. _sql_constraints = [
  14. ("property_owner",
  15. "UNIQUE (property_id, model, res_id)",
  16. "Another property with that name exists for that resource."),
  17. ]
  18. model = fields.Char(
  19. related="property_id.model", index=True, readonly=True,
  20. auto_join=True, store=True,
  21. )
  22. owner_id = fields.Reference(
  23. selection="_selection_owner_id", string="Owner",
  24. compute="_compute_owner_id", inverse="_inverse_owner_id",
  25. help="Record that owns this custom value.",
  26. )
  27. res_id = fields.Integer(
  28. string="Resource ID", required=True, index=True, store=True,
  29. ondelete="cascade",
  30. )
  31. property_id = fields.Many2one(
  32. comodel_name='custom.info.property', required=True, string='Property',
  33. readonly=True,
  34. )
  35. property_sequence = fields.Integer(
  36. related="property_id.sequence", store=True, index=True, readonly=True,
  37. )
  38. category_sequence = fields.Integer(
  39. string="Category Sequence",
  40. related="property_id.category_id.sequence", store=True, readonly=True,
  41. )
  42. category_id = fields.Many2one(
  43. related="property_id.category_id", store=True, readonly=True,
  44. )
  45. name = fields.Char(related='property_id.name', readonly=True)
  46. field_type = fields.Selection(
  47. related="property_id.field_type", readonly=True,
  48. )
  49. field_name = fields.Char(
  50. compute="_compute_field_name",
  51. help="Technical name of the field where the value is stored.",
  52. )
  53. required = fields.Boolean(related="property_id.required", readonly=True)
  54. value = fields.Char(
  55. compute="_compute_value", inverse="_inverse_value",
  56. search="_search_value",
  57. help="Value, always converted to/from the typed field.",
  58. )
  59. value_str = fields.Char(string="Text value", translate=True, index=True)
  60. value_int = fields.Integer(string="Whole number value", index=True)
  61. value_float = fields.Float(string="Decimal number value", index=True)
  62. value_bool = fields.Boolean(string="Yes/No value", index=True)
  63. value_id = fields.Many2one(
  64. comodel_name="custom.info.option", string="Selection value",
  65. ondelete="cascade", domain="[('property_ids', '=', property_id)]",
  66. )
  67. @api.multi
  68. def check_access_rule(self, operation):
  69. """You access a value if you access its owner record."""
  70. if self.env.uid != SUPERUSER_ID:
  71. for record in self.filtered('owner_id'):
  72. record.owner_id.check_access_rights(operation)
  73. record.owner_id.check_access_rule(operation)
  74. return super().check_access_rule(operation)
  75. @api.model
  76. def _selection_owner_id(self):
  77. """You can choose among models linked to a template."""
  78. models = self.env["ir.model.fields"].search([
  79. ("ttype", "=", "many2one"),
  80. ("relation", "=", "custom.info.template"),
  81. ("model_id.transient", "=", False),
  82. "!", ("model", "=like", "custom.info.%"),
  83. ]).mapped("model_id")
  84. models = models.search([("id", "in", models.ids)], order="name")
  85. return [(m.model, m.name) for m in models
  86. if m.model in self.env and self.env[m.model]._auto]
  87. @api.multi
  88. @api.depends("property_id.field_type")
  89. def _compute_field_name(self):
  90. """Get the technical name where the real typed value is stored."""
  91. for s in self:
  92. s.field_name = "value_{!s}".format(s.property_id.field_type)
  93. @api.multi
  94. @api.depends("res_id", "model")
  95. def _compute_owner_id(self):
  96. """Get the id from the linked record."""
  97. for record in self:
  98. record.owner_id = "{},{}".format(record.model, record.res_id)
  99. @api.multi
  100. def _inverse_owner_id(self):
  101. """Store the owner according to the model and ID."""
  102. for record in self.filtered('owner_id'):
  103. record.model = record.owner_id._name
  104. record.res_id = record.owner_id.id
  105. @api.multi
  106. @api.depends("property_id.field_type", "field_name", "value_str",
  107. "value_int", "value_float", "value_bool", "value_id")
  108. def _compute_value(self):
  109. """Get the value as a string, from the original field."""
  110. for s in self:
  111. if s.field_type == "id":
  112. s.value = s.value_id.display_name
  113. elif s.field_type == "bool":
  114. s.value = _("Yes") if s.value_bool else _("No")
  115. else:
  116. s.value = getattr(s, s.field_name, False)
  117. @api.multi
  118. def _inverse_value(self):
  119. """Write the value correctly converted in the typed field."""
  120. for record in self:
  121. if (record.field_type == "id"
  122. and record.value == record.value_id.display_name):
  123. # Avoid another search that can return a different value
  124. continue
  125. record[record.field_name] = self._transform_value(
  126. record.value, record.field_type, record.property_id,
  127. )
  128. @api.one
  129. @api.constrains("property_id", "value_str", "value_int", "value_float")
  130. def _check_min_max_limits(self):
  131. """Ensure value falls inside the property's stablished limits."""
  132. minimum, maximum = self.property_id.minimum, self.property_id.maximum
  133. if minimum <= maximum:
  134. value = self[self.field_name]
  135. if not value:
  136. # This is a job for :meth:`.~_check_required`
  137. return
  138. if self.field_type == "str":
  139. number = len(self.value_str)
  140. message = _(
  141. "Length for %(prop)s is %(val)s, but it should be "
  142. "between %(min)d and %(max)d.")
  143. elif self.field_type in {"int", "float"}:
  144. number = value
  145. if self.field_type == "int":
  146. message = _(
  147. "Value for %(prop)s is %(val)s, but it should be "
  148. "between %(min)d and %(max)d.")
  149. else:
  150. message = _(
  151. "Value for %(prop)s is %(val)s, but it should be "
  152. "between %(min)f and %(max)f.")
  153. else:
  154. return
  155. if not minimum <= number <= maximum:
  156. raise ValidationError(message % {
  157. "prop": self.property_id.display_name,
  158. "val": number,
  159. "min": minimum,
  160. "max": maximum,
  161. })
  162. @api.multi
  163. @api.onchange("property_id")
  164. def _onchange_property_set_default_value(self):
  165. """Load default value for this property."""
  166. for record in self:
  167. if not record.value and record.property_id.default_value:
  168. record.value = record.property_id.default_value
  169. if not record.field_type and record.property_id.field_type:
  170. record.field_type = record.property_id.field_type
  171. @api.onchange('value')
  172. def _onchange_value(self):
  173. """Inverse function is not launched after writing, so we need to
  174. trigger it right now."""
  175. self._inverse_value()
  176. @api.model
  177. def _transform_value(self, value, format_, properties=None):
  178. """Transforms a text value to the expected format.
  179. :param str/bool value:
  180. Custom value in raw string.
  181. :param str format_:
  182. Target conversion format for the value. Must be available among
  183. ``custom.info.property`` options.
  184. :param recordset properties:
  185. Useful when :param:`format_` is ``id``, as it helps to ensure the
  186. option is available in these properties. If :param:`format_` is
  187. ``id`` and :param:`properties` is ``None``, no transformation will
  188. be made for :param:`value`.
  189. """
  190. if not value:
  191. value = False
  192. elif format_ == "id" and properties:
  193. value = self.env["custom.info.option"].search([
  194. ("property_ids", "in", properties.ids),
  195. ("name", "ilike", u"%{}%".format(value)),
  196. ], limit=1)
  197. elif format_ == "bool":
  198. value = value.strip().lower() not in {
  199. "0", "false", "", "no", "off", _("No").lower()}
  200. elif format_ not in {"str", "id"}:
  201. value = safe_eval("{!s}({!r})".format(format_, value))
  202. return value
  203. @api.model
  204. def _search_value(self, operator, value):
  205. """Search from the stored field directly."""
  206. options = (
  207. o[0] for o in
  208. self.property_id._fields["field_type"]
  209. .get_description(self.env)["selection"])
  210. domain = []
  211. for fmt in options:
  212. try:
  213. _value = (self._transform_value(value, fmt)
  214. if not isinstance(value, list) else
  215. [self._transform_value(v, fmt) for v in value])
  216. except ValueError:
  217. # If you are searching something that cannot be casted, then
  218. # your property is probably from another type
  219. continue
  220. domain += [
  221. "&",
  222. ("field_type", "=", fmt),
  223. ("value_" + fmt, operator, _value),
  224. ]
  225. return ["|"] * int(len(domain) / 3 - 1) + domain