whatsapp_account.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import logging
  2. import requests
  3. import json
  4. import mimetypes
  5. import base64
  6. from markupsafe import Markup
  7. from odoo import fields, models, _
  8. from odoo.addons.whatsapp.tools.whatsapp_api import WhatsAppApi
  9. from odoo.tools import plaintext2html
  10. _logger = logging.getLogger(__name__)
  11. class WhatsAppAccount(models.Model):
  12. _inherit = "whatsapp.account"
  13. whatsapp_web_url = fields.Char(
  14. string="WhatsApp Web URL", readonly=False, copy=False
  15. )
  16. whatsapp_web_login = fields.Char(string="Login", readonly=False, copy=False)
  17. whatsapp_web_api_key = fields.Char(string="API Key", readonly=False, copy=False)
  18. def get_groups(self):
  19. """
  20. Obtiene los grupos de WhatsApp Web para la cuenta desde la base de datos de la plataforma.
  21. Returns:
  22. list: Lista de diccionarios con la información de los grupos en formato compatible con Odoo
  23. """
  24. self.ensure_one()
  25. if not self.whatsapp_web_url:
  26. _logger.warning(
  27. "No se ha configurado la URL de WhatsApp Web para la cuenta %s",
  28. self.name,
  29. )
  30. return []
  31. if not self.whatsapp_web_login:
  32. _logger.warning(
  33. "No se ha configurado el Login (session_name) para la cuenta %s",
  34. self.name,
  35. )
  36. return []
  37. if not self.whatsapp_web_api_key:
  38. _logger.warning(
  39. "No se ha configurado la API Key para la cuenta %s", self.name
  40. )
  41. return []
  42. try:
  43. # Construir URL del nuevo endpoint
  44. base_url = self.whatsapp_web_url.rstrip("/")
  45. session_name = self.whatsapp_web_login
  46. url = f"{base_url}/api/v1/{session_name}/groups"
  47. headers = {
  48. "Content-Type": "application/json",
  49. "X-API-Key": self.whatsapp_web_api_key,
  50. }
  51. response = requests.get(url, headers=headers, timeout=30)
  52. if response.status_code == 200:
  53. groups = response.json()
  54. _logger.info(
  55. "Grupos obtenidos desde la base de datos: %d grupos", len(groups)
  56. )
  57. return groups
  58. else:
  59. _logger.error(
  60. "Error al obtener groups: %s - %s",
  61. response.status_code,
  62. response.text,
  63. )
  64. return []
  65. except Exception as e:
  66. _logger.error("Error en la petición de groups: %s", str(e))
  67. return []
  68. def _find_or_create_partner_from_payload(self, contacts_data):
  69. """
  70. Identify or create a partner based on webhook contacts list.
  71. Priority:
  72. 1. Mobile (last 10 digits match) -> Update WA ID if needed.
  73. 2. WA ID (exact match) -> Update Mobile/Name if needed.
  74. 3. Create new partner.
  75. Returns: res.partner record
  76. """
  77. if not contacts_data:
  78. return self.env["res.partner"]
  79. contact_info = contacts_data[0]
  80. wa_id = contact_info.get("wa_id")
  81. mobile = contact_info.get("phone_number") # Normalized phone from webhook
  82. # Try to get profile name, fallback to wa_id
  83. profile_name = contact_info.get("profile", {}).get("name") or wa_id
  84. # Lid handling: If the main ID is an LID (Lyophilized ID used for privacy),
  85. # we still prefer to link it to a real phone number if available.
  86. # The payload might have "wa_id" as the LID and "phone_number" as the real number,
  87. # or vice-versa depending on context. We trust 'phone_number' field for mobile search.
  88. partner = self.env["res.partner"]
  89. # Strategy 1: Search by Mobile (last 10 digits)
  90. if mobile and len(mobile) >= 10:
  91. last_10 = mobile[-10:]
  92. partner = (
  93. self.env["res.partner"]
  94. .sudo()
  95. .search([("mobile", "like", f"%{last_10}")], limit=1)
  96. )
  97. if partner:
  98. _logger.info(f"Partner found by mobile {last_10}: {partner.name}")
  99. # Update WA ID if missing or different (and valid)
  100. if wa_id and partner.whatsapp_web_id != wa_id:
  101. partner.write({"whatsapp_web_id": wa_id})
  102. return partner
  103. # Strategy 2: Search by WhatsApp Web ID
  104. if wa_id:
  105. partner = (
  106. self.env["res.partner"]
  107. .sudo()
  108. .search([("whatsapp_web_id", "=", wa_id)], limit=1)
  109. )
  110. if partner:
  111. _logger.info(f"Partner found by WA ID {wa_id}: {partner.name}")
  112. # Update mobile if missing
  113. if mobile and not partner.mobile:
  114. partner.write({"mobile": mobile})
  115. return partner
  116. # Strategy 3: Create New Partner
  117. vals = {
  118. "name": profile_name,
  119. "whatsapp_web_id": wa_id,
  120. "mobile": mobile,
  121. }
  122. _logger.info(f"Creating new partner from webhook: {vals}")
  123. partner = self.env["res.partner"].sudo().create(vals)
  124. return partner
  125. def _process_messages(self, value):
  126. """
  127. Sobrescritura completa para manejar mensajes enviados desde la misma cuenta (self-messages)
  128. y rutearlos al chat correcto.
  129. Refactorizado para soportar grupos vía metadata y creación Lazy.
  130. """
  131. # Log del payload recibido para debug
  132. _logger.info(
  133. "DEBUG - WhatsApp Webhook Value: %s",
  134. json.dumps(value, indent=4, default=str),
  135. )
  136. if "messages" not in value and value.get("whatsapp_business_api_data", {}).get(
  137. "messages"
  138. ):
  139. value = value["whatsapp_business_api_data"]
  140. wa_api = WhatsAppApi(self)
  141. # 1. Identificar Remitente (Sender)
  142. contacts_data = value.get("contacts", [])
  143. sender_partner = self._find_or_create_partner_from_payload(contacts_data)
  144. # Fallback Name if partner creation failed (rare)
  145. sender_name = sender_partner.name if sender_partner else "Unknown"
  146. # Determinar el ID del teléfono actual (para detectar auto-mensajes)
  147. my_phone_id = value.get("metadata", {}).get("phone_number_id")
  148. for messages in value.get("messages", []):
  149. parent_msg_id = False
  150. parent_id = False
  151. channel = False
  152. sender_mobile = messages["from"]
  153. message_type = messages["type"]
  154. # Lógica para detectar self-messages
  155. is_self_message = False
  156. if my_phone_id and sender_mobile == my_phone_id:
  157. is_self_message = True
  158. # Intentar obtener el destinatario real
  159. if "to" in messages:
  160. sender_mobile = messages["to"]
  161. elif (
  162. "id" in messages
  163. and "true_" in messages["id"]
  164. and "@c.us" in messages["id"]
  165. ):
  166. # Fallback: intentar parsear del ID (formato true_NUMBER@c.us_ID)
  167. try:
  168. # Extraer parte entre true_ y @
  169. parts = messages["id"].split("_")
  170. if len(parts) > 1:
  171. jid = parts[1] # 5215581845273@c.us
  172. sender_mobile = jid
  173. except:
  174. pass
  175. _logger.info(
  176. "Detectado self-message. Redirigiendo a chat de: %s", sender_mobile
  177. )
  178. # --- RECONCILIATION LOGIC ---
  179. # Si viene un job_id en metadata, reconciliar el ID antes de chequear duplicados.
  180. # Esto maneja el caso donde el "Echo" del mensaje trae el ID real y confirma el envío del worker.
  181. job_id = value.get("metadata", {}).get("job_id")
  182. if job_id:
  183. pending_msg = (
  184. self.env["whatsapp.message"]
  185. .sudo()
  186. .search([("job_id", "=", job_id)], limit=1)
  187. )
  188. if pending_msg and pending_msg.msg_uid != messages["id"]:
  189. _logger.info(
  190. "Reconciliando Message ID desde payload de mensajes: JobID %s -> Real ID %s",
  191. job_id,
  192. messages["id"],
  193. )
  194. pending_msg.msg_uid = messages["id"]
  195. # Opcional: Asegurar estado si es necesario, aunque si es un echo,
  196. # el estado 'sent' ya debería estar set por el envío inicial.
  197. # ----------------------------
  198. # --- DEDUPLICATION LOGIC ---
  199. # Check if this message was already processed or sent by Odoo
  200. # This prevents the "Echo" effect when Odoo sends a message and Webhook confirms it
  201. existing_wa_msg = (
  202. self.env["whatsapp.message"]
  203. .sudo()
  204. .search([("msg_uid", "=", messages["id"])], limit=1)
  205. )
  206. if existing_wa_msg and message_type != "reaction":
  207. _logger.info(
  208. "Skipping duplicate message %s (already exists)", messages["id"]
  209. )
  210. # Optionally update status here if needed, but avoiding duplicate mail.message is key
  211. continue
  212. # ---------------------------
  213. # Context / Reply Handling
  214. target_record = False
  215. if "context" in messages and messages["context"].get("id"):
  216. parent_whatsapp_message = (
  217. self.env["whatsapp.message"]
  218. .sudo()
  219. .search([("msg_uid", "=", messages["context"]["id"])])
  220. )
  221. if parent_whatsapp_message:
  222. parent_msg_id = parent_whatsapp_message.id
  223. parent_id = parent_whatsapp_message.mail_message_id
  224. if parent_id:
  225. # Check where the parent message belongs
  226. if (
  227. parent_id.model
  228. and parent_id.model != "discuss.channel"
  229. and parent_id.res_id
  230. ):
  231. # It's a reply to a document (Ticket, Order, etc.)
  232. try:
  233. target_record = self.env[parent_id.model].browse(
  234. parent_id.res_id
  235. )
  236. _logger.info(
  237. f"Reply routed to Document: {parent_id.model} #{parent_id.res_id}"
  238. )
  239. except Exception as e:
  240. _logger.warning(
  241. f"Could not load target record {parent_id.model} #{parent_id.res_id}: {e}"
  242. )
  243. target_record = False
  244. else:
  245. # It's a reply in a channel
  246. channel = (
  247. self.env["discuss.channel"]
  248. .sudo()
  249. .search([("message_ids", "in", parent_id.id)], limit=1)
  250. )
  251. # 2. Lógica de Grupos (Metadata - Decoupled & Lazy)
  252. group_metadata = value.get("metadata", {}).get("group")
  253. # Support legacy group_id only if group dict missing
  254. if not group_metadata and value.get("metadata", {}).get("group_id"):
  255. group_metadata = {"id": value.get("metadata", {}).get("group_id")}
  256. if group_metadata and not target_record:
  257. # Check if group module is installed (Use 'in' operator for models with dots)
  258. if "ww.group" in self.env:
  259. # Process Group (Lazy Create + Organic Member Add)
  260. group = self.env["ww.group"].process_webhook_group(
  261. self, group_metadata, sender_partner
  262. )
  263. if group and group.channel_id and not channel:
  264. channel = group.channel_id
  265. _logger.info(
  266. "Mensaje de grupo ruteado a canal: %s", channel.name
  267. )
  268. else:
  269. _logger.warning(
  270. "Recibido mensaje de grupo pero ww.group no está instalado."
  271. )
  272. # 3. Canal Directo (Si no es grupo y no tenemos target ni channel aun)
  273. if not target_record and not channel:
  274. channel = self._find_active_channel(
  275. sender_mobile, sender_name=sender_name, create_if_not_found=True
  276. )
  277. # --- RENAME LOGIC FOR 1:1 CHATS ---
  278. # Solo si estamos usando un canal (no si vamos a un documento)
  279. if channel and channel.channel_type == "whatsapp" and sender_partner:
  280. is_group_channel = False
  281. if channel.whatsapp_number and channel.whatsapp_number.endswith(
  282. "@g.us"
  283. ):
  284. is_group_channel = True
  285. if not is_group_channel and channel.name != sender_partner.name:
  286. _logger.info(
  287. f"Renaming channel {channel.id} from '{channel.name}' to '{sender_partner.name}'"
  288. )
  289. channel.sudo().write({"name": sender_partner.name})
  290. # -----------------------------------
  291. # Define Target Record if not set (fallback to channel)
  292. if not target_record:
  293. target_record = channel
  294. if not target_record:
  295. _logger.error("Could not determine target record for message")
  296. continue
  297. # Determinar autor (Author ID)
  298. # Preferimos usar el partner identificado del payload
  299. author_id = sender_partner.id if sender_partner else False
  300. # If no sender partner, try channel partner if target is channel
  301. if (
  302. not author_id
  303. and getattr(target_record, "_name", "") == "discuss.channel"
  304. ):
  305. author_id = target_record.whatsapp_partner_id.id
  306. if is_self_message:
  307. # Si es mensaje propio, usar el partner de la compañía o OdooBot
  308. author_id = self.env.ref("base.partner_root").id
  309. kwargs = {
  310. "message_type": "whatsapp_message",
  311. "author_id": author_id,
  312. "subtype_xmlid": "mail.mt_comment",
  313. "parent_id": parent_id.id if parent_id else None,
  314. }
  315. if message_type == "text":
  316. kwargs["body"] = plaintext2html(messages["text"]["body"])
  317. elif message_type == "button":
  318. kwargs["body"] = messages["button"]["text"]
  319. elif message_type in ("document", "image", "audio", "video", "sticker"):
  320. filename = messages[message_type].get("filename")
  321. is_voice = messages[message_type].get("voice")
  322. mime_type = messages[message_type].get("mime_type")
  323. caption = messages[message_type].get("caption")
  324. # Hybrid Handling: Check for local base64 content
  325. data_base64 = messages[message_type].get("data_base64")
  326. if data_base64:
  327. _logger.info("Usando contenido base64 local para %s", message_type)
  328. try:
  329. datas = base64.b64decode(data_base64)
  330. except Exception as e:
  331. _logger.error("Error al decodificar data_base64: %s", e)
  332. datas = b""
  333. else:
  334. # Fallback to standard flow (download from Meta)
  335. datas = wa_api._get_whatsapp_document(messages[message_type]["id"])
  336. if not filename:
  337. extension = mimetypes.guess_extension(mime_type) or ""
  338. filename = message_type + extension
  339. kwargs["attachments"] = [(filename, datas, {"voice": is_voice})]
  340. if caption:
  341. kwargs["body"] = plaintext2html(caption)
  342. elif message_type == "location":
  343. url = Markup(
  344. "https://maps.google.com/maps?q={latitude},{longitude}"
  345. ).format(
  346. latitude=messages["location"]["latitude"],
  347. longitude=messages["location"]["longitude"],
  348. )
  349. body = Markup(
  350. '<a target="_blank" href="{url}"> <i class="fa fa-map-marker"/> {location_string} </a>'
  351. ).format(url=url, location_string=_("Location"))
  352. if messages["location"].get("name"):
  353. body += Markup("<br/>{location_name}").format(
  354. location_name=messages["location"]["name"]
  355. )
  356. if messages["location"].get("address"):
  357. body += Markup("<br/>{location_address}").format(
  358. location_address=messages["location"]["address"]
  359. )
  360. kwargs["body"] = body
  361. elif message_type == "contacts":
  362. body = ""
  363. for contact in messages["contacts"]:
  364. body += Markup(
  365. "<i class='fa fa-address-book'/> {contact_name} <br/>"
  366. ).format(
  367. contact_name=contact.get("name", {}).get("formatted_name", "")
  368. )
  369. for phone in contact.get("phones", []):
  370. body += Markup("{phone_type}: {phone_number}<br/>").format(
  371. phone_type=phone.get("type"),
  372. phone_number=phone.get("phone"),
  373. )
  374. kwargs["body"] = body
  375. elif message_type == "reaction":
  376. msg_uid = messages["reaction"].get("message_id")
  377. whatsapp_message = (
  378. self.env["whatsapp.message"]
  379. .sudo()
  380. .search([("msg_uid", "=", msg_uid)])
  381. )
  382. if whatsapp_message:
  383. # Use sender_partner for reaction if available
  384. partner_id = sender_partner
  385. # FALLBACK: If no sender_partner found (common in Groups where contacts is empty),
  386. # try to find partner by the 'from' field (mobile number)
  387. if not partner_id and messages.get("from"):
  388. mobile = messages["from"]
  389. if len(mobile) >= 10:
  390. partner_id = (
  391. self.env["res.partner"]
  392. .sudo()
  393. .search(
  394. [("mobile", "like", f"%{mobile[-10:]}")], limit=1
  395. )
  396. )
  397. if (
  398. not partner_id
  399. and getattr(target_record, "_name", "") == "discuss.channel"
  400. ):
  401. partner_id = target_record.whatsapp_partner_id
  402. emoji = messages["reaction"].get("emoji")
  403. whatsapp_message.mail_message_id._post_whatsapp_reaction(
  404. reaction_content=emoji, partner_id=partner_id
  405. )
  406. continue
  407. else:
  408. _logger.warning("Unsupported whatsapp message type: %s", messages)
  409. continue
  410. # Fix: Only pass whatsapp_inbound_msg_uid if valid for this channel type
  411. # Standard channels (like groups) do not support this param and will crash
  412. if getattr(target_record, "_name", "") == "discuss.channel":
  413. if (
  414. hasattr(target_record, "channel_type")
  415. and target_record.channel_type == "whatsapp"
  416. ):
  417. kwargs["whatsapp_inbound_msg_uid"] = messages["id"]
  418. target_record.message_post(**kwargs)