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.

217 lines
7.9 KiB

6 years ago
  1. # Copyright 2013 Nicolas Bessi (Camptocamp SA)
  2. # Copyright 2014 Agile Business Group (<http://www.agilebg.com>)
  3. # Copyright 2015 Grupo ESOC (<http://www.grupoesoc.es>)
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  5. import logging
  6. from odoo import api, fields, models
  7. from .. import exceptions
  8. _logger = logging.getLogger(__name__)
  9. class ResPartner(models.Model):
  10. """Adds last name and first name; name becomes a stored function field."""
  11. _inherit = "res.partner"
  12. firstname = fields.Char("First name", index=True)
  13. lastname = fields.Char("Last name", index=True)
  14. name = fields.Char(
  15. compute="_compute_name",
  16. inverse="_inverse_name_after_cleaning_whitespace",
  17. required=False,
  18. store=True,
  19. readonly=False,
  20. )
  21. @api.model
  22. def create(self, vals):
  23. """Add inverted names at creation if unavailable."""
  24. context = dict(self.env.context)
  25. name = vals.get("name", context.get("default_name"))
  26. if name is not None:
  27. # Calculate the splitted fields
  28. inverted = self._get_inverse_name(
  29. self._get_whitespace_cleaned_name(name),
  30. vals.get("is_company", self.default_get(["is_company"])["is_company"]),
  31. )
  32. for key, value in inverted.items():
  33. if not vals.get(key) or context.get("copy"):
  34. vals[key] = value
  35. # Remove the combined fields
  36. if "name" in vals:
  37. del vals["name"]
  38. if "default_name" in context:
  39. del context["default_name"]
  40. return super(ResPartner, self.with_context(context)).create(vals)
  41. def copy(self, default=None):
  42. """Ensure partners are copied right.
  43. Odoo adds ``(copy)`` to the end of :attr:`~.name`, but that would get
  44. ignored in :meth:`~.create` because it also copies explicitly firstname
  45. and lastname fields.
  46. """
  47. return super(ResPartner, self.with_context(copy=True)).copy(default)
  48. @api.model
  49. def default_get(self, fields_list):
  50. """Invert name when getting default values."""
  51. result = super(ResPartner, self).default_get(fields_list)
  52. inverted = self._get_inverse_name(
  53. self._get_whitespace_cleaned_name(result.get("name", "")),
  54. result.get("is_company", False),
  55. )
  56. for field in list(inverted.keys()):
  57. if field in fields_list:
  58. result[field] = inverted.get(field)
  59. return result
  60. @api.model
  61. def _names_order_default(self):
  62. return "first_last"
  63. @api.model
  64. def _get_names_order(self):
  65. """Get names order configuration from system parameters.
  66. You can override this method to read configuration from language,
  67. country, company or other"""
  68. return (
  69. self.env["ir.config_parameter"]
  70. .sudo()
  71. .get_param("partner_names_order", self._names_order_default())
  72. )
  73. @api.model
  74. def _get_computed_name(self, lastname, firstname):
  75. """Compute the 'name' field according to splitted data.
  76. You can override this method to change the order of lastname and
  77. firstname the computed name"""
  78. order = self._get_names_order()
  79. if order == "last_first_comma":
  80. return ", ".join(p for p in (lastname, firstname) if p)
  81. elif order == "first_last":
  82. return " ".join(p for p in (firstname, lastname) if p)
  83. else:
  84. return " ".join(p for p in (lastname, firstname) if p)
  85. @api.depends("firstname", "lastname")
  86. def _compute_name(self):
  87. """Write the 'name' field according to splitted data."""
  88. for record in self:
  89. record.name = record._get_computed_name(record.lastname, record.firstname)
  90. def _inverse_name_after_cleaning_whitespace(self):
  91. """Clean whitespace in :attr:`~.name` and split it.
  92. The splitting logic is stored separately in :meth:`~._inverse_name`, so
  93. submodules can extend that method and get whitespace cleaning for free.
  94. """
  95. for record in self:
  96. # Remove unneeded whitespace
  97. clean = record._get_whitespace_cleaned_name(record.name)
  98. record.name = clean
  99. record._inverse_name()
  100. @api.model
  101. def _get_whitespace_cleaned_name(self, name, comma=False):
  102. """Remove redundant whitespace from :param:`name`.
  103. Removes leading, trailing and duplicated whitespace.
  104. """
  105. try:
  106. name = " ".join(name.split()) if name else name
  107. except UnicodeDecodeError:
  108. # with users coming from LDAP, name can be a str encoded as utf-8
  109. # this happens with ActiveDirectory for instance, and in that case
  110. # we get a UnicodeDecodeError during the automatic ASCII -> Unicode
  111. # conversion that Python does for us.
  112. # In that case we need to manually decode the string to get a
  113. # proper unicode string.
  114. name = " ".join(name.decode("utf-8").split()) if name else name
  115. if comma:
  116. name = name.replace(" ,", ",")
  117. name = name.replace(", ", ",")
  118. return name
  119. @api.model
  120. def _get_inverse_name(self, name, is_company=False):
  121. """Compute the inverted name.
  122. - If the partner is a company, save it in the lastname.
  123. - Otherwise, make a guess.
  124. This method can be easily overriden by other submodules.
  125. You can also override this method to change the order of name's
  126. attributes
  127. When this method is called, :attr:`~.name` already has unified and
  128. trimmed whitespace.
  129. """
  130. # Company name goes to the lastname
  131. if is_company or not name:
  132. parts = [name or False, False]
  133. # Guess name splitting
  134. else:
  135. order = self._get_names_order()
  136. # Remove redundant spaces
  137. name = self._get_whitespace_cleaned_name(
  138. name, comma=(order == "last_first_comma")
  139. )
  140. parts = name.split("," if order == "last_first_comma" else " ", 1)
  141. if len(parts) > 1:
  142. if order == "first_last":
  143. parts = [" ".join(parts[1:]), parts[0]]
  144. else:
  145. parts = [parts[0], " ".join(parts[1:])]
  146. else:
  147. while len(parts) < 2:
  148. parts.append(False)
  149. return {"lastname": parts[0], "firstname": parts[1]}
  150. def _inverse_name(self):
  151. """Try to revert the effect of :meth:`._compute_name`."""
  152. for record in self:
  153. parts = record._get_inverse_name(record.name, record.is_company)
  154. record.lastname = parts["lastname"]
  155. record.firstname = parts["firstname"]
  156. @api.constrains("firstname", "lastname")
  157. def _check_name(self):
  158. """Ensure at least one name is set."""
  159. for record in self:
  160. if all(
  161. (
  162. record.type == "contact" or record.is_company,
  163. not (record.firstname or record.lastname),
  164. )
  165. ):
  166. raise exceptions.EmptyNamesError(record)
  167. @api.model
  168. def _install_partner_firstname(self):
  169. """Save names correctly in the database.
  170. Before installing the module, field ``name`` contains all full names.
  171. When installing it, this method parses those names and saves them
  172. correctly into the database. This can be called later too if needed.
  173. """
  174. # Find records with empty firstname and lastname
  175. records = self.search([("firstname", "=", False), ("lastname", "=", False)])
  176. # Force calculations there
  177. records._inverse_name()
  178. _logger.info("%d partners updated installing module.", len(records))
  179. # Disabling SQL constraint givint a more explicit error using a Python
  180. # contstraint
  181. _sql_constraints = [("check_name", "CHECK( 1=1 )", "Contacts require a name.")]