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.

198 lines
6.9 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2013 Nicolas Bessi (Camptocamp SA)
  3. # © 2014 Agile Business Group (<http://www.agilebg.com>)
  4. # © 2015 Grupo ESOC (<http://www.grupoesoc.es>)
  5. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  6. import logging
  7. from openerp import api, fields, models
  8. from .. import exceptions
  9. _logger = logging.getLogger(__name__)
  10. class ResPartner(models.Model):
  11. """Adds last name and first name; name becomes a stored function field."""
  12. _inherit = 'res.partner'
  13. firstname = fields.Char("First name")
  14. lastname = fields.Char("Last name")
  15. name = fields.Char(
  16. compute="_compute_name",
  17. inverse="_inverse_name_after_cleaning_whitespace",
  18. required=False,
  19. store=True)
  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",
  30. self.default_get(["is_company"])["is_company"]))
  31. for key, value in inverted.iteritems():
  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. @api.multi
  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. for field in inverted.keys():
  56. if field in fields_list:
  57. result[field] = inverted.get(field)
  58. return result
  59. @api.model
  60. def _get_computed_name(self, lastname, firstname):
  61. """Compute the 'name' field according to splitted data.
  62. You can override this method to change the order of lastname and
  63. firstname the computed name"""
  64. return u" ".join((p for p in (lastname, firstname) if p))
  65. @api.one
  66. @api.depends("firstname", "lastname")
  67. def _compute_name(self):
  68. """Write the 'name' field according to splitted data."""
  69. self.name = self._get_computed_name(self.lastname, self.firstname)
  70. @api.one
  71. def _inverse_name_after_cleaning_whitespace(self):
  72. """Clean whitespace in :attr:`~.name` and split it.
  73. The splitting logic is stored separately in :meth:`~._inverse_name`, so
  74. submodules can extend that method and get whitespace cleaning for free.
  75. """
  76. # Remove unneeded whitespace
  77. clean = self._get_whitespace_cleaned_name(self.name)
  78. # Clean name avoiding infinite recursion
  79. if self.name != clean:
  80. self.name = clean
  81. # Save name in the real fields
  82. else:
  83. self._inverse_name()
  84. @api.model
  85. def _get_whitespace_cleaned_name(self, name):
  86. """Remove redundant whitespace from :param:`name`.
  87. Removes leading, trailing and duplicated whitespace.
  88. """
  89. return u" ".join(name.split(None)) if name else name
  90. @api.model
  91. def _get_inverse_name(self, name, is_company=False):
  92. """Compute the inverted name.
  93. - If the partner is a company, save it in the lastname.
  94. - Otherwise, make a guess.
  95. This method can be easily overriden by other submodules.
  96. You can also override this method to change the order of name's
  97. attributes
  98. When this method is called, :attr:`~.name` already has unified and
  99. trimmed whitespace.
  100. """
  101. # Company name goes to the lastname
  102. if is_company or not name:
  103. parts = [name or False, False]
  104. # Guess name splitting
  105. else:
  106. parts = name.strip().split(" ", 1)
  107. while len(parts) < 2:
  108. parts.append(False)
  109. return {"lastname": parts[0], "firstname": parts[1]}
  110. @api.one
  111. def _inverse_name(self):
  112. """Try to revert the effect of :meth:`._compute_name`."""
  113. parts = self._get_inverse_name(self.name, self.is_company)
  114. self.lastname, self.firstname = parts["lastname"], parts["firstname"]
  115. @api.one
  116. @api.constrains("firstname", "lastname")
  117. def _check_name(self):
  118. """Ensure at least one name is set."""
  119. if ((self.type == 'contact' or self.is_company) and
  120. not (self.firstname or self.lastname)):
  121. raise exceptions.EmptyNamesError(self)
  122. @api.one
  123. @api.onchange("firstname", "lastname")
  124. def _onchange_subnames(self):
  125. """Avoid recursion when the user changes one of these fields.
  126. This forces to skip the :attr:`~.name` inversion when the user is
  127. setting it in a not-inverted way.
  128. """
  129. # Modify self's context without creating a new Environment.
  130. # See https://github.com/odoo/odoo/issues/7472#issuecomment-119503916.
  131. self.env.context = self.with_context(skip_onchange=True).env.context
  132. @api.one
  133. @api.onchange("name")
  134. def _onchange_name(self):
  135. """Ensure :attr:`~.name` is inverted in the UI."""
  136. if self.env.context.get("skip_onchange"):
  137. # Do not skip next onchange
  138. self.env.context = (
  139. self.with_context(skip_onchange=False).env.context)
  140. else:
  141. self._inverse_name_after_cleaning_whitespace()
  142. @api.model
  143. def _install_partner_firstname(self):
  144. """Save names correctly in the database.
  145. Before installing the module, field ``name`` contains all full names.
  146. When installing it, this method parses those names and saves them
  147. correctly into the database. This can be called later too if needed.
  148. """
  149. # Find records with empty firstname and lastname
  150. records = self.search([("firstname", "=", False),
  151. ("lastname", "=", False)])
  152. # Force calculations there
  153. records._inverse_name()
  154. _logger.info("%d partners updated installing module.", len(records))
  155. # Disabling SQL constraint givint a more explicit error using a Python
  156. # contstraint
  157. _sql_constraints = [(
  158. 'check_name',
  159. "CHECK( 1=1 )",
  160. 'Contacts require a name.'
  161. )]