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.

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