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.

222 lines
8.1 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. if isinstance(name, bytes):
  106. # With users coming from LDAP, name can be a byte encoded string.
  107. # This happens with FreeIPA for instance.
  108. name = name.decode("utf-8")
  109. try:
  110. name = " ".join(name.split()) if name else name
  111. except UnicodeDecodeError:
  112. # with users coming from LDAP, name can be a str encoded as utf-8
  113. # this happens with ActiveDirectory for instance, and in that case
  114. # we get a UnicodeDecodeError during the automatic ASCII -> Unicode
  115. # conversion that Python does for us.
  116. # In that case we need to manually decode the string to get a
  117. # proper unicode string.
  118. name = " ".join(name.decode("utf-8").split()) if name else name
  119. if comma:
  120. name = name.replace(" ,", ",")
  121. name = name.replace(", ", ",")
  122. return name
  123. @api.model
  124. def _get_inverse_name(self, name, is_company=False):
  125. """Compute the inverted name.
  126. - If the partner is a company, save it in the lastname.
  127. - Otherwise, make a guess.
  128. This method can be easily overriden by other submodules.
  129. You can also override this method to change the order of name's
  130. attributes
  131. When this method is called, :attr:`~.name` already has unified and
  132. trimmed whitespace.
  133. """
  134. # Company name goes to the lastname
  135. if is_company or not name:
  136. parts = [name or False, False]
  137. # Guess name splitting
  138. else:
  139. order = self._get_names_order()
  140. # Remove redundant spaces
  141. name = self._get_whitespace_cleaned_name(
  142. name, comma=(order == "last_first_comma")
  143. )
  144. parts = name.split("," if order == "last_first_comma" else " ", 1)
  145. if len(parts) > 1:
  146. if order == "first_last":
  147. parts = [" ".join(parts[1:]), parts[0]]
  148. else:
  149. parts = [parts[0], " ".join(parts[1:])]
  150. else:
  151. while len(parts) < 2:
  152. parts.append(False)
  153. return {"lastname": parts[0], "firstname": parts[1]}
  154. def _inverse_name(self):
  155. """Try to revert the effect of :meth:`._compute_name`."""
  156. for record in self:
  157. parts = record._get_inverse_name(record.name, record.is_company)
  158. record.lastname = parts["lastname"]
  159. record.firstname = parts["firstname"]
  160. @api.constrains("firstname", "lastname")
  161. def _check_name(self):
  162. """Ensure at least one name is set."""
  163. for record in self:
  164. if all(
  165. (
  166. record.type == "contact" or record.is_company,
  167. not (record.firstname or record.lastname),
  168. )
  169. ):
  170. raise exceptions.EmptyNamesError(record)
  171. @api.model
  172. def _install_partner_firstname(self):
  173. """Save names correctly in the database.
  174. Before installing the module, field ``name`` contains all full names.
  175. When installing it, this method parses those names and saves them
  176. correctly into the database. This can be called later too if needed.
  177. """
  178. # Find records with empty firstname and lastname
  179. records = self.search([("firstname", "=", False), ("lastname", "=", False)])
  180. # Force calculations there
  181. records._inverse_name()
  182. _logger.info("%d partners updated installing module.", len(records))
  183. # Disabling SQL constraint givint a more explicit error using a Python
  184. # contstraint
  185. _sql_constraints = [("check_name", "CHECK( 1=1 )", "Contacts require a name.")]