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.

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