from odoo import models, fields, api from odoo.exceptions import UserError class WhatsAppSendWizard(models.TransientModel): _name = 'whatsapp.send.wizard' _description = 'Send WhatsApp Message' partner_id = fields.Many2one('res.partner', string='Contacto') phone = fields.Char(string='Teléfono', required=True) account_id = fields.Many2one( 'whatsapp.account', string='Cuenta WhatsApp', required=True, default=lambda self: self.env['whatsapp.account'].get_default_account(), ) message_type = fields.Selection([ ('text', 'Texto'), ('image', 'Imagen'), ('document', 'Documento'), ], string='Tipo', default='text', required=True) content = fields.Text(string='Mensaje', required=True) media_url = fields.Char(string='URL del Archivo') attachment_id = fields.Many2one('ir.attachment', string='Adjunto') res_model = fields.Char(string='Modelo Origen') res_id = fields.Integer(string='ID Origen') @api.onchange('attachment_id') def _onchange_attachment_id(self): if self.attachment_id: base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') self.media_url = f"{base_url}/web/content/{self.attachment_id.id}" def action_send(self): """Send the WhatsApp message""" self.ensure_one() if not self.account_id: raise UserError('Seleccione una cuenta de WhatsApp') conversation = self.env['whatsapp.conversation'].find_or_create_by_phone( phone=self.phone, account_id=self.account_id.id, contact_name=self.partner_id.name if self.partner_id else None, ) if self.partner_id: conversation.partner_id = self.partner_id self.env['whatsapp.message'].send_message( conversation_id=conversation.id, content=self.content, message_type=self.message_type, media_url=self.media_url, ) return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'message': 'Mensaje enviado correctamente', 'type': 'success', } } def action_send_and_open(self): """Send message and open conversation""" self.action_send() conversation = self.env['whatsapp.conversation'].search([ ('phone_number', '=', self.phone), ('account_id', '=', self.account_id.id), ], limit=1, order='id desc') if conversation: return conversation.action_open_chat() return {'type': 'ir.actions.act_window_close'}