96 lines
3.0 KiB
Python
96 lines
3.0 KiB
Python
from odoo import models, fields, api
|
|
from odoo.exceptions import UserError
|
|
|
|
|
|
class WhatsAppMassWizard(models.TransientModel):
|
|
_name = 'whatsapp.mass.wizard'
|
|
_description = 'Send Mass WhatsApp Message'
|
|
|
|
account_id = fields.Many2one(
|
|
'whatsapp.account',
|
|
string='Cuenta WhatsApp',
|
|
required=True,
|
|
default=lambda self: self.env['whatsapp.account'].get_default_account(),
|
|
)
|
|
partner_ids = fields.Many2many(
|
|
'res.partner',
|
|
string='Contactos',
|
|
required=True,
|
|
)
|
|
content = fields.Text(string='Mensaje', required=True)
|
|
use_template = fields.Boolean(string='Usar Variables')
|
|
total_count = fields.Integer(
|
|
string='Total Contactos',
|
|
compute='_compute_stats',
|
|
)
|
|
valid_count = fields.Integer(
|
|
string='Con Teléfono',
|
|
compute='_compute_stats',
|
|
)
|
|
|
|
@api.depends('partner_ids')
|
|
def _compute_stats(self):
|
|
for wizard in self:
|
|
wizard.total_count = len(wizard.partner_ids)
|
|
wizard.valid_count = len(wizard.partner_ids.filtered(
|
|
lambda p: p.mobile or p.phone
|
|
))
|
|
|
|
@api.model
|
|
def default_get(self, fields_list):
|
|
res = super().default_get(fields_list)
|
|
active_ids = self.env.context.get('active_ids', [])
|
|
active_model = self.env.context.get('active_model')
|
|
|
|
if active_model == 'res.partner' and active_ids:
|
|
res['partner_ids'] = [(6, 0, active_ids)]
|
|
|
|
return res
|
|
|
|
def action_send(self):
|
|
"""Send WhatsApp to all selected partners"""
|
|
self.ensure_one()
|
|
|
|
if not self.account_id:
|
|
raise UserError('Seleccione una cuenta de WhatsApp')
|
|
|
|
sent_count = 0
|
|
failed_count = 0
|
|
|
|
for partner in self.partner_ids:
|
|
phone = partner.mobile or partner.phone
|
|
if not phone:
|
|
failed_count += 1
|
|
continue
|
|
|
|
try:
|
|
content = self.content
|
|
if self.use_template:
|
|
content = content.replace('{{name}}', partner.name or '')
|
|
content = content.replace('{{email}}', partner.email or '')
|
|
|
|
conversation = self.env['whatsapp.conversation'].find_or_create_by_phone(
|
|
phone=phone,
|
|
account_id=self.account_id.id,
|
|
contact_name=partner.name,
|
|
)
|
|
conversation.partner_id = partner
|
|
|
|
self.env['whatsapp.message'].send_message(
|
|
conversation_id=conversation.id,
|
|
content=content,
|
|
)
|
|
sent_count += 1
|
|
|
|
except Exception:
|
|
failed_count += 1
|
|
|
|
return {
|
|
'type': 'ir.actions.client',
|
|
'tag': 'display_notification',
|
|
'params': {
|
|
'message': f'Enviados: {sent_count}, Fallidos: {failed_count}',
|
|
'type': 'success' if failed_count == 0 else 'warning',
|
|
}
|
|
}
|