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.

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