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.

174 lines
6.2 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
  3. # Copyright 2016 Tecnativa - Vicent Cubells
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  5. import logging
  6. from odoo import api, fields, models, tools
  7. _logger = logging.getLogger(__name__)
  8. class BaseImportMatch(models.Model):
  9. _name = "base_import.match"
  10. _description = "Deduplicate settings prior to CSV imports."
  11. _order = "sequence, name"
  12. name = fields.Char(
  13. compute="_compute_name",
  14. store=True,
  15. index=True)
  16. sequence = fields.Integer(index=True)
  17. model_id = fields.Many2one(
  18. "ir.model",
  19. "Model",
  20. required=True,
  21. ondelete="cascade",
  22. domain=[("transient", "=", False)],
  23. help="In this model you will apply the match.")
  24. model_name = fields.Char(
  25. related="model_id.model",
  26. store=True,
  27. index=True)
  28. field_ids = fields.One2many(
  29. comodel_name="base_import.match.field",
  30. inverse_name="match_id",
  31. string="Fields",
  32. required=True,
  33. help="Fields that will define an unique key.")
  34. @api.onchange("model_id")
  35. def _onchange_model_id(self):
  36. self.field_ids = False
  37. @api.depends("model_id", "field_ids")
  38. def _compute_name(self):
  39. """Automatic self-descriptive name for the setting records."""
  40. for one in self:
  41. one.name = u"{}: {}".format(
  42. one.model_id.display_name,
  43. " + ".join(one.field_ids.mapped("display_name")),
  44. )
  45. @api.model
  46. def _match_find(self, model, converted_row, imported_row):
  47. """Find a update target for the given row.
  48. This will traverse by order all match rules that can be used with the
  49. imported data, and return a match for the first rule that returns a
  50. single result.
  51. :param odoo.models.Model model:
  52. Model object that is being imported.
  53. :param dict converted_row:
  54. Row converted to Odoo api format, like the 3rd value that
  55. :meth:`odoo.models.Model._convert_records` returns.
  56. :param dict imported_row:
  57. Row as it is being imported, in format::
  58. {
  59. "field_name": "string value",
  60. "other_field": "True",
  61. ...
  62. }
  63. :return odoo.models.Model:
  64. Return a dataset with one single match if it was found, or an
  65. empty dataset if none or multiple matches were found.
  66. """
  67. # Get usable rules to perform matches
  68. usable = self._usable_rules(model._name, converted_row)
  69. # Traverse usable combinations
  70. for combination in usable:
  71. combination_valid = True
  72. domain = list()
  73. for field in combination.field_ids:
  74. # Check imported value if it is a conditional field
  75. if field.conditional:
  76. # Invalid combinations are skipped
  77. if imported_row[field.name] != field.imported_value:
  78. combination_valid = False
  79. break
  80. domain.append((field.name, "=", converted_row[field.name]))
  81. if not combination_valid:
  82. continue
  83. match = model.search(domain)
  84. # When a single match is found, stop searching
  85. if len(match) == 1:
  86. return match
  87. elif match:
  88. _logger.warning(
  89. "Found multiple matches for model %s and domain %s; "
  90. "falling back to default behavior (create new record)",
  91. model._name,
  92. domain,
  93. )
  94. # Return an empty match if none or multiple was found
  95. return model
  96. @api.model
  97. @tools.ormcache("model_name", "fields")
  98. def _usable_rules(self, model_name, fields):
  99. """Return a set of elements usable for calling ``load()``.
  100. :param str model_name:
  101. Technical name of the model where you are loading data.
  102. E.g. ``res.partner``.
  103. :param list(str|bool) fields:
  104. List of field names being imported.
  105. :return bool:
  106. Indicates if we should patch its load method.
  107. """
  108. result = self
  109. available = self.search([("model_name", "=", model_name)])
  110. # Use only criteria with all required fields to match
  111. for record in available:
  112. if all(f.name in fields for f in record.field_ids):
  113. result |= record
  114. return result
  115. class BaseImportMatchField(models.Model):
  116. _name = "base_import.match.field"
  117. _description = "Field import match definition"
  118. name = fields.Char(
  119. related="field_id.name")
  120. field_id = fields.Many2one(
  121. comodel_name="ir.model.fields",
  122. string="Field",
  123. required=True,
  124. ondelete="cascade",
  125. domain="[('model_id', '=', model_id)]",
  126. help="Field that will be part of an unique key.")
  127. match_id = fields.Many2one(
  128. comodel_name="base_import.match",
  129. string="Match",
  130. ondelete="cascade",
  131. required=True)
  132. model_id = fields.Many2one(
  133. related="match_id.model_id")
  134. conditional = fields.Boolean(
  135. help="Enable if you want to use this field only in some conditions.")
  136. imported_value = fields.Char(
  137. help="If the imported value is not this, the whole matching rule will "
  138. "be discarded. Be careful, this data is always treated as a "
  139. "string, and comparison is case-sensitive so if you set 'True', "
  140. "it will NOT match '1' nor 'true', only EXACTLY 'True'.")
  141. @api.depends("conditional", "field_id", "imported_value")
  142. def _compute_display_name(self):
  143. for one in self:
  144. pattern = u"{name} ({cond})" if one.conditional else u"{name}"
  145. one.display_name = pattern.format(
  146. name=one.field_id.name,
  147. cond=one.imported_value,
  148. )
  149. @api.onchange("field_id", "match_id", "conditional", "imported_value")
  150. def _onchange_match_id_name(self):
  151. """Update match name."""
  152. self.mapped("match_id")._compute_name()