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.

250 lines
9.0 KiB

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