Skip to Content
Odoo Меню
  • Увійти
  • Спробуйте це безкоштовно
  • Додатки
    Фінанси
    • Бухоблік
    • Виставлення рахунку
    • Витрати
    • Електронні таблиці (BI)
    • Документи
    • Підпис
    Продажі
    • CRM
    • Продажі
    • POS Магазин
    • POS Ресторан
    • Підписки
    • Оренда
    Веб-сайти
    • Конструктор веб-сайту
    • Електронна комерція
    • Блог
    • Форум
    • Живий чат
    • Електронне навчання
    Ланцюг поставок
    • Склад
    • Виробництво
    • PLM
    • Купівлі
    • Технічне обслуговування
    • Якість
    Кадри
    • Співробітники
    • Рекрутинг
    • Відпустки
    • Оцінювання
    • Рекомендації
    • Автотранспорт
    Маркетинг
    • Маркетинг соцмереж
    • Email-маркетинг
    • SMS-маркетинг
    • Події
    • Автом. маркетингу
    • Опитування
    Послуги
    • Проект
    • Табелі
    • Виїзне обслуговування
    • Служба підтримки
    • Планування
    • Призначення
    Продуктивність
    • Обговорення
    • Схвалення
    • IoT
    • IP-телефонія
    • База знань
    • WhatsApp
    Сторонні модулі Odoo Studio Платформа Odoo Cloud
  • Сфери
    Роздрібна торгівля
    • Книжковий магазин
    • Магазин одягу
    • Магазин меблів
    • Продуктовий магазин
    • Магазин будівельних матеріалів
    • Магазин іграшок
    Food & Hospitality
    • Бар та паб
    • Ресторан
    • Фастфуд
    • Guest House
    • Дистриб'ютор напоїв
    • Hotel
    Нерухомість
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Консалтинг
    • Бухгалтерська компанія
    • Партнер Odoo
    • Агенція маркетингу
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Меблі
    • Їжа
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Системи сонячної енергії
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Інші
    • Nonprofit Organization
    • Екологічна агенція
    • Оренда білбордів
    • Фотографія
    • Лізинг велосипедів
    • Реселлер програмного забезпечення
    Browse all Industries
  • Спільнота
    Навчання
    • Навчальний посібник
    • Документація
    • Сертифікації
    • Тренування
    • Блог
    • Подкаст
    Сприяйте Освіті
    • Програма навчання
    • Бізнес гра Scale Up!
    • Відвідайте Odoo
    Отримайте програмне забезпечення
    • Завантаження
    • Порівняйте версії
    • Релізи
    Співпрацюйте
    • Github
    • Форум
    • Події
    • Переклади
    • Стати партнером
    • Services for Partners
    • Зареєструйте вашу бухгалтерську фірму
    Отримайте послуги
    • Знайдіть партнера
    • Знайдіть бухгалтера
    • Зустріньтеся з консультантом
    • Послуги з впровадження
    • Референси клієнтів
    • Підтримка
    • Оновлення
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Отримати демо
  • Ціни
  • Допомога

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухоблік
  • Склад
  • PoS
  • Проект
  • MRP
All apps
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Допомога

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

Підписатися

Отримуйте сповіщення про активність щодо цієї публікації

Це запитання позначене
javascriptcrmpythonnotificationsodooodoo16
1 Відповісти
2178 Переглядів
Аватар
Abhishek

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!


0
Аватар
Відмінити
Аватар
Saif Sabri
Найкраща відповідь

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.

0
Аватар
Відмінити
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Реєстрація
Related Posts Відповіді Переглядів Дія
Call wizard view in js function
javascript python odoo
Аватар
Аватар
1
груд. 22
4439
TypeError: Cannot read property 'taxes_by_id' of undefined at DiscountButton.apply_discount
javascript python odoo
Аватар
0
груд. 20
50
How to call JavaScript from python function?
javascript python odoo
Аватар
0
груд. 15
14424
Display header only on the first page and footer on the last page Qweb Odoo 14
javascript python xml odoo
Аватар
Аватар
Аватар
2
серп. 24
7898
How to set default values to fields in Odoo 14
javascript python xml odoo
Аватар
Аватар
1
жовт. 22
25557
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
Open Source
  • Завантаження
  • Github
  • Runbot
  • Переклади
Послуги
  • Хостинг Odoo.sh
  • Підтримка
  • Оновлення
  • Кастомні доробки
  • Навчання
  • Знайдіть бухгалтера
  • Знайдіть партнера
  • Стати партнером
Про нас
  • Наша компанія
  • Торгові активи
  • Зв'яжіться з нами
  • Вакансії
  • Події
  • Подкаст
  • Блог
  • Клієнти
  • Юридичні документи • Конфіденційність
  • Безпека
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo - це набір програм для роботи з відкритим кодом, які охоплюють всі ваші потреби компанії: CRM, електронна комерція, бухгалтерський облік, склад, точка продажу, управління проектами тощо.

Унікальна пропозиція Odoo - це одночасно дуже проста у використанні та повністю інтегрована.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now