website_visitor.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  2. from datetime import datetime, timedelta
  3. import json
  4. from odoo import api, Command, fields, models, _
  5. from odoo.exceptions import UserError
  6. from odoo.http import request
  7. from odoo.tools.sql import column_exists, create_column
  8. class WebsiteVisitor(models.Model):
  9. _inherit = 'website.visitor'
  10. livechat_operator_id = fields.Many2one('res.partner', compute='_compute_livechat_operator_id', store=True, string='Speaking with', index='btree_not_null')
  11. livechat_operator_name = fields.Char('Operator Name', related="livechat_operator_id.name")
  12. mail_channel_ids = fields.One2many('mail.channel', 'livechat_visitor_id',
  13. string="Visitor's livechat channels", readonly=True)
  14. session_count = fields.Integer('# Sessions', compute="_compute_session_count")
  15. def _auto_init(self):
  16. # Skip the computation of the field `livechat_operator_id` at the module installation
  17. # We can assume no livechat operator attributed to visitor if it was not installed
  18. if not column_exists(self.env.cr, "website_visitor", "livechat_operator_id"):
  19. create_column(self.env.cr, "website_visitor", "livechat_operator_id", "int4")
  20. return super()._auto_init()
  21. @api.depends('mail_channel_ids.livechat_active', 'mail_channel_ids.livechat_operator_id')
  22. def _compute_livechat_operator_id(self):
  23. results = self.env['mail.channel'].search_read(
  24. [('livechat_visitor_id', 'in', self.ids), ('livechat_active', '=', True)],
  25. ['livechat_visitor_id', 'livechat_operator_id']
  26. )
  27. visitor_operator_map = {int(result['livechat_visitor_id'][0]): int(result['livechat_operator_id'][0]) for result in results}
  28. for visitor in self:
  29. visitor.livechat_operator_id = visitor_operator_map.get(visitor.id, False)
  30. @api.depends('mail_channel_ids')
  31. def _compute_session_count(self):
  32. sessions = self.env['mail.channel'].search([('livechat_visitor_id', 'in', self.ids)])
  33. session_count = dict.fromkeys(self.ids, 0)
  34. for session in sessions.filtered(lambda c: c.message_ids):
  35. session_count[session.livechat_visitor_id.id] += 1
  36. for visitor in self:
  37. visitor.session_count = session_count.get(visitor.id, 0)
  38. def action_send_chat_request(self):
  39. """ Send a chat request to website_visitor(s).
  40. This creates a chat_request and a mail_channel with livechat active flag.
  41. But for the visitor to get the chat request, the operator still has to speak to the visitor.
  42. The visitor will receive the chat request the next time he navigates to a website page.
  43. (see _handle_webpage_dispatch for next step)"""
  44. # check if visitor is available
  45. unavailable_visitors_count = self.env['mail.channel'].search_count([('livechat_visitor_id', 'in', self.ids), ('livechat_active', '=', True)])
  46. if unavailable_visitors_count:
  47. raise UserError(_('Recipients are not available. Please refresh the page to get latest visitors status.'))
  48. # check if user is available as operator
  49. for website in self.mapped('website_id'):
  50. if not website.channel_id:
  51. raise UserError(_('No Livechat Channel allows you to send a chat request for website %s.', website.name))
  52. self.website_id.channel_id.write({'user_ids': [(4, self.env.user.id)]})
  53. # Create chat_requests and linked mail_channels
  54. mail_channel_vals_list = []
  55. for visitor in self:
  56. operator = self.env.user
  57. country = visitor.country_id
  58. visitor_name = "%s (%s)" % (visitor.display_name, country.name) if country else visitor.display_name
  59. members_to_add = [Command.link(operator.partner_id.id)]
  60. if visitor.partner_id:
  61. members_to_add.append(Command.link(visitor.partner_id.id))
  62. else:
  63. members_to_add.append(Command.link(self.env.ref('base.public_partner').id))
  64. mail_channel_vals_list.append({
  65. 'channel_partner_ids': members_to_add,
  66. 'livechat_channel_id': visitor.website_id.channel_id.id,
  67. 'livechat_operator_id': self.env.user.partner_id.id,
  68. 'channel_type': 'livechat',
  69. 'country_id': country.id,
  70. 'anonymous_name': visitor_name,
  71. 'name': ', '.join([visitor_name, operator.livechat_username if operator.livechat_username else operator.name]),
  72. 'livechat_visitor_id': visitor.id,
  73. 'livechat_active': True,
  74. })
  75. if mail_channel_vals_list:
  76. mail_channels = self.env['mail.channel'].create(mail_channel_vals_list)
  77. # Open empty chatter to allow the operator to start chatting with the visitor.
  78. channel_members = self.env['mail.channel.member'].sudo().search([
  79. ('partner_id', '=', self.env.user.partner_id.id),
  80. ('channel_id', 'in', mail_channels.ids),
  81. ])
  82. channel_members.write({
  83. 'fold_state': 'open',
  84. 'is_minimized': True,
  85. })
  86. mail_channels_info = mail_channels.channel_info()
  87. notifications = []
  88. for mail_channel_info in mail_channels_info:
  89. notifications.append([operator.partner_id, 'website_livechat.send_chat_request', mail_channel_info])
  90. self.env['bus.bus']._sendmany(notifications)
  91. def _merge_visitor(self, target):
  92. """ Copy sessions of the secondary visitors to the main partner visitor. """
  93. target.mail_channel_ids |= self.mail_channel_ids
  94. self.mail_channel_ids.channel_partner_ids = [
  95. (3, self.env.ref('base.public_partner').id),
  96. (4, target.partner_id.id),
  97. ]
  98. return super()._merge_visitor(target)
  99. def _upsert_visitor(self, access_token, force_track_values=None):
  100. visitor_id, upsert = super()._upsert_visitor(access_token, force_track_values=force_track_values)
  101. if upsert == 'inserted':
  102. visitor_sudo = self.sudo().browse(visitor_id)
  103. mail_channel_uuid = json.loads(request.httprequest.cookies.get('im_livechat_session', '{}')).get('uuid')
  104. if mail_channel_uuid:
  105. mail_channel = request.env["mail.channel"].sudo().search([("uuid", "=", mail_channel_uuid)])
  106. mail_channel.write({
  107. 'livechat_visitor_id': visitor_sudo.id,
  108. 'anonymous_name': visitor_sudo.display_name
  109. })
  110. return visitor_id, upsert