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.

80 lines
2.9 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2015 Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>
  3. # © 2015 Antonio Espinosa <antonioea@antiun.com>
  4. # © 2015 Javier Iniesta <javieria@antiun.com>
  5. # © 2016 Antonio Espinosa - <antonio.espinosa@tecnativa.com>
  6. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  7. from openerp import models, fields, api, _
  8. class MailMassMailingContact(models.Model):
  9. _inherit = 'mail.mass_mailing.contact'
  10. partner_id = fields.Many2one(comodel_name='res.partner', string="Partner",
  11. domain=[('email', '!=', False)])
  12. _sql_constraints = [
  13. ('partner_list_uniq', 'unique(partner_id, list_id)',
  14. _('Partner already exists in this mailing list.'))
  15. ]
  16. @api.onchange('partner_id')
  17. def _onchange_partner(self):
  18. if self.partner_id:
  19. self.name = self.partner_id.name
  20. self.email = self.partner_id.email
  21. @api.model
  22. def create(self, vals):
  23. if not vals.get('partner_id'):
  24. vals = self._set_partner(vals)
  25. vals = self._set_name_email(vals)
  26. return super(MailMassMailingContact, self).create(vals)
  27. @api.one
  28. def write(self, vals):
  29. if vals.get('partner_id', None) is False:
  30. # If removing partner, search again by email
  31. vals = self._set_partner(vals)
  32. vals = self._set_name_email(vals)
  33. return super(MailMassMailingContact, self).write(vals)
  34. def _prepare_partner(self, vals, mailing_list):
  35. vals = {
  36. 'name': vals.get('name') or vals.get('email'),
  37. 'email': vals.get('email', False),
  38. }
  39. if mailing_list.partner_category:
  40. vals['category_id'] = [(4, mailing_list.partner_category.id, 0)]
  41. return vals
  42. def _set_partner(self, vals):
  43. email = vals.get('email', self.email)
  44. if not email: # pragma: no cover
  45. return vals
  46. m_mailing = self.env['mail.mass_mailing.list']
  47. m_partner = self.env['res.partner']
  48. list_id = vals.get('list_id', self.list_id.id)
  49. mailing_list = m_mailing.browse(list_id)
  50. # Look for a partner with that email
  51. email = email.strip()
  52. partners = m_partner.search([('email', '=ilike', email)], limit=1)
  53. if partners:
  54. # Partner found
  55. vals['partner_id'] = partners[0].id
  56. elif mailing_list.partner_mandatory:
  57. # Create partner
  58. partner = m_partner.sudo().create(
  59. self._prepare_partner(vals, mailing_list))
  60. vals['partner_id'] = partner.id
  61. return vals
  62. def _set_name_email(self, vals):
  63. partner_id = vals.get('partner_id', self.partner_id.id)
  64. if not partner_id:
  65. return vals
  66. partner = self.env['res.partner'].browse(partner_id)
  67. vals['email'] = partner.email
  68. vals['name'] = partner.name
  69. return vals