Enable Dark Mode!
how-to-customize-the-odoo-20-point-of-sale-frontend-with-owl-3-plugins.jpg
By: Fathima Mazlin AM

How to Customize the Odoo 20 Point of Sale Frontend with OWL 3 Plugins

Technical Odoo 20 POS

The Odoo POS frontend can be created using OWL. In Odoo 20, new plugins are added to manage the POS frontend and share data/logic using OWL 3.

In this blog, we will understand how to make changes to the POS frontend using OWL 3 plugins. We will understand the structure of POS and default plugins and create new custom buttons and screens. We will also learn how to patch POS models and add our code inside the point_of_sale._assets_pos bundle, and finally we will test our changes using Hoot.

What actually changed with Owl 3?

Owl 2 plugins are accessible via this.env.services or via the useService() hook. In Owl 3, there is no longer this.env. Plugins are classes derived from Plugin.

Example:

import { Component, Plugin, signal, usePlugin } from "@odoo/owl";
class CounterPlugin extends Plugin {
    count = signal(0);
    increment() {
        this.count.set(this.count() + 1);
    }
}
class CounterButton extends Component {
    static template = "my_module.CounterButton";
    counter = usePlugin(CounterPlugin);
}

CounterPlugin holds a number, count, that starts at 0, and increment() adds 1 to it. CounterButton gets the plugin with counter = usePlugin(CounterPlugin), so it can read the count and call increment(). Owl creates only one instance of the plugin, so every component that uses it sees and updates the same number.

The POS app structure

All the POS frontend code lives in addons/point_of_sale/static/src/app/. In Odoo 20, the folder is split by responsibility rather than by technology:

  • Components are reusable pieces like the navbar and the pop-ups.
  • Screens hold the full screens: product, payment, ticket, and so on. The product screen has its own control_buttons folder, and it’s one we’ll extend.
  • Models hold the frontend models (PosOrder, PosOrderline, etc.) and the related-models machinery that connects them.
  • Plugins hold the plugins that replace what used to be services. The POS plugin set has three parts that work together.

pos_data_plugin - Handling POS data

The pos_data_plugin is responsible for loading the required POS data from the Odoo backend to the browser.

pos_router_plugin – Navigation between pages

Used to route between different screens in the Point of Sale. These include the product screen, payments screen, and receipts. Each screen must be added into the pos_pages registry.

import { registry } from "@web/core/registry";
import { MyScreen } from "./my_screen";
registry.category("pos_pages").add("MyScreen", {
    name: "MyScreen",
    component: MyScreen,
    route: `/pos/ui/${odoo.pos_config_id}/my-screen`,
    params: {},
});

Name determines what the screen will be called. The component determines what will be displayed on the screen. Route determines the URL within the POS.

To navigate to this screen:

this.pos.navigate("MyScreen");

If a parameter is required on entering the screen, one can be passed in as a second parameter:

this.pos.navigate("ProductScreen", { orderUuid: order.uuid });

On the product screen, an order needs to be passed in. Here, we pass in the UUID of the order. The router essentially is a list of screens.

pos_ticket_printer_plugin - POS Ticket and Receipt Printing

Handles printing functionality within the POS. We will not customise this within this blog; however, knowing where this functionality exists in the code may be useful.

Loading files through the POS bundle

The POS does not load its code through web.assets_backend. It has its own bundle, point_of_sale._assets_pos, so your files must be listed there or the POS will never see them.

'assets': {
        'point_of_sale._assets_pos': [
            'module_name/static/src/**/*',
        ],
},

Patching a POS model

If you wish to add extra functionality to the order object, for example, a summary of order items, you can do so using patches. Patches allow additional methods to be added or overriding methods in a class. This means that for every order, this patch will be added. Adding patches to POS objects is a safe way to modify them so that modifications can be made safely even with upgrades. In this example, a patch is added to PosOrder. The patch adds a getSummary function which returns a summary of order items. This can then be displayed on our custom screen.

// static/src/utils/order_summary.js
export function summarizeLines(lines) {
    const units = lines.reduce((total, line) => total + line.qty, 0);
    return { lines: lines.length, units };
}

summarizeLines takes a list of lines, each with a quantity (qty). It counts the lines and adds up the quantities to get the total units.

// static/src/models/pos_order.js
import { patch } from "@web/core/utils/patch";
import { PosOrder } from "@point_of_sale/app/models/pos_order";
import { summarizeLines } from "@pos_order_summary/utils/order_summary";
patch(PosOrder.prototype, {
    getSummary() {
        const lines = this.lines.map((line) => ({
            name: line.getFullProductName(),
            qty: line.getQuantity(),
        }));
        return { items: lines, ...summarizeLines(lines) };
    },
});

