Skip to content

Unleash the Power of Odoo 18 Realtime Notifications: A Master Guide

odoo 18 realtime notifications 7

In today’s fast-paced business world, instant information is not just a luxury—it’s a necessity. From tracking sales orders to monitoring inventory levels, keeping users informed in real-time can significantly boost productivity and user satisfaction. This is where Odoo 18 Realtime Notifications come into play, transforming static applications into dynamic, responsive tools.

This guide, based on the fundamental principles of Odoo’s Bus/Longpolling example, will walk you through the process of implementing real-time notifications in your Odoo 18 environment. We’ll explore the built-in Bus/Longpolling mechanism, which enables server-initiated communication with client browsers, pushing instant updates without requiring tedious page refreshes. Say goodbye to manual refreshes and clunky cron jobs for updates; with just a few lines of Python and JavaScript, you can send instant alerts that empower your users.

Let’s dive in and revolutionize your Odoo experience.

The Indispensable Value of Real-time Notifications in Odoo 18

Imagine a scenario where a sales manager needs to know immediately when a high-value customer places an order, or an inventory manager gets an instant alert when stock levels drop critically low. Without real-time notifications, these updates would rely on periodic checks, manual refreshes, or scheduled reports – all of which introduce delays and potential missed opportunities.

Odoo 18 Realtime Notifications address these challenges head-on by offering:

  • Enhanced User Experience: Users no longer have to guess if data has changed. Notifications provide immediate feedback, making the application feel more alive and intuitive.
  • Increased Efficiency: Critical information reaches the right people at the right time, enabling faster decision-making and quicker responses to evolving situations.
  • Improved Collaboration: Teams can stay synchronized on project progress, task assignments, or customer interactions without constant communication overhead.
  • Proactive Problem Solving: Alerts about system errors, low stock, or delayed processes allow for immediate intervention, preventing minor issues from escalating.
  • Reduced Server Load (Compared to Polling): While Longpolling maintains a connection, it’s generally more efficient than traditional short-polling, where the client repeatedly asks the server for updates.

While many developers might resort to traditional methods like cron jobs for background processing or manual page refreshes to see updates, Odoo’s Bus/Longpolling is a sophisticated, efficient, and native solution for delivering instant alerts. It’s a game-changer if you’re building custom modules or dashboards.

Mastering Odoo 18 Realtime Notifications: A Step-by-Step Tutorial

Implementing real-time notifications in Odoo 18 involves both server-side (Python) and client-side (JavaScript) configurations. Follow these steps to set up your dynamic notification system.

Step 1: Understanding Odoo’s Bus/Longpolling Core

At its heart, Odoo’s Bus/Longpolling mechanism leverages the concept of a “long-lived” HTTP request. Instead of the server immediately responding to a client’s request, it holds the connection open until new data is available or a timeout occurs. When new data (a “notification”) is pushed, the server responds, and the client receives it instantly. The client then immediately re-establishes the connection, waiting for the next update.

Think of it like this: instead of repeatedly knocking on a door to ask if mail has arrived (short-polling), you send a message to the post office saying, “Send me mail immediately when it arrives, and I’ll send another request to wait for the next batch” (long-polling). This system is highly effective for delivering Odoo 18 Realtime Notifications with minimal latency.

Step 2: Setting Up Your Odoo Module

Before you start coding, ensure you have an existing Odoo module where you want to implement the notifications, or create a new one. Crucially, your module must declare a dependency on the bus module in its __manifest__.py file. This ensures that the necessary Odoo Bus functionalities are available to your module.

# your_module/__manifest__.py
{
    'name': 'My Realtime Notifications Module',
    'summary': 'Module to demonstrate Odoo 18 Realtime Notifications',
    'version': '1.0',
    'category': 'Extra Tools',
    'depends': ['base', 'bus'], # Ensure 'bus' is in your dependencies
    'data': [],
    'assets': {
        'web.assets_backend': [
            'your_module/static/src/js/realtime_notifications.js',
        ],
    },
    'installable': True,
    'application': True,
    'license': 'LGPL-3',
}

