Skip to Content
Menu
You need to be registered to interact with the community.
This question has been flagged

Need Help: Odoo 16 Lead Transfer Module - Notifications & Activity Logging Not Working


Current Situation


I have created a custom lead transfer module in Odoo 16 for transferring leads between sales team members. The basic transfer functionality works, but I'm facing issues with notifications and activity logging.


## Current Code


My current implementation:


```python

class LeadTransferWizard(models.TransientModel):

    _name = 'lead.transfer.wizard'

    _description = 'Lead Transfer Wizard'


    lead_id = fields.Many2one('crm.lead', string='Lead', required=True)

    user_id = fields.Many2one('res.users', string='Transfer To', required=True)

    note = fields.Text(string='Note')


    def action_transfer(self):

        self.ensure_one()

        lead = self.lead_id

        try:

            # Update lead

            lead.write({

                'transferred_to_user_id': lead.id,

                'res_model_id': self.env['ir.model']._get('crm.lead').id,

            })

           

            # Post note in chatter

            lead.message_post(

                body=_('Lead transferred to %s') % self.user_id.name,

                message_type='notification',

                subtype_xmlid='mail.mt_note'

            )

           

            return {

                'type': 'ir.actions.client',

                'tag': 'display_notification',

                'params': {

                    'message': _('Lead transferred successfully'),

                    'type': 'success',

                }

            }

           

        except Exception as e:

            lead.write({'transfer_lead_status': 'draft'})

            raise UserError(_('Failed to transfer lead: %s') % str(e))

```


## Issues I'm Facing


1. **Notification Problems:**

   - Users are not getting desktop notifications when leads are assigned to them

   - Need popup notifications with sound alerts

   - Want the notifications to be more visible and attention-grabbing


2. **Activity Logging Issues:**

   - Activity timestamps are not being logged properly

   - No priority system for transferred leads

   - Can't track precise transfer times


## What I Need


1. **Notification Requirements:**

   - Desktop notifications with sound

   - Browser popup notifications

   - Real-time alerts when leads are transferred

   - Notifications should include:

     * Lead name

     * Priority

     * Sender information

     * Quick action buttons (if possible)


2. **Activity Logging Requirements:**

   - Precise timestamps for all transfer actions

   - Priority-based due dates

   - Complete activity history

   - Proper tracking of all lead movements


## Technical Details


- Odoo Version: 16.0

- Modules installed:

  * CRM

  * Mail

  * Bus

- Browser: Chrome/Firefox (latest versions)


## Questions


1. What's the correct way to implement browser notifications in Odoo 16?

2. How can I add sound to the notifications?

3. What's the best approach for accurate activity timestamp logging?

4. How can I implement a priority system for transferred leads?

5. Is there a way to make notifications persistent until acknowledged?


## What I've Tried


1. Attempted to use bus.bus for notifications:

```python

self.env['bus.bus']._sendone(

    self.user_id.partner_id,

    'lead.transfer',

    {'message': 'New lead assigned'}

)

```

But this doesn't seem to trigger any notifications.


2. Tried adding sound:

```javascript

var audio = new Audio('/path/to/sound.mp3');

audio.play();

```

But couldn't get it working in the Odoo environment.


## Additional Information


- The basic lead transfer functionality works fine

- Users have appropriate access rights

- Browser notifications are enabled

- No JavaScript errors in console

- Server logs show no errors


Any help or guidance would be greatly appreciated. Thank you in advance!


Avatar
Opusti
Best Answer

My response was crafted with AI assistance, tailored to provide detailed and actionable guidance for your query.
To address the issues you're facing with notifications and activity logging in your custom Odoo 16 Lead Transfer Module, let's break down the solutions step by step. We'll cover both notifications and activity logging improvements.

1. Notification Improvements

Desktop Notifications with Sound

To implement desktop notifications with sound, you need to use Odoo's Bus (Browser Unidirectional Server) system and JavaScript for handling notifications on the client side.

Step 1: Send Notification via Bus

Update your action_transfer method to send a notification via the Bus system:

python   Copy

def action_transfer(self):
    self.ensure_one()
    lead = self.lead_id
    try:
        # Update lead
        lead.write({
            'user_id': self.user_id.id,  # Assign lead to the new user
            'date_transferred': fields.Datetime.now(),  # Log transfer time
        })

        # Post note in chatter
        lead.message_post(
            body=_('Lead transferred to %s') % self.user_id.name,
            message_type='notification',
            subtype_xmlid='mail.mt_note'
        )

        # Send Bus notification
        notification = {
            'type': 'lead_transfer',
            'lead_name': lead.name,
            'priority': lead.priority,
            'sender': self.env.user.name,
            'message': _('Lead %s has been transferred to you.') % lead.name,
        }
        self.env['bus.bus']._sendone(
            self.user_id.partner_id,
            'lead.transfer.notification',
            notification
        )

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'message': _('Lead transferred successfully'),
                'type': 'success',
            }
        }

    except Exception as e:
        lead.write({'transfer_lead_status': 'draft'})
        raise UserError(_('Failed to transfer lead: %s') % str(e))
