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.

95 lines
3.1 KiB

  1. # Copyright 2019 Komit <https://komit-consulting.com>
  2. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  3. import logging
  4. from odoo import api, models, _
  5. from odoo.exceptions import UserError, ValidationError
  6. from odoo.tools import config
  7. _logger = logging.getLogger(__name__)
  8. try:
  9. from email_validator import (
  10. validate_email,
  11. EmailSyntaxError,
  12. EmailUndeliverableError,
  13. )
  14. except ImportError:
  15. _logger.debug('Cannot import "email_validator".')
  16. validate_email = None
  17. class ResPartner(models.Model):
  18. _inherit = 'res.partner'
  19. @api.model
  20. def email_check(self, emails):
  21. if (config['test_enable'] and
  22. not self.env.context.get('test_partner_email_check')):
  23. return emails
  24. return ','.join(self._normalize_email(email.strip())
  25. for email in emails.split(','))
  26. @api.constrains('email')
  27. def _check_email_unique(self):
  28. if self._should_filter_duplicates():
  29. for rec in self.filtered("email"):
  30. if ',' in rec.email:
  31. raise UserError(
  32. _("Field contains multiple email addresses. This is "
  33. "not supported when duplicate email addresses are "
  34. "not allowed.")
  35. )
  36. if self.search_count(
  37. [('email', '=', rec.email), ('id', '!=', rec.id)]
  38. ):
  39. raise UserError(
  40. _("Email '%s' is already in use.") % rec.email.strip()
  41. )
  42. def _normalize_email(self, email):
  43. if validate_email is None:
  44. _logger.warning(
  45. 'Can not validate email, '
  46. 'python dependency required "email_validator"')
  47. return email
  48. try:
  49. result = validate_email(
  50. email,
  51. check_deliverability=self._should_check_deliverability(),
  52. )
  53. except EmailSyntaxError:
  54. raise ValidationError(
  55. _("%s is an invalid email") % email.strip()
  56. )
  57. except EmailUndeliverableError:
  58. raise ValidationError(
  59. _("Cannot deliver to email address %s") % email.strip()
  60. )
  61. return result['local'].lower() + '@' + result['domain_i18n']
  62. def _should_filter_duplicates(self):
  63. conf = self.env['ir.config_parameter'].sudo().get_param(
  64. 'partner_email_check_filter_duplicates', 'False'
  65. )
  66. return conf == 'True'
  67. def _should_check_deliverability(self):
  68. conf = self.env['ir.config_parameter'].sudo().get_param(
  69. 'partner_email_check_check_deliverability', 'False'
  70. )
  71. return conf == 'True'
  72. @api.model
  73. def create(self, vals):
  74. if vals.get('email'):
  75. vals['email'] = self.email_check(vals['email'])
  76. return super(ResPartner, self).create(vals)
  77. @api.multi
  78. def write(self, vals):
  79. if vals.get('email'):
  80. vals['email'] = self.email_check(vals['email'])
  81. return super(ResPartner, self).write(vals)