We add a method called getSummary() to the PosOrder model. Using the patch() function from @web/core/utils/patch, we add this method to the prototype of the PosOrder class, meaning that all orders in the POS will have access to this method. Within the method, this refers to the specific order. We take each item in this.lines and create an object containing just the product name (using getFullProductName()) and quantity (using getQuantity()). We pass the array of lines into summarizeLines(). The result is then combined with the array and returned. This gives us something like { items: [ { name: 'Desk’, qty: 2 } ], lines: 1, units: 2 }. Note that items is an array of each row, and lines is simply the count.

Adding a custom screen

A POS screen is an Owl component registered in the pos_pages registry. The registry entry carries a name, the component, a route, and its params, so every page gets its own address inside the POS. Our screen shows the summary of the current order, and it also uses a small plugin to count how many times it has been opened.

// static/src/screens/order_summary_screen.js
import { Component, usePlugin } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { usePos } from "@point_of_sale/app/hooks/pos_hook";
import { SummaryHistoryPlugin } from "@pos_order_summary/plugins/summary_history_plugin";
export class OrderSummaryScreen extends Component {
    static template = "pos_order_summary.OrderSummaryScreen";
    setup() {
        this.pos = usePos();
        this.history = usePlugin(SummaryHistoryPlugin);
        this.history.markOpened();
    }
    get summary() {
        const order = this.pos.getOrder();
        return order ? order.getSummary() : { lines: 0, units: 0, items: [] };
    }
    back() {
        this.pos.navigate("ProductScreen", { orderUuid: this.pos.getOrder()?.uuid });
    }
}
registry.category("pos_pages").add("OrderSummaryScreen", {
    name: "OrderSummaryScreen",
    component: OrderSummaryScreen,
    route: `/pos/ui/${odoo.pos_config_id}/order-summary`,
    params: {},
});

And its template:

<!-- static/src/screens/order_summary_screen.xml -->
<templates id="template" xml:space="preserve">
    <t t-name="pos_order_summary.OrderSummaryScreen">
        <div class="d-flex flex-column h-100 bg-view p-3">
            <div class="d-flex align-items-center mb-3">
                <button class="btn btn-secondary me-3" t-on-click="back">Back</button>
                <h3 class="m-0">Order summary</h3>
            </div>
            <p>
                <t t-out="summary.lines"/> lines,
                <t t-out="summary.units"/> units in total
            </p>
            <p class="text-muted small">
                Summary opened: <t t-out="this.history.opened()"/> times
            </p>
            <ul class="list-group">
                <li t-foreach="summary.items" t-as="item" t-key="item_index"
                    class="list-group-item d-flex justify-content-between">
                    <span t-out="item.name"/>
                    <span t-out="item.qty"/>
                </li>
            </ul>
        </div>
    </t>
</templates>

This screen is implemented using the OrderSummaryScreen component. It references a template, loads the POS store, connects to the SummaryHistoryPlugin, and increments opened by 1. To get the summary, it requests from the current order how many items are in the order, the total quantity, and the product/quantity pairs.

How to Customize the Odoo 20 Point of Sale Frontend with OWL 3 Plugins-cybrosys

Adding a control button

The buttons under the order lines on the product screen belong to the ControlButtons component. We patch it to add an action, then extend its template to draw the button.

// static/src/overrides/control_buttons.js
import { patch } from "@web/core/utils/patch";
import { ControlButtons } from "@point_of_sale/app/screens/product_screen/control_buttons/control_buttons";
patch(ControlButtons.prototype, {
    openOrderSummary() {
        this.pos.navigate("OrderSummaryScreen");
    },
});
<!-- static/src/overrides/control_buttons.xml -->
<templates id="template" xml:space="preserve">
    <t t-inherit="point_of_sale.ControlButtons" t-inherit-mode="extension">
        <xpath expr="//button[hasclass('more-btn')]" position="before">
            <button class="btn btn-light btn-lg lh-lg flex-grow-1"
                    t-on-click="() => this.openOrderSummary()">
                <i class="fa fa-list-ul me-1"/> Summary
            </button>
        </xpath>
    </t>
</templates>

We have added the openOrderSummary() method. We have used this.pos.navigate("OrderSummaryScreen") to move to the screen that we have previously registered. In the template, we have changed the original control buttons by using t-inherit="point_of_sale.ControlButtons" and t-inherit-mode="extension". We then locate the 3 dots button using the XPath //button[hasclass('more-btn')]. By setting position="before", we have put the new Summary button before the 3 dots button; hence, in the screenshot, Summary appears next to the 3 dots. We have applied the same Bootstrap classes as the other buttons (btn btn-light btn-lg lh-lg flex-grow-1) to make it appear native. The button includes an icon (fa fa-list-ul) and the text of Summary. Lastly, when the button is clicked (t-on-click), we run the openOrderSummary() method.

How to Customize the Odoo 20 Point of Sale Frontend with OWL 3 Plugins-cybrosys

Writing Hoot tests

Hoot is Odoo’s JS test runner. Test files go in the addon’s static/tests folder; the file name must end in .test.js, and the runner page lives at /web/tests.

Add the test files to the manifest:

'assets': {
      'web.assets_unit_tests': [
       'module_name/static/tests/**/*',
   ],
},
// static/tests/order_summary.test.js
import { describe, expect, test } from "@odoo/hoot";
import { summarizeLines } from "@pos_order_summary/utils/order_summary";
import { SummaryHistoryPlugin } from "@pos_order_summary/plugins/summary_history_plugin";
describe("summarizeLines", () => {
    test("counts lines and units", () => {
        const lines = [
            { name: "Desk", qty: 2 },
            { name: "Chair", qty: 1 },
        ];
        expect(summarizeLines(lines)).toEqual({ lines: 2, units: 3 });
    });
    test("an empty order is all zeros", () => {
        expect(summarizeLines([])).toEqual({ lines: 0, units: 0 });
    });
});
describe("SummaryHistoryPlugin", () => {
    test("tracks opened count with signal", () => {
        const plugin = new SummaryHistoryPlugin();
        expect(plugin.opened()).toBe(0);
        plugin.markOpened();
        expect(plugin.opened()).toBe(1);
        plugin.markOpened();
        expect(plugin.opened()).toBe(2);
    });
});

We wrote three small Hoot tests that check our code without opening the POS. describe, test, and expect come from @odoo/hoot: describe groups related to tests, test is one scenario, and expect checks a result. The first group covers summarizeLines. One test gives it a Desk with quantity 2 and a Chair with quantity 1 and expects { lines: 2, units: 3 }. toEqual compares the contents of the objects, not whether they are the same object. The other test gives it an empty list and expects zeros, which protects the starting value of 0 in the reduce, so an empty order never causes an error. The second group covers SummaryHistoryPlugin. Its test creates the plugin with new SummaryHistoryPlugin(), checks that opened() starts at 0, calls markOpened() and checks for 1, then calls it again and checks for 2. toBe checks the exact number. These tests are quick because they never load the POS, but they only run on the web.assets_unit_tests bundle in the manifest includes the utils, plugins, and tests files. Creating a plugin directly with new depends on how Owl 3 builds plugins, so if the third test fails, look there first.

How to Customize the Odoo 20 Point of Sale Frontend with OWL 3 Plugins-cybrosys

All tests have passed. As there is a green bar and “3 tests completed” in the top section and a green 3 on the right, we know that all 3 tests have passed. Our module appears in the left sidebar with the tag @pos_order_summary (3). This has been split into 2 tests in summarizeLines and 1 test in SummaryHistoryPlugin to correspond to the 2 describe blocks in the test file. The test counts lines and units have passed with the correct values: 2 lines and 3 units. The test empty order returns all 0s has passed with values 0 and 0. The time taken for each test is shown on the right-hand side (27 ms, 29 ms, 20 ms). Other test suites such as @spreadsheet and @pos_enterprise have appeared in the sidebar, as these modules have also been installed.

The POS frontend can be customized very intuitively. However, when getting into the common logic, OWL 3 modules are used instead of services. We examined the structure of the POS application and its key modules to create a small module called pos_order_summary. This module adds a button in the PosOrder component and a new custom screen in pos_pages. All resources are loaded using the point_of_sale_assets_pos bundle, and the logic is covered with tests in Hoot. In general, it is advised to make minimal changes to the POS.

To read more about Overview of the New Frontend Framework in OWL 3 For Odoo 20, refer to our blog Overview of the New Frontend Framework in OWL 3 For Odoo 20.


Frequently Asked Questions

What changed in OWL 3 for POS plugins?

In Owl 2, plugins were accessed through this.env.services or useService(). In Owl 3, this.env is gone, and plugins are classes that extend Plugin. Components access them with usePlugin(MyPlugin), and Owl creates only one instance, so every component that uses the plugin shares the same state.

What is Hoot in Odoo 20?

Hoot is Odoo's JavaScript testing framework used to test frontend functionality. It helps developers verify JavaScript methods, plugins, and other frontend logic through automated tests.

Where can we run Hoot tests in Odoo?

Hoot tests can be accessed through the /web/tests page in Odoo. Test files must be included in the web.assets_unit_tests bundle in the module manifest to be loaded by the test runner.

Can we customize the Odoo 20 POS frontend without modifying the core code?

Yes. The POS frontend can be customized using OWL components, plugins, registries, patches, and XML template inheritance. These approaches help extend existing functionality while keeping core code modifications minimal.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



WhatsApp