mailing_sms_test.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from odoo import fields, models, _
  4. from odoo.addons.phone_validation.tools import phone_validation
  5. class MassSMSTest(models.TransientModel):
  6. _name = 'mailing.sms.test'
  7. _description = 'Test SMS Mailing'
  8. def _default_numbers(self):
  9. return self.env.user.partner_id.phone_sanitized or ""
  10. numbers = fields.Text(string='Number(s)', required=True,
  11. default=_default_numbers, help='Carriage-return-separated list of phone numbers')
  12. mailing_id = fields.Many2one('mailing.mailing', string='Mailing', required=True, ondelete='cascade')
  13. def action_send_sms(self):
  14. self.ensure_one()
  15. numbers = [number.strip() for number in self.numbers.splitlines()]
  16. sanitize_res = phone_validation.phone_sanitize_numbers_w_record(numbers, self.env.user)
  17. sanitized_numbers = [info['sanitized'] for info in sanitize_res.values() if info['sanitized']]
  18. invalid_numbers = [number for number, info in sanitize_res.items() if info['code']]
  19. record = self.env[self.mailing_id.mailing_model_real].search([], limit=1)
  20. body = self.mailing_id.body_plaintext
  21. if record:
  22. # Returns a proper error if there is a syntax error with qweb
  23. body = self.env['mail.render.mixin']._render_template(body, self.mailing_id.mailing_model_real, record.ids)[record.id]
  24. # res_id is used to map the result to the number to log notifications as IAP does not return numbers...
  25. # TODO: clean IAP to make it return a clean dict with numbers / use custom keys / rename res_id to external_id
  26. sent_sms_list = self.env['sms.api']._send_sms_batch([{
  27. 'res_id': number,
  28. 'number': number,
  29. 'content': body,
  30. } for number in sanitized_numbers])
  31. error_messages = {}
  32. if any(sent_sms.get('state') != 'success' for sent_sms in sent_sms_list):
  33. error_messages = self.env['sms.api']._get_sms_api_error_messages()
  34. notification_messages = []
  35. if invalid_numbers:
  36. notification_messages.append(_('The following numbers are not correctly encoded: %s',
  37. ', '.join(invalid_numbers)))
  38. for sent_sms in sent_sms_list:
  39. if sent_sms.get('state') == 'success':
  40. notification_messages.append(
  41. _('Test SMS successfully sent to %s', sent_sms.get('res_id')))
  42. elif sent_sms.get('state'):
  43. notification_messages.append(
  44. _('Test SMS could not be sent to %s:<br>%s',
  45. sent_sms.get('res_id'),
  46. error_messages.get(sent_sms['state'], _("An error occurred.")))
  47. )
  48. if notification_messages:
  49. self.mailing_id._message_log(body='<ul>%s</ul>' % ''.join(
  50. ['<li>%s</li>' % notification_message for notification_message in notification_messages]
  51. ))
  52. return True