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.

238 lines
8.6 KiB

  1. # -*- coding: utf-8 -*-
  2. # Author: Nicolas Bessi. Copyright Camptocamp SA
  3. # Copyright (C)
  4. # 2014: Agile Business Group (<http://www.agilebg.com>)
  5. # 2015: Grupo ESOC <www.grupoesoc.es>
  6. # 2015: Antiun Ingenieria S.L. - Antonio Espinosa
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU Affero General Public License as
  10. # published by the Free Software Foundation, either version 3 of the
  11. # License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Affero General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Affero General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. import logging
  21. from openerp import api, fields, models
  22. from . import exceptions
  23. _logger = logging.getLogger(__name__)
  24. class ResPartner(models.Model):
  25. """Adds last name and first name; name becomes a stored function field."""
  26. _inherit = 'res.partner'
  27. firstname = fields.Char("First name")
  28. lastname = fields.Char("Last name")
  29. name = fields.Char(
  30. compute="_compute_name",
  31. inverse="_inverse_name_after_cleaning_whitespace",
  32. required=False,
  33. store=True)
  34. @api.model
  35. def create(self, vals):
  36. """Add inverted names at creation if unavailable."""
  37. context = dict(self.env.context)
  38. name = vals.get("name", context.get("default_name"))
  39. if name is not None:
  40. # Calculate the splitted fields
  41. inverted = self._get_inverse_name(
  42. self._get_whitespace_cleaned_name(name),
  43. vals.get("is_company",
  44. self.default_get(["is_company"])["is_company"]))
  45. for key, value in inverted.iteritems():
  46. if not vals.get(key) or context.get("copy"):
  47. vals[key] = value
  48. # Remove the combined fields
  49. if "name" in vals:
  50. del vals["name"]
  51. if "default_name" in context:
  52. del context["default_name"]
  53. return super(ResPartner, self.with_context(context)).create(vals)
  54. @api.multi
  55. def copy(self, default=None):
  56. """Ensure partners are copied right.
  57. Odoo adds ``(copy)`` to the end of :attr:`~.name`, but that would get
  58. ignored in :meth:`~.create` because it also copies explicitly firstname
  59. and lastname fields.
  60. """
  61. return super(ResPartner, self.with_context(copy=True)).copy(default)
  62. @api.model
  63. def default_get(self, fields_list):
  64. """Invert name when getting default values."""
  65. result = super(ResPartner, self).default_get(fields_list)
  66. inverted = self._get_inverse_name(
  67. self._get_whitespace_cleaned_name(result.get("name", "")),
  68. result.get("is_company", False))
  69. for field in inverted.keys():
  70. if field in fields_list:
  71. result[field] = inverted.get(field)
  72. return result
  73. @api.model
  74. def _names_order_default(self):
  75. return 'last_first'
  76. @api.model
  77. def _get_names_order(self):
  78. """Get names order configuration from system parameters.
  79. You can override this method to read configuration from language,
  80. country, company or other"""
  81. return self.env['ir.config_parameter'].get_param(
  82. 'partner_names_order', self._names_order_default())
  83. @api.model
  84. def _get_computed_name(self, lastname, firstname):
  85. """Compute the 'name' field according to splitted data.
  86. You can override this method to change the order of lastname and
  87. firstname the computed name"""
  88. order = self._get_names_order()
  89. if order == 'last_first_comma':
  90. return u", ".join((p for p in (lastname, firstname) if p))
  91. elif order == 'first_last':
  92. return u" ".join((p for p in (firstname, lastname) if p))
  93. else:
  94. return u" ".join((p for p in (lastname, firstname) if p))
  95. @api.one
  96. @api.depends("firstname", "lastname")
  97. def _compute_name(self):
  98. """Write the 'name' field according to splitted data."""
  99. self.name = self._get_computed_name(self.lastname, self.firstname)
  100. @api.one
  101. def _inverse_name_after_cleaning_whitespace(self):
  102. """Clean whitespace in :attr:`~.name` and split it.
  103. The splitting logic is stored separately in :meth:`~._inverse_name`, so
  104. submodules can extend that method and get whitespace cleaning for free.
  105. """
  106. # Remove unneeded whitespace
  107. clean = self._get_whitespace_cleaned_name(self.name)
  108. # Clean name avoiding infinite recursion
  109. if self.name != clean:
  110. self.name = clean
  111. # Save name in the real fields
  112. else:
  113. self._inverse_name()
  114. @api.model
  115. def _get_whitespace_cleaned_name(self, name, comma=False):
  116. """Remove redundant whitespace from :param:`name`.
  117. Removes leading, trailing and duplicated whitespace.
  118. """
  119. if name:
  120. name = u" ".join(name.split(None))
  121. if comma:
  122. name = name.replace(" ,", ",")
  123. name = name.replace(", ", ",")
  124. return name
  125. @api.model
  126. def _get_inverse_name(self, name, is_company=False):
  127. """Compute the inverted name.
  128. - If the partner is a company, save it in the lastname.
  129. - Otherwise, make a guess.
  130. This method can be easily overriden by other submodules.
  131. You can also override this method to change the order of name's
  132. attributes
  133. When this method is called, :attr:`~.name` already has unified and
  134. trimmed whitespace.
  135. """
  136. # Company name goes to the lastname
  137. if is_company or not name:
  138. parts = [name or False, False]
  139. # Guess name splitting
  140. else:
  141. order = self._get_names_order()
  142. # Remove redundant spaces
  143. name = self._get_whitespace_cleaned_name(
  144. name, comma=(order == 'last_first_comma'))
  145. parts = name.split("," if order == 'last_first_comma' else " ", 1)
  146. if len(parts) > 1:
  147. if order == 'first_last':
  148. parts = [u" ".join(parts[1:]), parts[0]]
  149. else:
  150. parts = [parts[0], u" ".join(parts[1:])]
  151. else:
  152. while len(parts) < 2:
  153. parts.append(False)
  154. return {"lastname": parts[0], "firstname": parts[1]}
  155. @api.one
  156. def _inverse_name(self):
  157. """Try to revert the effect of :meth:`._compute_name`."""
  158. parts = self._get_inverse_name(self.name, self.is_company)
  159. self.lastname, self.firstname = parts["lastname"], parts["firstname"]
  160. @api.one
  161. @api.constrains("firstname", "lastname")
  162. def _check_name(self):
  163. """Ensure at least one name is set."""
  164. if not (self.firstname or self.lastname):
  165. raise exceptions.EmptyNamesError(self)
  166. @api.one
  167. @api.onchange("firstname", "lastname")
  168. def _onchange_subnames(self):
  169. """Avoid recursion when the user changes one of these fields.
  170. This forces to skip the :attr:`~.name` inversion when the user is
  171. setting it in a not-inverted way.
  172. """
  173. # Modify self's context without creating a new Environment.
  174. # See https://github.com/odoo/odoo/issues/7472#issuecomment-119503916.
  175. self.env.context = self.with_context(skip_onchange=True).env.context
  176. @api.one
  177. @api.onchange("name")
  178. def _onchange_name(self):
  179. """Ensure :attr:`~.name` is inverted in the UI."""
  180. if self.env.context.get("skip_onchange"):
  181. # Do not skip next onchange
  182. self.env.context = (
  183. self.with_context(skip_onchange=False).env.context)
  184. else:
  185. self._inverse_name_after_cleaning_whitespace()
  186. @api.model
  187. def _install_partner_firstname(self):
  188. """Save names correctly in the database.
  189. Before installing the module, field ``name`` contains all full names.
  190. When installing it, this method parses those names and saves them
  191. correctly into the database. This can be called later too if needed.
  192. """
  193. # Find records with empty firstname and lastname
  194. records = self.search([("firstname", "=", False),
  195. ("lastname", "=", False)])
  196. # Force calculations there
  197. records._inverse_name()
  198. _logger.info("%d partners updated installing module.", len(records))