odex30_standard/odex30_base/os_whatsapp_integration/wizard/wizard.py

52 lines
1.9 KiB
Python

from odoo import api, fields, models
import html2text
class WhatsappSendMessage(models.TransientModel):
_name = 'whatsapp.message.wizard'
_description = 'Whatsapp Message Wizard'
user_id = fields.Many2one('res.partner', string="Recipient")
mobile = fields.Char(related='user_id.mobile', required=True, readonly=False)
message = fields.Text(string="Message")
model = fields.Char('Related Document Model')
template_id = fields.Many2one(
'mail.template', 'Use template', index=True,
domain="[('model', '=', model)]"
)
@api.onchange('template_id')
def _onchange_template_id(self):
"""
Renders the selected template and populates the message field.
This is the correct method for Odoo 17/18.
"""
if self.template_id:
res_id = self._context.get('active_id')
# Render the template's body_html field for the active record
rendered_html = self.template_id._render_field('body_html', [res_id], compute_lang=True)[res_id]
# Convert the rendered HTML to plain text suitable for WhatsApp
self.message = html2text.html2text(rendered_html)
def send_message(self):
"""
Generates the WhatsApp Web URL and opens it in a new tab.
"""
self.ensure_one()
if self.message and self.mobile:
# Properly encode the message for a URL, handling spaces and new lines
message_string = self.message.replace(' ', '%20').replace('\n', '%0A')
# Sanitize the mobile number for the URL
number = self.mobile.replace('+', '').replace(' ', '')
link = f"https://web.whatsapp.com/send?phone={number}&text={message_string}"
return {
'type': 'ir.actions.act_url',
'url': link,
'target': 'new',
}
return True