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.

241 lines
9.6 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
  3. # Copyright 2017 Pedro M. Baeza <pedro.baeza@tecnativa.com>
  4. # License LGPL-3 - See http://www.gnu.org/licenses/lgpl-3.0.html
  5. from openerp import _, api, fields, models, SUPERUSER_ID
  6. from openerp.exceptions import ValidationError
  7. from openerp.tools.safe_eval import safe_eval
  8. class CustomInfoValue(models.Model):
  9. _description = "Custom information value"
  10. _name = "custom.info.value"
  11. _rec_name = 'value'
  12. _order = ("model, res_id, category_sequence, category_id, "
  13. "property_sequence, property_id")
  14. _sql_constraints = [
  15. ("property_owner",
  16. "UNIQUE (property_id, model, res_id)",
  17. "Another property with that name exists for that resource."),
  18. ]
  19. model = fields.Char(
  20. related="property_id.model", index=True, readonly=True,
  21. auto_join=True, store=True,
  22. )
  23. owner_id = fields.Reference(
  24. selection="_selection_owner_id", string="Owner",
  25. compute="_compute_owner_id", inverse="_inverse_owner_id",
  26. help="Record that owns this custom value.",
  27. )
  28. res_id = fields.Integer(
  29. string="Resource ID", required=True, index=True, store=True,
  30. ondelete="cascade",
  31. )
  32. property_id = fields.Many2one(
  33. comodel_name='custom.info.property', required=True, string='Property',
  34. readonly=True,
  35. )
  36. property_sequence = fields.Integer(
  37. related="property_id.sequence", store=True, index=True, readonly=True,
  38. )
  39. category_sequence = fields.Integer(
  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', 'in', [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(CustomInfoValue, self).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" and
  122. 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. @api.onchange('value')
  170. def _onchange_value(self):
  171. """Inverse function is not launched after writing, so we need to
  172. trigger it right now."""
  173. self._inverse_value()
  174. @api.model
  175. def _transform_value(self, value, format_, properties=None):
  176. """Transforms a text value to the expected format.
  177. :param str/bool value:
  178. Custom value in raw string.
  179. :param str format_:
  180. Target conversion format for the value. Must be available among
  181. ``custom.info.property`` options.
  182. :param recordset properties:
  183. Useful when :param:`format_` is ``id``, as it helps to ensure the
  184. option is available in these properties. If :param:`format_` is
  185. ``id`` and :param:`properties` is ``None``, no transformation will
  186. be made for :param:`value`.
  187. """
  188. if not value:
  189. value = False
  190. elif format_ == "id" and properties:
  191. value = self.env["custom.info.option"].search([
  192. ("property_ids", "in", properties.ids),
  193. ("name", "ilike", u"%{}%".format(value)),
  194. ], limit=1)
  195. elif format_ == "bool":
  196. value = value.strip().lower() not in {
  197. "0", "false", "", "no", "off", _("No").lower()}
  198. elif format_ not in {"str", "id"}:
  199. value = safe_eval("{!s}({!r})".format(format_, value))
  200. return value
  201. @api.model
  202. def _search_value(self, operator, value):
  203. """Search from the stored field directly."""
  204. options = (
  205. o[0] for o in
  206. self.property_id._fields["field_type"]
  207. .get_description(self.env)["selection"])
  208. domain = []
  209. for fmt in options:
  210. try:
  211. _value = (self._transform_value(value, fmt)
  212. if not isinstance(value, list) else
  213. [self._transform_value(v, fmt) for v in value])
  214. except ValueError:
  215. # If you are searching something that cannot be casted, then
  216. # your property is probably from another type
  217. continue
  218. domain += [
  219. "&",
  220. ("field_type", "=", fmt),
  221. ("value_" + fmt, operator, _value),
  222. ]
  223. return ["|"] * (len(domain) / 3 - 1) + domain