Перейти к содержимому
Odoo Меню
  • Войти
  • Попробовать бесплатно
  • Модули
    Финансы
    • Бухгалтерия
    • Выставление счетов
    • Расходы
    • Таблицы
    • Документооборот
    • Подпись
    Продажи
    • CRM
    • Продажи
    • POS Магазин
    • POS Ресторан
    • Подписки
    • Аренда
    Вебсайты
    • Конструктор вебсайтов
    • eCommerce
    • Блог
    • Форум
    • Онлайн-чат
    • Электронное обучение
    Логистика
    • Склад
    • Производство
    • PLM
    • Закупки
    • Обслуживание
    • Качество
    Отдел кадров
    • Сотрудники
    • Подбор персонала
    • Отпуска
    • Оценка персонала
    • Реферальная программа
    • Автопарк
    Маркетинг
    • SMM
    • E-mail рассылки
    • СМС рассылки
    • Мероприятия
    • Автоматизация маркетинга
    • Опросы
    Услуги
    • Проекты
    • Табели
    • Выездной сервис
    • Поддержка
    • Планирование
    • Встречи
    Продуктивность
    • Обсуждения
    • Согласование
    • IoT
    • VoIP-телефония
    • Knowledge
    • WhatsApp
    Сторонние приложения Модуль Студия Odoo Платформа Odoo Cloud
  • Индустрии
    Розничная торговля
    • Книжный магазин
    • Магазин одежды
    • Мебельный магазин
    • Продуктовый магазин
    • Строительный магазин
    • Магазин игрушек
    Гостинично-ресторанный бизнес
    • Бар и паб
    • Ресторан
    • Фастфуд
    • Гостевой дом
    • Дистрибьютор напитков
    • Отель
    Недвижимость
    • Агентство недвижимости
    • Архитектурное бюро
    • Строительство
    • Управление недвижимостью
    • Ландшафтный дизайн
    • Товарищество собственников жилья
    Консалтинг
    • Бухгалтерская фирма
    • Партнер Odoo
    • Маркетинговое агентство
    • Юридическая фирма
    • Подбор персонала
    • Аудиторское бюро
    Производство
    • Текстиль
    • Металл
    • Мебель
    • Продукты питания
    • Пивоварня
    • Корпоративные сувениры
    Здоровье и фитнес
    • Спортивный комплекс
    • Магазин оптики
    • Фитнес-клуб
    • Велнес-центр
    • Аптека
    • Салон красоты
    Услуги
    • Специалист по бытовым услугам
    • Продажа и обслуживание IT-оборудования
    • Солнечные энергосистемы
    • Производство обуви
    • Клининг
    • Системы ОВКВ
    Прочее
    • Некоммерческая организация
    • Консалтинг в сфере устойчивого развития
    • Аренда рекламных щитов
    • Бизнес по фотосъемке
    • Прокат велосипедов
    • Реселлер программного обеспечения
    Все индустрии
  • Community
    Обучение
    • Видео уроки
    • Документация
    • Сертификация
    • Тренинг
    • Блог
    • Подкаст
    Образование и развитие
    • Образовательная программа
    • Деловая игра Scale Up!
    • Экскурсия в офис Odoo
    ПО
    • Скачать
    • Сравнить версии
    • Релизы
    Сотрудничество
    • Github
    • Форум
    • Мероприятия
    • Перевод
    • Стать партнером
    • Услуги для партнеров
    • Зарегистрировать бухгалтерскую фирму
    Услуги
    • Найти партнера
    • Найти бухгалтера
    • Встреча с экспертом
    • Услуги по внедрению
    • Отзывы клиентов
    • Поддержка
    • Обновления
    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
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Помощь

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

Подписаться

Получайте уведомления о появлении активности в этом посте

Этот вопрос был отмечен
javascriptcrmpythonnotificationsodooodoo16
1 Ответить
2185 Представления
Аватар
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
Аватар
Отменить
Не оставайтесь в стороне – присоединяйтесь к обсуждению!

Создайте аккаунт сегодня, чтобы получить доступ к эксклюзивным функциям и стать частью нашего замечательного сообщества!

Регистрация
Похожие посты Ответы Просмотры Активность
Call wizard view in js function
javascript python odoo
Аватар
Аватар
1
дек. 22
4450
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
14443
Display header only on the first page and footer on the last page Qweb Odoo 14
javascript python xml odoo
Аватар
Аватар
Аватар
2
авг. 24
7913
How to set default values to fields in Odoo 14
javascript python xml odoo
Аватар
Аватар
1
окт. 22
25562
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • Github
  • Runbot
  • Перевод
Услуги
  • Хостинг Odoo.sh
  • Поддержка
  • Обновление
  • Индивидуальные решения по доработке
  • Образование
  • Найти бухгалтера
  • Найти партнера
  • Стать партнером
О нас
  • Наша компания
  • Активы бренда
  • Cвяжитесь с нами
  • Вакансии
  • Мероприятия
  • Подкаст
  • Блог
  • Клиенты
  • Правовые документы • Конфиденциальность
  • Безопасность
الْعَرَبيّة 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, E-commerce, Бухгалтерия, Склад, POS, управление проектами и др.

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