Step 3: Crafting the Server-Side Logic for Odoo 18 Realtime Notifications

The server-side implementation involves writing Python code that triggers the notification whenever a specific event occurs. This could be after a record is created, updated, a process is completed, or any other significant action.

Add the following Python code to the relevant method in your Odoo model. For instance, if you want to notify a user when a new customer is created, you might place this code within a create or write method.

# Example: In a method after creating a new customer
class ResPartner(models.Model):
    _inherit = 'res.partner'

    @api.model
    def create(self, vals):
        new_partner = super(ResPartner, self).create(vals)

        # Send a real-time notification
        # to the current logged-in user
        self.env['bus.bus']._sendone(
            self.env.user.partner_id,  # Target recipient (e.g., current user's partner_id)
            "customer_channel",  # Custom channel name
            {
                "message": f"New customer created: {new_partner.name}",
                "customer_id": new_partner.id,
                "type": "success"
            }
        )
        return new_partner

Explanation of the Python Code:

  • self.env['bus.bus']._sendone(...): This is the core method responsible for sending a single notification through the Odoo Bus.
  • self.env.user.partner_id: This specifies the target recipient. Here, we’re sending the notification to the partner associated with the currently logged-in user. You can target specific res.partner records, which represent users, customers, or even custom groups. For example, self.env.ref('base.user_admin').partner_id would send it to the administrator.
  • "customer_channel": This is a custom channel name. It acts as a topic or category for your notifications. The client-side JavaScript will need to subscribe to this exact channel to receive these specific notifications. Choose a unique and descriptive name for clarity.
  • {"message": f"New customer created: {new_partner.name}", "customer_id": new_partner.id, "type": "success"}: This is the payload – the actual data you want to send. It’s a Python dictionary, allowing you to send various pieces of information. In this example, we’re sending a message, the ID of the new customer, and a notification type. You can include any JSON-serializable data relevant to your notification.

For more information on targeting and channels, refer to the official Odoo documentation on the Bus module, which provides detailed insights into _sendone and _sendmany methods: Odoo Bus Documentation

Step 4: Implementing Client-Side Subscription and Display

The client-side (browser) needs to listen for notifications on the specified channel and then display them to the user. This is done using JavaScript.

Create a JavaScript file (e.g., realtime_notifications.js) inside your module’s static/src/js/ directory.

/** @odoo-module **/

import { registry } from '@web/core/registry';
import { useService } from '@web/core/utils/hooks';
import { effect } from "@odoo/owl";

// This is a simplified example. In a real application, you might encapsulate this
// logic within a component or a dedicated service.
const setupRealtimeNotifications = () => {
    const bus = useService("bus_service");
    const notification = useService("notification"); // Odoo's built-in notification service

    // Subscribe to the 'customer_channel'
    bus.addChannel("customer_channel");

    // Listen for incoming notifications
    effect(() => {
        bus.on("notification", null, (payload) => {
            for (let notif of payload) {
                // Check if the notification is for our specific channel
                if (notif[0] === "customer_channel") {
                    const messageData = notif[1]; // The payload from Python
                    console.log("Received Odoo 18 Realtime Notification:", messageData);

                    // Display the notification to the user using Odoo's notification service
                    notification.add(messageData.message, {
                        title: "Customer Update",
                        type: messageData.type || 'info', // Use type from payload or default to 'info'
                        sticky: false, // Notification will disappear after a few seconds
                        buttons: [
                            {
                                content: "View Customer",
                                onClick: () => {
                                    if (messageData.customer_id) {
                                        // Example: Redirect to the customer's form view
                                        const actionService = useService("action");
                                        actionService.doAction({
                                            type: 'ir.actions.act_window',
                                            res_model: 'res.partner',
                                            res_id: messageData.customer_id,
                                            views: [[false, 'form']],
                                            target: 'current',
                                            name: 'Customer Details',
                                        });
                                    }
                                },
                            },
                        ],
                    });
                }
            }
        });
    });
};