Step 2: Handle Notification in JavaScript

Add JavaScript to handle the Bus notification and display it as a desktop notification with sound.

  1. Create a new JavaScript file (e.g., lead_transfer_notification.js) in your module's static/src/js/ directory.
  2. Add the following code:

javascript  Copy

odoo.define('lead_transfer.notification', function (require) {
    "use strict";

    var Bus = require('bus.bus');
    var Notification = require('web.Notification');

    // Listen for Bus notifications
    Bus.on('lead.transfer.notification', null, function (notification) {
        // Play sound
        var audio = new Audio('/lead_transfer/static/src/sounds/notification.mp3');
        audio.play();

        // Display desktop notification
        Notification.create({
            title: 'New Lead Transferred',
            message: notification.message,
            type: 'info',
            sticky: true,  // Make notification persistent
            buttons: [
                {
                    text: 'View Lead',
                    click: function () {
                        window.open(`/web#id=${notification.lead_id}&model=crm.lead&view_type=form`, '_blank');
                    }
                }
            ]
        });
    });
});
  1. Include the JavaScript file in your module's assets_backend template:

xml

Copy

<template id="assets_backend" inherit_id="web.assets_backend">
    <xpath expr="." position="inside">
        <script type="text/javascript" src="/lead_transfer/static/src/js/lead_transfer_notification.js"></script>
    </xpath>
</template>

Run HTML
  1. Add a sound file (e.g., notification.mp3) to your module's static/src/sounds/ directory.

2. Activity Logging Improvements

Precise Timestamps and Priority System

To log precise timestamps and implement a priority system, update your crm.lead model and action_transfer method.

Step 1: Add Fields to crm.lead

Add the following fields to your crm.lead model:

python  Copy

class CrmLead(models.Model):
    _inherit = 'crm.lead'

    date_transferred = fields.Datetime(string='Transfer Date', readonly=True)
    transfer_priority = fields.Selection([
        ('0', 'Low'),
        ('1', 'Medium'),
        ('2', 'High'),
    ], string='Transfer Priority', default='0')
Step 2: Update action_transfer Method

Update the action_transfer method to log the transfer timestamp and priority:

python  Copy

def action_transfer(self):
    self.ensure_one()
    lead = self.lead_id
    try:
        # Update lead
        lead.write({
            'user_id': self.user_id.id,
            'date_transferred': fields.Datetime.now(),
            'transfer_priority': self.transfer_priority,  # Add priority
        })

        # Post note in chatter
        lead.message_post(
            body=_('Lead transferred to %s with priority %s') % (self.user_id.name, dict(lead._fields['transfer_priority'].selection).get(lead.transfer_priority)),
            message_type='notification',
            subtype_xmlid='mail.mt_note'
        )

        # Send Bus notification
        notification = {
            'type': 'lead_transfer',
            'lead_name': lead.name,
            'priority': lead.transfer_priority,
            'sender': self.env.user.name,
            'message': _('Lead %s has been transferred to you with priority %s.') % (lead.name, dict(lead._fields['transfer_priority'].selection).get(lead.transfer_priority)),
        }
        self.env['bus.bus']._sendone(
            self.user_id.partner_id,
            'lead.transfer.notification',
            notification
        )

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'message': _('Lead transferred successfully'),
                'type': 'success',
            }
        }

    except Exception as e:
        lead.write({'transfer_lead_status': 'draft'})
        raise UserError(_('Failed to transfer lead: %s') % str(e))

3. Persistent Notifications

To make notifications persistent until acknowledged, use the sticky option in the Notification.create method (as shown in the JavaScript code above).

Summary

  • Notifications: Use Odoo's Bus system and JavaScript to send desktop notifications with sound.
  • Activity Logging: Add fields for timestamps and priority, and update the action_transfer method to log these details.
  • Persistent Notifications: Use the sticky option in JavaScript notifications.

Avatar
Opusti
Related Posts Odgovori Prikazi Aktivnost
1
dec. 22
3649
0
dec. 20
50
0
dec. 15
13272
2
avg. 24
6530
1
okt. 22
24251