ww_group.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. from odoo import models, fields, api
  2. import logging
  3. from datetime import datetime
  4. _logger = logging.getLogger(__name__)
  5. class WWGroup(models.Model):
  6. _name = 'ww.group'
  7. _description = 'Grupo de WhatsApp Web'
  8. name = fields.Char(string='Nombre del Grupo', required=True)
  9. whatsapp_web_id = fields.Char(string='ID WhatsApp Web', index=True, help='ID único del grupo en WhatsApp Web')
  10. whatsapp_account_id = fields.Many2one('whatsapp.account', string='Cuenta de WhatsApp', required=True)
  11. channel_id = fields.Many2one('discuss.channel', string='Canal de Discusión', readonly=True)
  12. contact_ids = fields.Many2many(
  13. comodel_name='res.partner',
  14. relation='ww_group_contact_rel',
  15. column1='group_id',
  16. column2='contact_id',
  17. string='Contactos',
  18. readonly=True,
  19. )
  20. def _process_messages(self, messages_data):
  21. """Process WhatsApp messages and create them in the channel"""
  22. self.ensure_one()
  23. if not messages_data or not self.channel_id:
  24. return True
  25. # Get existing message IDs to avoid duplicates
  26. existing_ids = set(self.channel_id.message_ids.mapped('message_id'))
  27. # Prepare bulk create values
  28. message_vals_list = []
  29. for msg_data in messages_data:
  30. msg_id = msg_data.get('id', {}).get('_serialized')
  31. # Skip if message already exists
  32. if msg_id in existing_ids:
  33. continue
  34. # Get author partner
  35. author_whatsapp_id = msg_data.get('author')
  36. author = self.env['res.partner'].search([
  37. ('whatsapp_web_id', '=', author_whatsapp_id)
  38. ], limit=1) if author_whatsapp_id else False
  39. # Get quoted message author if exists
  40. quoted_author = False
  41. if msg_data.get('hasQuotedMsg') and msg_data.get('quotedParticipant'):
  42. quoted_author = self.env['res.partner'].search([
  43. ('whatsapp_web_id', '=', msg_data['quotedParticipant'])
  44. ], limit=1)
  45. # Convert timestamp to datetime
  46. timestamp = datetime.fromtimestamp(msg_data.get('timestamp', 0))
  47. # Prepare message body with author and content
  48. author_name = author.name if author else "Desconocido"
  49. message_body = f"{msg_data.get('body', '')}"
  50. # Add quoted message if exists
  51. if msg_data.get('hasQuotedMsg') and msg_data.get('quotedMsg', {}).get('body'):
  52. quoted_author_name = quoted_author.name if quoted_author else "Desconocido"
  53. message_body += f"\n\n<blockquote><strong>{quoted_author_name}:</strong> {msg_data['quotedMsg']['body']}</blockquote>"
  54. message_vals = {
  55. 'model': 'discuss.channel',
  56. 'res_id': self.channel_id.id,
  57. 'message_type': 'comment',
  58. 'subtype_id': self.env.ref('mail.mt_comment').id,
  59. 'body': message_body,
  60. 'date': timestamp,
  61. 'author_id': author.id if author else self.env.user.partner_id.id,
  62. 'message_id': msg_id,
  63. }
  64. message_vals_list.append(message_vals)
  65. # Bulk create messages
  66. if message_vals_list:
  67. self.env['mail.message'].create(message_vals_list)
  68. return True
  69. def _create_discussion_channel(self):
  70. """Create a discussion channel for the WhatsApp group"""
  71. self.ensure_one()
  72. try:
  73. # Verificar si ya existe un canal para este grupo
  74. if self.channel_id:
  75. return self.channel_id
  76. # Create channel name with WhatsApp prefix
  77. channel_name = f"📱 {self.name}"
  78. # Verificar que hay contactos
  79. if not self.contact_ids:
  80. _logger.warning(f"No hay contactos para crear el canal del grupo {self.name}")
  81. return False
  82. # Obtener los IDs de los contactos de forma segura
  83. partner_ids = []
  84. for contact in self.contact_ids:
  85. if contact and contact.id:
  86. partner_ids.append(contact.id)
  87. if not partner_ids:
  88. _logger.warning(f"No se encontraron IDs válidos de contactos para el grupo {self.name}")
  89. return False
  90. # Create the channel using channel_create
  91. channel = self.env['discuss.channel'].channel_create(
  92. name=channel_name,
  93. group_id=self.env.user.groups_id[0].id, # Usar el primer grupo del usuario actual
  94. )
  95. # Add members to the channel
  96. channel.add_members(partner_ids=partner_ids)
  97. # Link the channel to the group
  98. self.write({'channel_id': channel.id})
  99. return channel
  100. except Exception as e:
  101. _logger.error(f"Error al crear el canal para el grupo {self.name}: {str(e)}")
  102. return False
  103. def _update_discussion_channel(self):
  104. """Update the discussion channel members"""
  105. self.ensure_one()
  106. try:
  107. # Si no existe el canal, intentar crearlo
  108. if not self.channel_id:
  109. return self._create_discussion_channel()
  110. # Verificar que el canal aún existe
  111. channel = self.env['discuss.channel'].browse(self.channel_id.id)
  112. if not channel.exists():
  113. _logger.warning(f"El canal para el grupo {self.name} ya no existe, creando uno nuevo")
  114. self.write({'channel_id': False})
  115. return self._create_discussion_channel()
  116. # Obtener los IDs de los contactos de forma segura
  117. partner_ids = []
  118. for contact in self.contact_ids:
  119. if contact and contact.id:
  120. partner_ids.append(contact.id)
  121. if not partner_ids:
  122. _logger.warning(f"No hay contactos válidos para actualizar el canal del grupo {self.name}")
  123. return channel
  124. # Update channel members using add_members
  125. channel.add_members(partner_ids=partner_ids)
  126. return channel
  127. except Exception as e:
  128. _logger.error(f"Error al actualizar el canal para el grupo {self.name}: {str(e)}")
  129. return False
  130. @api.model
  131. def sync_ww_contacts_groups(self):
  132. """
  133. Sincroniza los contactos y grupos de WhatsApp Web.
  134. Solo sincroniza contactos que están dentro de grupos y valida que no se dupliquen,
  135. verificando los últimos 10 dígitos del campo mobile.
  136. """
  137. accounts = self.env['whatsapp.account'].search([])
  138. for account in accounts:
  139. try:
  140. # Obtener grupos usando el método de la cuenta
  141. groups_data = account.get_groups()
  142. if not groups_data:
  143. continue
  144. # Procesar cada grupo
  145. for group_data in groups_data:
  146. group_id = group_data.get('id').get('_serialized')
  147. group_name = group_data.get('name', 'Sin nombre')
  148. # Buscar o crear grupo
  149. group = self.search([
  150. ('whatsapp_web_id', '=', group_id),
  151. ('whatsapp_account_id', '=', account.id)
  152. ], limit=1)
  153. if not group:
  154. group = self.create({
  155. 'name': group_name,
  156. 'whatsapp_web_id': group_id,
  157. 'whatsapp_account_id': account.id
  158. })
  159. # Create discussion channel for new group
  160. group._create_discussion_channel()
  161. else:
  162. # Actualizar nombre del grupo si cambió
  163. if group.name != group_name:
  164. group.write({'name': group_name})
  165. # Actualizar nombre del canal si existe
  166. if group.channel_id:
  167. group.channel_id.write({'name': f"📱 {group_name}"})
  168. # Procesar participantes del grupo
  169. participants = group_data.get('members', [])
  170. contact_ids = []
  171. for participant in participants:
  172. whatsapp_web_id = participant.get('id', {}).get('_serialized')
  173. mobile = participant.get('number', '')
  174. is_admin = participant.get('isAdmin', False)
  175. is_super_admin = participant.get('isSuperAdmin', False)
  176. # Derive participant name
  177. participant_name = participant.get('name') or participant.get('pushname') or mobile
  178. # Search for existing contact
  179. contact = self.env['res.partner'].search([
  180. ('whatsapp_web_id', '=', whatsapp_web_id)
  181. ], limit=1)
  182. if not contact and mobile and len(mobile) >= 10:
  183. last_10_digits = mobile[-10:]
  184. contact = self.env['res.partner'].search([
  185. ('mobile', 'like', '%' + last_10_digits)
  186. ], limit=1)
  187. partner_vals = {
  188. 'name': participant_name,
  189. 'mobile': mobile,
  190. 'whatsapp_web_id': whatsapp_web_id,
  191. }
  192. if contact:
  193. # Update existing contact
  194. contact.write(partner_vals)
  195. else:
  196. # Create new contact
  197. contact = self.env['res.partner'].create(partner_vals)
  198. if contact:
  199. contact_ids.append(contact.id)
  200. # Actualizar contactos del grupo
  201. group.write({'contact_ids': [(6, 0, contact_ids)]})
  202. # Update discussion channel members
  203. group._update_discussion_channel()
  204. # Process messages if available
  205. messages = group_data.get('messages', [])
  206. if messages:
  207. group._process_messages(messages)
  208. except Exception as e:
  209. _logger.error("Error en la sincronización de grupos para la cuenta %s: %s", account.name, str(e))
  210. continue
  211. return True