// Register the notification setup logic to run when the backend app loads
registry.category("bus_listeners").add("customer_channel_listener", setupRealtimeNotifications);

Explanation of the JavaScript Code:

  • import { registry } from '@web/core/registry'; and import { useService } from '@web/core/utils/hooks';: These lines import necessary modules from Odoo’s web client framework, specifically for registering services and using hooks in functional components (or in this case, a setup function).
  • const bus = useService("bus_service");: This line retrieves Odoo’s bus_service, which is the client-side interface for interacting with the Bus.
  • const notification = useService("notification");: This gets Odoo’s built-in notification service, which allows you to display user-friendly alerts.
  • bus.addChannel("customer_channel");: This is crucial! It tells the client to subscribe to the “customer_channel” that we defined on the server side. Without this, the client won’t receive notifications from that channel.
  • bus.on("notification", null, (payload) => { ... });: This sets up a listener for any incoming notifications on the Bus. The payload is an array of [channel_name, data] tuples.
  • if (notif[0] === "customer_channel") { ... }: Since the bus.on listener receives all notifications, it’s vital to filter them by checking notif[0] (the channel name) to ensure you’re processing notifications relevant to your logic.
  • notification.add(...): This leverages Odoo’s native notification system to display a banner-style message to the user, providing a consistent and non-intrusive way to show Odoo 18 Realtime Notifications. We can even add buttons for interactive user engagement, like navigating directly to the updated record.
  • registry.category("bus_listeners").add("customer_channel_listener", setupRealtimeNotifications);: This registers our setupRealtimeNotifications function to be called when the Odoo web client (specifically, the bus listeners category) is initialized. This ensures our subscription logic runs as soon as the user loads the Odoo backend.

Step 5: Integrating JavaScript Assets

For your Odoo module to load the new JavaScript file, you need to declare it in the assets section of your module’s __manifest__.py file. This tells Odoo to include your JavaScript when the web client loads.

# your_module/__manifest__.py (updated assets section)
{
    # ... (other manifest details)
    'assets': {
        'web.assets_backend': [
            'your_module/static/src/js/realtime_notifications.js',
        ],
    },
    # ...
}

Remember to replace your_module with the actual technical name of your Odoo module.

Step 6: Module Upgrade and Testing Your Odoo 18 Realtime Notifications

After making all these changes, you must upgrade your Odoo module.

  1. Navigate to the “Apps” menu in your Odoo instance.
  2. Remove the “Apps” filter and search for your module.
  3. Click the “Upgrade” button for your module.

Once upgraded, it’s time to test:

  1. Open your browser’s developer console (usually F12) and go to the “Console” tab to observe console.log messages.
  2. In Odoo, perform the action that triggers your Python code (e.g., create a new customer if you’ve implemented the example above).
  3. Observe the Odoo UI for the notification banner and check the browser console for the console.log output. You should see your Odoo 18 Realtime Notifications appearing instantly!

Advanced Considerations for Robust Odoo 18 Realtime Notifications

While the basic setup is straightforward, building a robust real-time notification system requires considering several advanced aspects:

  • Security and Access Control: Always ensure that notifications only reach authorized users. Before sending sensitive data, verify user permissions on the server side. Never send unencrypted or overly broad information to public channels. For instance, sending a specific document link should only be to users who have access to that document.
  • Scalability: For very high-volume applications with thousands of concurrent users and constant updates, Odoo’s default Longpolling might face limitations due to the number of open connections. In such extreme scenarios, dedicated WebSockets solutions (like integrating with external message brokers) could offer better performance. However, for most Odoo deployments, the built-in Bus/Longpolling is highly effective for Odoo 18 Realtime Notifications.
  • Error Handling and Logging: Implement comprehensive error handling in both Python and JavaScript. Log any issues with sending or receiving notifications to help debug problems. For instance, if _sendone fails, you might want to log the error. On the client side, gracefully handle cases where the notification service might be unavailable.
  • User Interface and Experience (UX): Design notifications to be informative yet non-intrusive. Consider:
    • Notification Types: Use success, warning, danger, info types appropriately.
    • Persistence: Should notifications be sticky (remain until dismissed) or disappear automatically?
    • Actionability: Can users click on a notification to navigate to the relevant record or perform an action?
    • Notification Center: For complex systems, consider a dedicated in-app notification center where users can review past alerts.
  • Cross-Version Compatibility: While this guide focuses on Odoo 18, specific implementation details, especially in JavaScript (e.g., how services are imported or components are registered), might differ slightly in older or future Odoo versions. Always consult the official Odoo documentation for your specific version.
  • Testing: Thoroughly test your notifications under various conditions: different users, different roles, high load, and network latency.

