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.

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