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.

242 lines
8.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. )
  20. @api.model
  21. def create(self, vals):
  22. """Add inverted names at creation if unavailable."""
  23. context = dict(self.env.context)
  24. name = vals.get("name", context.get("default_name"))
  25. if name is not None:
  26. # Calculate the splitted fields
  27. inverted = self._get_inverse_name(
  28. self._get_whitespace_cleaned_name(name),
  29. vals.get("is_company", self.default_get(["is_company"])["is_company"]),
  30. )
  31. for key, value in inverted.items():
  32. if not vals.get(key) or context.get("copy"):
  33. vals[key] = value
  34. # Remove the combined fields
  35. if "name" in vals:
  36. del vals["name"]
  37. if "default_name" in context:
  38. del context["default_name"]
  39. return super(ResPartner, self.with_context(context)).create(vals)
  40. def copy(self, default=None):
  41. """Ensure partners are copied right.
  42. Odoo adds ``(copy)`` to the end of :attr:`~.name`, but that would get
  43. ignored in :meth:`~.create` because it also copies explicitly firstname
  44. and lastname fields.
  45. """
  46. return super(ResPartner, self.with_context(copy=True)).copy(default)
  47. @api.model
  48. def default_get(self, fields_list):
  49. """Invert name when getting default values."""
  50. result = super(ResPartner, self).default_get(fields_list)
  51. inverted = self._get_inverse_name(
  52. self._get_whitespace_cleaned_name(result.get("name", "")),
  53. result.get("is_company", False),
  54. )
  55. for field in list(inverted.keys()):
  56. if field in fields_list:
  57. result[field] = inverted.get(field)
  58. return result
  59. @api.model
  60. def _names_order_default(self):
  61. return "first_last"
  62. @api.model
  63. def _get_names_order(self):
  64. """Get names order configuration from system parameters.
  65. You can override this method to read configuration from language,
  66. country, company or other"""
  67. return (
  68. self.env["ir.config_parameter"]
  69. .sudo()
  70. .get_param("partner_names_order", self._names_order_default())
  71. )
  72. @api.model
  73. def _get_computed_name(self, lastname, firstname):
  74. """Compute the 'name' field according to splitted data.
  75. You can override this method to change the order of lastname and
  76. firstname the computed name"""
  77. order = self._get_names_order()
  78. if order == "last_first_comma":
  79. return ", ".join(p for p in (lastname, firstname) if p)
  80. elif order == "first_last":
  81. return " ".join(p for p in (firstname, lastname) if p)
  82. else:
  83. return " ".join(p for p in (lastname, firstname) if p)
  84. @api.depends("firstname", "lastname")
  85. def _compute_name(self):
  86. """Write the 'name' field according to splitted data."""
  87. for record in self:
  88. record.name = record._get_computed_name(record.lastname, record.firstname)
  89. def _inverse_name_after_cleaning_whitespace(self):
  90. """Clean whitespace in :attr:`~.name` and split it.
  91. The splitting logic is stored separately in :meth:`~._inverse_name`, so
  92. submodules can extend that method and get whitespace cleaning for free.
  93. """
  94. for record in self:
  95. # Remove unneeded whitespace
  96. clean = record._get_whitespace_cleaned_name(record.name)
  97. # Clean name avoiding infinite recursion
  98. if record.name != clean:
  99. record.name = clean
  100. # Save name in the real fields
  101. else:
  102. record._inverse_name()
  103. @api.model
  104. def _get_whitespace_cleaned_name(self, name, comma=False):
  105. """Remove redundant whitespace from :param:`name`.
  106. Removes leading, trailing and duplicated whitespace.
  107. """
  108. try:
  109. name = " ".join(name.split()) if name else name
  110. except UnicodeDecodeError:
  111. # with users coming from LDAP, name can be a str encoded as utf-8
  112. # this happens with ActiveDirectory for instance, and in that case
  113. # we get a UnicodeDecodeError during the automatic ASCII -> Unicode
  114. # conversion that Python does for us.
  115. # In that case we need to manually decode the string to get a
  116. # proper unicode string.
  117. name = " ".join(name.decode("utf-8").split()) if name else name
  118. if comma:
  119. name = name.replace(" ,", ",")
  120. name = name.replace(", ", ",")
  121. return name
  122. @api.model
  123. def _get_inverse_name(self, name, is_company=False):
  124. """Compute the inverted name.
  125. - If the partner is a company, save it in the lastname.
  126. - Otherwise, make a guess.
  127. This method can be easily overriden by other submodules.
  128. You can also override this method to change the order of name's
  129. attributes
  130. When this method is called, :attr:`~.name` already has unified and
  131. trimmed whitespace.
  132. """
  133. # Company name goes to the lastname
  134. if is_company or not name:
  135. parts = [name or False, False]
  136. # Guess name splitting
  137. else:
  138. order = self._get_names_order()
  139. # Remove redundant spaces
  140. name = self._get_whitespace_cleaned_name(
  141. name, comma=(order == "last_first_comma")
  142. )
  143. parts = name.split("," if order == "last_first_comma" else " ", 1)
  144. if len(parts) > 1:
  145. if order == "first_last":
  146. parts = [" ".join(parts[1:]), parts[0]]
  147. else:
  148. parts = [parts[0], " ".join(parts[1:])]
  149. else:
  150. while len(parts) < 2:
  151. parts.append(False)
  152. return {"lastname": parts[0], "firstname": parts[1]}
  153. def _inverse_name(self):
  154. """Try to revert the effect of :meth:`._compute_name`."""
  155. for record in self:
  156. parts = record._get_inverse_name(record.name, record.is_company)
  157. record.lastname = parts["lastname"]
  158. record.firstname = parts["firstname"]
  159. @api.constrains("firstname", "lastname")
  160. def _check_name(self):
  161. """Ensure at least one name is set."""
  162. for record in self:
  163. if all(
  164. (
  165. record.type == "contact" or record.is_company,
  166. not (record.firstname or record.lastname),
  167. )
  168. ):
  169. raise exceptions.EmptyNamesError(record)
  170. @api.onchange("firstname", "lastname")
  171. def _onchange_subnames(self):
  172. """Avoid recursion when the user changes one of these fields.
  173. This forces to skip the :attr:`~.name` inversion when the user is
  174. setting it in a not-inverted way.
  175. """
  176. # Modify self's context without creating a new Environment.
  177. # See https://github.com/odoo/odoo/issues/7472#issuecomment-119503916.
  178. self.env.context = self.with_context(skip_onchange=True).env.context
  179. @api.onchange("name")
  180. def _onchange_name(self):
  181. """Ensure :attr:`~.name` is inverted in the UI."""
  182. if self.env.context.get("skip_onchange"):
  183. # Do not skip next onchange
  184. self.env.context = self.with_context(skip_onchange=False).env.context
  185. else:
  186. self._inverse_name_after_cleaning_whitespace()
  187. @api.model
  188. def _install_partner_firstname(self):
  189. """Save names correctly in the database.
  190. Before installing the module, field ``name`` contains all full names.
  191. When installing it, this method parses those names and saves them
  192. correctly into the database. This can be called later too if needed.
  193. """
  194. # Find records with empty firstname and lastname
  195. records = self.search([("firstname", "=", False), ("lastname", "=", False)])
  196. # Force calculations there
  197. records._inverse_name()
  198. _logger.info("%d partners updated installing module.", len(records))
  199. # Disabling SQL constraint givint a more explicit error using a Python
  200. # contstraint
  201. _sql_constraints = [("check_name", "CHECK( 1=1 )", "Contacts require a name.")]