Beyond the Basics: Use Cases and Customization

The versatility of Odoo 18 Realtime Notifications extends to numerous business scenarios:

  • CRM Alerts: Instant notifications for new leads, assigned opportunities, or overdue follow-ups.
  • Inventory Management: Alerts for low stock levels, goods receipt, or stock transfers.
  • Project Management: Notifications for task assignments, status changes, or comments on project tasks.
  • Manufacturing Orders: Real-time updates on production progress or machine downtime.
  • Approval Workflows: Instant alerts when a document (e.g., expense report, leave request) is awaiting approval.
  • E-commerce: Notifying administrators of new online orders or customer inquiries.

You can customize the payload (data dictionary in _sendone) to include more complex data structures. This allows you to send not just a message, but also IDs, URLs, status codes, or even small snippets of HTML to render richer notifications on the client side.

For example, you could send a payload with more structured data:

# Server-side
self.env['bus.bus']._sendone(
    self.env.user.partner_id,
    "project_update_channel",
    {
        "title": "Project Update!",
        "message": f"Task '{task.name}' in project '{project.name}' has been marked as done.",
        "project_id": project.id,
        "task_id": task.id,
        "author": self.env.user.name,
        "timestamp": fields.Datetime.now().isoformat()
    }
)

Then, on the client side, you can parse this data to display a more interactive notification:

// Client-side adaptation
if (notif[0] === "project_update_channel") {
    const projectData = notif[1];
    notification.add(projectData.message, {
        title: projectData.title,
        type: 'info',
        buttons: [
            {
                content: "View Task",
                onClick: () => {
                    // Navigate to the task form
                    const actionService = useService("action");
                    actionService.doAction({
                        type: 'ir.actions.act_window',
                        res_model: 'project.task',
                        res_id: projectData.task_id,
                        views: [[false, 'form']],
                        target: 'current',
                    });
                },
            },
            {
                content: "View Project",
                onClick: () => {
                    // Navigate to the project form
                    const actionService = useService("action");
                    actionService.doAction({
                        type: 'ir.actions.act_window',
                        res_model: 'project.project',
                        res_id: projectData.project_id,
                        views: [[false, 'form']],
                        target: 'current',
                    });
                },
            },
        ],
    });
}

This level of customization makes Odoo 18 Realtime Notifications a truly powerful feature for building dynamic and highly interactive Odoo applications. For further learning on JavaScript in Odoo 18, check out Odoo’s Frontend Development Documentation.

Conclusion

Implementing Odoo 18 Realtime Notifications using the built-in Bus/Longpolling mechanism is a powerful way to significantly enhance user experience, streamline operations, and keep your team constantly informed. By following the step-by-step tutorial outlined above, you can effortlessly transition from static, refresh-dependent interfaces to dynamic, instantly updated applications.

The ability to push server-side events directly to the client opens up a world of possibilities for more responsive and engaging Odoo modules. Start experimenting with these capabilities today and unlock a new level of efficiency and interactivity in your Odoo 18 environment!


Discover more from teguhteja.id

Subscribe to get the latest posts sent to your email.

Leave a Reply

WP Twitter Auto Publish Powered By : XYZScripts.com