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.

239 lines
9.6 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, compute_sudo=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. compute_sudo=True,
  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. )
  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. widget = fields.Selection(
  50. related="property_id.widget", readonly=True,
  51. )
  52. field_name = fields.Char(
  53. compute="_compute_field_name",
  54. help="Technical name of the field where the value is stored.",
  55. )
  56. required = fields.Boolean(related="property_id.required", readonly=True)
  57. value = fields.Char(
  58. compute="_compute_value",
  59. search="_search_value",
  60. help="Value, always converted to/from the typed field.",
  61. )
  62. value_str = fields.Char(string="Text value", translate=True, index=True)
  63. value_int = fields.Integer(string="Whole number value", index=True)
  64. value_float = fields.Float(string="Decimal number value", index=True)
  65. value_bool = fields.Boolean(string="Yes/No value", index=True)
  66. value_date = fields.Date(string="Date value", index=True)
  67. value_id = fields.Many2one(
  68. comodel_name="custom.info.option", string="Selection value",
  69. ondelete="cascade", domain="[('property_ids', '=', property_id)]",
  70. )
  71. @api.multi
  72. def check_access_rule(self, operation):
  73. """You access a value if you access its owner record."""
  74. if self.env.uid != SUPERUSER_ID:
  75. for record in self.filtered('owner_id'):
  76. record.owner_id.check_access_rights(operation)
  77. record.owner_id.check_access_rule(operation)
  78. return super().check_access_rule(operation)
  79. @api.model
  80. def _selection_owner_id(self):
  81. """You can choose among models linked to a template."""
  82. models = self.env["ir.model.fields"].search([
  83. ("ttype", "=", "many2one"),
  84. ("relation", "=", "custom.info.template"),
  85. ("model_id.transient", "=", False),
  86. "!", ("model", "=like", "custom.info.%"),
  87. ]).mapped("model_id")
  88. models = models.search([("id", "in", models.ids)], order="name")
  89. return [(m.model, m.name) for m in models
  90. if m.model in self.env and self.env[m.model]._auto]
  91. @api.multi
  92. @api.depends("property_id.field_type")
  93. def _compute_field_name(self):
  94. """Get the technical name where the real typed value is stored."""
  95. for s in self:
  96. s.field_name = "value_{!s}".format(s.property_id.field_type)
  97. @api.multi
  98. @api.depends("res_id", "model")
  99. def _compute_owner_id(self):
  100. """Get the id from the linked record."""
  101. for record in self:
  102. record.owner_id = "{},{}".format(record.model, record.res_id)
  103. @api.multi
  104. def _inverse_owner_id(self):
  105. """Store the owner according to the model and ID."""
  106. for record in self.filtered('owner_id'):
  107. record.model = record.owner_id._name
  108. record.res_id = record.owner_id.id
  109. @api.multi
  110. @api.depends("property_id.field_type", "field_name", "value_str",
  111. "value_int", "value_float", "value_bool", "value_id")
  112. def _compute_value(self):
  113. """Get the value as a string, from the original field."""
  114. for s in self:
  115. if s.field_type == "id":
  116. s.value = s.value_id.display_name
  117. elif s.field_type == "bool":
  118. s.value = _("Yes") if s.value_bool else _("No")
  119. else:
  120. s.value = getattr(s, s.field_name, False)
  121. @api.one
  122. @api.constrains("property_id", "value_str", "value_int", "value_float")
  123. def _check_min_max_limits(self):
  124. """Ensure value falls inside the property's stablished limits."""
  125. minimum, maximum = self.property_id.minimum, self.property_id.maximum
  126. if minimum <= maximum:
  127. value = self[self.field_name]
  128. if not value:
  129. # This is a job for :meth:`.~_check_required`
  130. return
  131. if self.field_type == "str":
  132. number = len(self.value_str)
  133. message = _(
  134. "Length for %(prop)s is %(val)s, but it should be "
  135. "between %(min)d and %(max)d.")
  136. elif self.field_type in {"int", "float"}:
  137. number = value
  138. if self.field_type == "int":
  139. message = _(
  140. "Value for %(prop)s is %(val)s, but it should be "
  141. "between %(min)d and %(max)d.")
  142. else:
  143. message = _(
  144. "Value for %(prop)s is %(val)s, but it should be "
  145. "between %(min)f and %(max)f.")
  146. else:
  147. return
  148. if not minimum <= number <= maximum:
  149. raise ValidationError(message % {
  150. "prop": self.property_id.display_name,
  151. "val": number,
  152. "min": minimum,
  153. "max": maximum,
  154. })
  155. @api.constrains('value_str', 'value_int', 'value_float', 'value_bool',
  156. 'value_date', 'value_id', 'property_id')
  157. def _check_required(self):
  158. for record in self:
  159. if not record.required:
  160. continue
  161. if not record.value:
  162. raise ValidationError(_(
  163. 'Some required elements have not been fulfilled'
  164. ))
  165. @api.onchange("property_id")
  166. def _onchange_property_set_default_value(self):
  167. """Load default value for this property."""
  168. for record in self:
  169. if not record.value and record.property_id.default_value:
  170. record.value = record.property_id.default_value
  171. if not record.field_type and record.property_id.field_type:
  172. record.field_type = record.property_id.field_type
  173. @api.model
  174. def _transform_value(self, value, format_, properties=None):
  175. """Transforms a text value to the expected format.
  176. :param str/bool value:
  177. Custom value in raw string.
  178. :param str format_:
  179. Target conversion format for the value. Must be available among
  180. ``custom.info.property`` options.
  181. :param recordset properties:
  182. Useful when :param:`format_` is ``id``, as it helps to ensure the
  183. option is available in these properties. If :param:`format_` is
  184. ``id`` and :param:`properties` is ``None``, no transformation will
  185. be made for :param:`value`.
  186. """
  187. if not value:
  188. value = False
  189. elif format_ == "id" and properties:
  190. value = self.env["custom.info.option"].search([
  191. ("property_ids", "in", properties.ids),
  192. ("name", "ilike", u"%{}%".format(value)),
  193. ], limit=1)
  194. elif format_ == "bool":
  195. value = value.strip().lower() not in {
  196. "0", "false", "", "no", "off", _("No").lower()}
  197. elif format_ not in {"str", "id"}:
  198. value = safe_eval("{!s}({!r})".format(format_, value))
  199. return value
  200. @api.model
  201. def _search_value(self, operator, value):
  202. """Search from the stored field directly."""
  203. options = (
  204. o[0] for o in
  205. self.property_id._fields["field_type"]
  206. .get_description(self.env)["selection"])
  207. domain = []
  208. for fmt in options:
  209. try:
  210. _value = (self._transform_value(value, fmt)
  211. if not isinstance(value, list) else
  212. [self._transform_value(v, fmt) for v in value])
  213. except ValueError:
  214. # If you are searching something that cannot be casted, then
  215. # your property is probably from another type
  216. continue
  217. domain += [
  218. "&",
  219. ("field_type", "=", fmt),
  220. ("value_" + fmt, operator, _value),
  221. ]
  222. return ["|"] * int(len(domain) / 3 - 1) + domain