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.

78 lines
2.7 KiB

  1. # -*- coding: utf-8 -*-
  2. # See README.rst file on addon root folder for license details
  3. from openerp import models, fields, api, _
  4. class MailMassMailingContact(models.Model):
  5. _inherit = 'mail.mass_mailing.contact'
  6. partner_id = fields.Many2one(comodel_name='res.partner', string="Partner",
  7. domain=[('email', '!=', False)])
  8. _sql_constraints = [
  9. ('partner_list_uniq', 'unique(partner_id, list_id)',
  10. _('Partner already exists in this mailing list.'))
  11. ]
  12. @api.one
  13. @api.onchange('partner_id')
  14. def _onchange_partner(self):
  15. if self.partner_id:
  16. self.name = self.partner_id.name
  17. self.email = self.partner_id.email
  18. @api.model
  19. @api.returns('self', lambda x: x.id)
  20. def create(self, vals):
  21. if not vals.get('partner_id'):
  22. vals = self._set_partner(vals)
  23. vals = self._set_name_email(vals)
  24. return super(MailMassMailingContact, self).create(vals)
  25. @api.one
  26. def write(self, vals):
  27. if vals.get('partner_id', None) is False:
  28. # If removing partner, search again by email
  29. vals = self._set_partner(vals)
  30. vals = self._set_name_email(vals)
  31. return super(MailMassMailingContact, self).write(vals)
  32. def _prepare_partner(self, vals, mailing_list):
  33. vals = {
  34. 'name': vals.get('name') or vals.get('email'),
  35. 'email': vals.get('email', False),
  36. }
  37. if mailing_list.partner_category:
  38. vals['category_id'] = [(4, mailing_list.partner_category.id, 0)]
  39. return vals
  40. def _set_partner(self, vals):
  41. email = vals.get('email', self.email)
  42. if not email:
  43. return vals
  44. m_mailing = self.env['mail.mass_mailing.list']
  45. m_partner = self.env['res.partner']
  46. list_id = vals.get('list_id', self.list_id.id)
  47. mailing_list = m_mailing.browse(list_id)
  48. # Look for a partner with that email
  49. email = email.strip()
  50. partners = m_partner.search([('email', '=ilike', email)], limit=1)
  51. if partners:
  52. # Partner found
  53. vals['partner_id'] = partners[0].id
  54. elif mailing_list.partner_mandatory:
  55. # Create partner
  56. partner = m_partner.sudo().create(
  57. self._prepare_partner(vals, mailing_list))
  58. vals['partner_id'] = partner.id
  59. return vals
  60. def _set_name_email(self, vals):
  61. partner_id = vals.get('partner_id', self.partner_id.id)
  62. if not partner_id:
  63. return vals
  64. partner = self.env['res.partner'].browse(partner_id)
  65. vals['email'] = partner.email
  66. vals['name'] = partner.name
  67. return vals