From eca7136f9c57bf201aaa832d5fea4f59d4b1ef28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jes=C3=BAs=20Alan=20Ramos=20Rodr=C3=ADguez?= Date: Sun, 12 Jul 2026 08:12:50 -0600 Subject: [PATCH] [ADD] purchase_line_sale_history: Sales history on purchase order lines Add a Sales History toggle on purchase order lines that displays, below the order lines, a year x month pivot table with the quantities of the line's product sold in posted customer invoices (credit notes subtracted). Only one line per order can be active at a time (enforced live in the form via onchange and at API level via create/write), the history is computed on the exact product variant, and the number of past years shown is configurable in the purchase settings (default: 2). --- purchase_line_sale_history/README.rst | 120 +++++ purchase_line_sale_history/__init__.py | 1 + purchase_line_sale_history/__manifest__.py | 25 + purchase_line_sale_history/i18n/es.po | 115 +++++ purchase_line_sale_history/models/__init__.py | 3 + .../models/purchase_order.py | 100 ++++ .../models/purchase_order_line.py | 38 ++ .../models/res_config_settings.py | 16 + purchase_line_sale_history/pyproject.toml | 3 + .../readme/CONFIGURE.md | 6 + .../readme/CONTRIBUTORS.md | 1 + .../readme/DESCRIPTION.md | 11 + purchase_line_sale_history/readme/ROADMAP.md | 4 + purchase_line_sale_history/readme/USAGE.md | 7 + .../static/description/index.html | 472 ++++++++++++++++++ .../purchase_order_sales_history_field.esm.js | 96 ++++ .../scss/purchase_order_sales_history.scss | 97 ++++ .../purchase_order_sales_history_field.xml | 89 ++++ purchase_line_sale_history/tests/__init__.py | 1 + .../tests/test_purchase_line_sale_history.py | 153 ++++++ .../views/purchase_order_views.xml | 31 ++ .../views/res_config_settings_views.xml | 23 + 22 files changed, 1412 insertions(+) create mode 100644 purchase_line_sale_history/README.rst create mode 100644 purchase_line_sale_history/__init__.py create mode 100644 purchase_line_sale_history/__manifest__.py create mode 100644 purchase_line_sale_history/i18n/es.po create mode 100644 purchase_line_sale_history/models/__init__.py create mode 100644 purchase_line_sale_history/models/purchase_order.py create mode 100644 purchase_line_sale_history/models/purchase_order_line.py create mode 100644 purchase_line_sale_history/models/res_config_settings.py create mode 100644 purchase_line_sale_history/pyproject.toml create mode 100644 purchase_line_sale_history/readme/CONFIGURE.md create mode 100644 purchase_line_sale_history/readme/CONTRIBUTORS.md create mode 100644 purchase_line_sale_history/readme/DESCRIPTION.md create mode 100644 purchase_line_sale_history/readme/ROADMAP.md create mode 100644 purchase_line_sale_history/readme/USAGE.md create mode 100644 purchase_line_sale_history/static/description/index.html create mode 100644 purchase_line_sale_history/static/src/js/purchase_order_sales_history_field.esm.js create mode 100644 purchase_line_sale_history/static/src/scss/purchase_order_sales_history.scss create mode 100644 purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml create mode 100644 purchase_line_sale_history/tests/__init__.py create mode 100644 purchase_line_sale_history/tests/test_purchase_line_sale_history.py create mode 100644 purchase_line_sale_history/views/purchase_order_views.xml create mode 100644 purchase_line_sale_history/views/res_config_settings_views.xml diff --git a/purchase_line_sale_history/README.rst b/purchase_line_sale_history/README.rst new file mode 100644 index 00000000000..d4c96ce9f64 --- /dev/null +++ b/purchase_line_sale_history/README.rst @@ -0,0 +1,120 @@ +.. image:: https://odoo-community.org/readme-banner-image + :target: https://odoo-community.org/get-involved?utm_source=readme + :alt: Odoo Community Association + +========================== +Purchase Line Sale History +========================== + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:5bf45f132157b7b8d23e12b4de2c626257fe9841031e31a4f59531f4b5965775 + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png + :target: https://odoo-community.org/page/development-status + :alt: Beta +.. |badge2| image:: https://img.shields.io/badge/license-LGPL--3-blue.png + :target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html + :alt: License: LGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fpurchase--workflow-lightgray.png?logo=github + :target: https://github.com/OCA/purchase-workflow/tree/19.0/purchase_line_sale_history + :alt: OCA/purchase-workflow +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/purchase-workflow-19-0/purchase-workflow-19-0-purchase_line_sale_history + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png + :target: https://runboat.odoo-community.org/builds?repo=OCA/purchase-workflow&target_branch=19.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module lets purchasers consult the sales history of a product while +filling a purchase order, without leaving the order form. + +Each purchase order line gets a *Sales History* checkbox. When checked, +a pivot table is displayed below the order lines with the quantities of +that product sold per month (columns) and year (rows), based on posted +customer invoices (credit notes are subtracted). Only one line per order +can be active at a time. + +The history is computed for the exact product variant of the line, so +different variants of the same product template are never mixed. + +**Table of contents** + +.. contents:: + :local: + +Configuration +============= + +1. Go to *Purchase > Configuration > Settings*. +2. Set *Sales History Years* to the number of past years to display in + addition to the current one (default: 2, i.e. three year rows in + total). + +A sale is any line of a posted customer invoice; quantities from +customer credit notes are subtracted. + +Usage +===== + +1. Open or create a purchase order. +2. Check the *Sales History* box on the line whose product you want to + analyze. The monthly sales pivot table appears below the order lines. +3. Check the box on another line to switch the table to that product; + the previous checkbox is unchecked automatically. +4. Future months of the current year are displayed as a dash (—), + distinct from months with zero sales. + +Known issues / Roadmap +====================== + +- Add an option to aggregate the history by product template instead of + the exact product variant. +- Consider sourcing the history from sale orders or stock moves as an + alternative to posted customer invoices. + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +------- + +* Jarsa + +Contributors +------------ + +- Jesús Alan Ramos Rodríguez + +Maintainers +----------- + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +This module is part of the `OCA/purchase-workflow `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/purchase_line_sale_history/__init__.py b/purchase_line_sale_history/__init__.py new file mode 100644 index 00000000000..0650744f6bc --- /dev/null +++ b/purchase_line_sale_history/__init__.py @@ -0,0 +1 @@ +from . import models diff --git a/purchase_line_sale_history/__manifest__.py b/purchase_line_sale_history/__manifest__.py new file mode 100644 index 00000000000..9308f39db32 --- /dev/null +++ b/purchase_line_sale_history/__manifest__.py @@ -0,0 +1,25 @@ +# Copyright 2026 Jarsa +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). +{ + "name": "Purchase Line Sale History", + "summary": "Show the sales history of a product while filling a " + "purchase order line", + "version": "19.0.1.0.0", + "category": "Purchases", + "website": "https://github.com/OCA/purchase-workflow", + "author": "Jarsa, Odoo Community Association (OCA)", + "license": "LGPL-3", + "depends": ["purchase"], + "data": [ + "views/res_config_settings_views.xml", + "views/purchase_order_views.xml", + ], + "assets": { + "web.assets_backend": [ + "purchase_line_sale_history/static/src/js/purchase_order_sales_history_field.esm.js", + "purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml", + "purchase_line_sale_history/static/src/scss/purchase_order_sales_history.scss", + ], + }, + "installable": True, +} diff --git a/purchase_line_sale_history/i18n/es.po b/purchase_line_sale_history/i18n/es.po new file mode 100644 index 00000000000..dbcb24a71e8 --- /dev/null +++ b/purchase_line_sale_history/i18n/es.po @@ -0,0 +1,115 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * purchase_line_sale_history +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 19.0+e\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2026-07-15 00:32+0000\n" +"PO-Revision-Date: 2026-07-15 00:32+0000\n" +"Last-Translator: \n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: \n" + +#. module: purchase_line_sale_history +#. odoo-javascript +#: code:addons/purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml:0 +msgid "" +"Check the Sales History box on a line to see its product's sales history." +msgstr "" +"Marca la casilla Histórico de ventas en una línea para ver el histórico de " +"ventas de su producto." + +#. module: purchase_line_sale_history +#: model:ir.model,name:purchase_line_sale_history.model_res_config_settings +msgid "Config Settings" +msgstr "Ajustes de configuración" + +#. module: purchase_line_sale_history +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_purchase_order__display_name +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_purchase_order_line__display_name +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_res_config_settings__display_name +msgid "Display Name" +msgstr "Nombre para mostrar" + +#. module: purchase_line_sale_history +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_purchase_order__id +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_purchase_order_line__id +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_res_config_settings__id +msgid "ID" +msgstr "ID" + +#. module: purchase_line_sale_history +#: model_terms:ir.ui.view,arch_db:purchase_line_sale_history.res_config_settings_view_form +msgid "" +"Number of past years, in addition to the current one, shown in the sales " +"history of a purchase order line" +msgstr "" +"Número de años anteriores, además del actual, mostrados en el histórico de " +"ventas de una línea de pedido de compra" + +#. module: purchase_line_sale_history +#: model:ir.model.fields,help:purchase_line_sale_history.field_res_config_settings__purchase_sales_history_years +msgid "" +"Number of past years, in addition to the current one, shown in the sales " +"history of a purchase order line." +msgstr "" +"Número de años anteriores, además del actual, mostrados en el histórico de " +"ventas de una línea de pedido de compra." + +#. module: purchase_line_sale_history +#: model:ir.model.fields,help:purchase_line_sale_history.field_purchase_order__sales_history_line_id +msgid "Order line whose product sales history is displayed." +msgstr "Línea del pedido cuyo histórico de ventas del producto se muestra." + +#. module: purchase_line_sale_history +#: model:ir.model,name:purchase_line_sale_history.model_purchase_order +msgid "Purchase Order" +msgstr "Pedido de compra" + +#. module: purchase_line_sale_history +#: model:ir.model,name:purchase_line_sale_history.model_purchase_order_line +msgid "Purchase Order Line" +msgstr "Línea de pedido de compra" + +#. module: purchase_line_sale_history +#. odoo-javascript +#: code:addons/purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml:0 +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_purchase_order_line__show_sales_history +msgid "Sales History" +msgstr "Histórico de ventas" + +#. module: purchase_line_sale_history +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_purchase_order__sales_history_line_id +msgid "Sales History Line" +msgstr "Línea del histórico de ventas" + +#. module: purchase_line_sale_history +#: model:ir.model.fields,field_description:purchase_line_sale_history.field_res_config_settings__purchase_sales_history_years +msgid "Sales History Years" +msgstr "Años del histórico de ventas" + +#. module: purchase_line_sale_history +#: model:ir.model.fields,help:purchase_line_sale_history.field_purchase_order_line__show_sales_history +msgid "" +"Show the sales history of this line's product below the order lines. Only " +"one line per order can be active at a time." +msgstr "" +"Muestra el histórico de ventas del producto de esta línea debajo de las " +"líneas del pedido. Solo una línea por pedido puede estar activa a la vez." + +#. module: purchase_line_sale_history +#. odoo-javascript +#: code:addons/purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml:0 +msgid "Total" +msgstr "Total" + +#. module: purchase_line_sale_history +#. odoo-javascript +#: code:addons/purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml:0 +msgid "Year" +msgstr "Año" diff --git a/purchase_line_sale_history/models/__init__.py b/purchase_line_sale_history/models/__init__.py new file mode 100644 index 00000000000..3cf91acfc7a --- /dev/null +++ b/purchase_line_sale_history/models/__init__.py @@ -0,0 +1,3 @@ +from . import purchase_order +from . import purchase_order_line +from . import res_config_settings diff --git a/purchase_line_sale_history/models/purchase_order.py b/purchase_line_sale_history/models/purchase_order.py new file mode 100644 index 00000000000..d14f232cc20 --- /dev/null +++ b/purchase_line_sale_history/models/purchase_order.py @@ -0,0 +1,100 @@ +# Copyright 2026 Jarsa +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). + +from babel.dates import get_month_names + +from odoo import api, fields, models +from odoo.tools.misc import babel_locale_parse, get_lang + + +class PurchaseOrder(models.Model): + _inherit = "purchase.order" + + sales_history_line_id = fields.Many2one( + comodel_name="purchase.order.line", + string="Sales History Line", + copy=False, + help="Order line whose product sales history is displayed.", + ) + sales_history_data = fields.Json( + compute="_compute_sales_history_data", + export_string_translation=False, + ) + + @api.onchange("order_line") + def _onchange_order_line_sales_history(self): + # Line-level onchanges cannot reach sibling lines, so the live + # exclusivity is handled here. sales_history_line_id round-trips + # through the client between onchange calls, so it reliably tells + # which line was active before this change, even before saving. + active = self.order_line.filtered("show_sales_history") + prev = self.sales_history_line_id + # In the onchange environment the lines are NewId records while the + # many2one holds the real id, so compare through _origin. + new = ( + active.filtered(lambda line: line != prev and line._origin != prev)[-1:] + or active[:1] + ) + (active - new).show_sales_history = False + self.sales_history_line_id = new + + @api.depends("sales_history_line_id.product_id", "date_order") + def _compute_sales_history_data(self): + years_back = int( + self.env["ir.config_parameter"] + .sudo() + .get_param("purchase_line_sale_history.years_back", 2) + ) + month_names = get_month_names( + "abbreviated", locale=babel_locale_parse(get_lang(self.env).code) + ) + months = [month_names[month] for month in range(1, 13)] + for order in self: + line = order.sales_history_line_id + if not line.product_id: + order.sales_history_data = False + continue + order_date = order.date_order or fields.Datetime.now() + current_year = order_date.year + years = [current_year - offset for offset in range(years_back + 1)] + qty_by_month = order._get_sales_history_quantities( + line.product_id, years[-1], current_year + ) + data = {} + for year in years: + row = [] + for month in range(1, 13): + qty = qty_by_month.get((year, month)) + if qty is None: + is_future = year == current_year and month > order_date.month + row.append(None if is_future else 0) + else: + row.append(round(qty, 2)) + data[str(year)] = row + order.sales_history_data = { + "product_name": line.product_id.display_name, + "years": years, + "months": months, + "data": data, + } + + def _get_sales_history_quantities(self, product, year_from, year_to): + """Return {(year, month): qty} of posted customer invoice quantities + for ``product``, with credit notes subtracted.""" + base_domain = [ + ("product_id", "=", product.id), + ("parent_state", "=", "posted"), + ("date", ">=", fields.Date.to_date(f"{year_from}-01-01")), + ("date", "<=", fields.Date.to_date(f"{year_to}-12-31")), + ] + qty_by_month = {} + for move_type, sign in (("out_invoice", 1), ("out_refund", -1)): + groups = self.env["account.move.line"]._read_group( + base_domain + [("move_id.move_type", "=", move_type)], + groupby=["date:month"], + aggregates=["quantity:sum"], + ) + for month_start, qty in groups: + key = (month_start.year, month_start.month) + qty_by_month[key] = qty_by_month.get(key, 0.0) + sign * (qty or 0.0) + return qty_by_month diff --git a/purchase_line_sale_history/models/purchase_order_line.py b/purchase_line_sale_history/models/purchase_order_line.py new file mode 100644 index 00000000000..e42471f46f7 --- /dev/null +++ b/purchase_line_sale_history/models/purchase_order_line.py @@ -0,0 +1,38 @@ +# Copyright 2026 Jarsa +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). + +from odoo import api, fields, models + + +class PurchaseOrderLine(models.Model): + _inherit = "purchase.order.line" + + show_sales_history = fields.Boolean( + string="Sales History", + copy=False, + help="Show the sales history of this line's product below the " + "order lines. Only one line per order can be active at a time.", + ) + + @api.model_create_multi + def create(self, vals_list): + lines = super().create(vals_list) + lines.filtered("show_sales_history")[-1:]._activate_sales_history() + return lines + + def write(self, vals): + res = super().write(vals) + if vals.get("show_sales_history"): + self[-1:]._activate_sales_history() + elif "show_sales_history" in vals: + self.order_id.filtered( + lambda order: order.sales_history_line_id in self + ).sales_history_line_id = False + return res + + def _activate_sales_history(self): + for line in self: + (line.order_id.order_line - line).filtered( + "show_sales_history" + ).show_sales_history = False + line.order_id.sales_history_line_id = line diff --git a/purchase_line_sale_history/models/res_config_settings.py b/purchase_line_sale_history/models/res_config_settings.py new file mode 100644 index 00000000000..dd40ef026f1 --- /dev/null +++ b/purchase_line_sale_history/models/res_config_settings.py @@ -0,0 +1,16 @@ +# Copyright 2026 Jarsa +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). + +from odoo import fields, models + + +class ResConfigSettings(models.TransientModel): + _inherit = "res.config.settings" + + purchase_sales_history_years = fields.Integer( + string="Sales History Years", + config_parameter="purchase_line_sale_history.years_back", + default=2, + help="Number of past years, in addition to the current one, shown " + "in the sales history of a purchase order line.", + ) diff --git a/purchase_line_sale_history/pyproject.toml b/purchase_line_sale_history/pyproject.toml new file mode 100644 index 00000000000..4231d0cccb3 --- /dev/null +++ b/purchase_line_sale_history/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/purchase_line_sale_history/readme/CONFIGURE.md b/purchase_line_sale_history/readme/CONFIGURE.md new file mode 100644 index 00000000000..24b29967c70 --- /dev/null +++ b/purchase_line_sale_history/readme/CONFIGURE.md @@ -0,0 +1,6 @@ +1. Go to *Purchase > Configuration > Settings*. +2. Set *Sales History Years* to the number of past years to display in + addition to the current one (default: 2, i.e. three year rows in total). + +A sale is any line of a posted customer invoice; quantities from customer +credit notes are subtracted. diff --git a/purchase_line_sale_history/readme/CONTRIBUTORS.md b/purchase_line_sale_history/readme/CONTRIBUTORS.md new file mode 100644 index 00000000000..01242e3685d --- /dev/null +++ b/purchase_line_sale_history/readme/CONTRIBUTORS.md @@ -0,0 +1 @@ +- Jesús Alan Ramos Rodríguez \ diff --git a/purchase_line_sale_history/readme/DESCRIPTION.md b/purchase_line_sale_history/readme/DESCRIPTION.md new file mode 100644 index 00000000000..3bbd7f10883 --- /dev/null +++ b/purchase_line_sale_history/readme/DESCRIPTION.md @@ -0,0 +1,11 @@ +This module lets purchasers consult the sales history of a product while +filling a purchase order, without leaving the order form. + +Each purchase order line gets a *Sales History* checkbox. When checked, a +pivot table is displayed below the order lines with the quantities of that +product sold per month (columns) and year (rows), based on posted customer +invoices (credit notes are subtracted). Only one line per order can be +active at a time. + +The history is computed for the exact product variant of the line, so +different variants of the same product template are never mixed. diff --git a/purchase_line_sale_history/readme/ROADMAP.md b/purchase_line_sale_history/readme/ROADMAP.md new file mode 100644 index 00000000000..a7fcdd0a2d8 --- /dev/null +++ b/purchase_line_sale_history/readme/ROADMAP.md @@ -0,0 +1,4 @@ +- Add an option to aggregate the history by product template instead of + the exact product variant. +- Consider sourcing the history from sale orders or stock moves as an + alternative to posted customer invoices. diff --git a/purchase_line_sale_history/readme/USAGE.md b/purchase_line_sale_history/readme/USAGE.md new file mode 100644 index 00000000000..daffb51d8b6 --- /dev/null +++ b/purchase_line_sale_history/readme/USAGE.md @@ -0,0 +1,7 @@ +1. Open or create a purchase order. +2. Check the *Sales History* box on the line whose product you want to + analyze. The monthly sales pivot table appears below the order lines. +3. Check the box on another line to switch the table to that product; the + previous checkbox is unchecked automatically. +4. Future months of the current year are displayed as a dash (—), + distinct from months with zero sales. diff --git a/purchase_line_sale_history/static/description/index.html b/purchase_line_sale_history/static/description/index.html new file mode 100644 index 00000000000..dfea70c0611 --- /dev/null +++ b/purchase_line_sale_history/static/description/index.html @@ -0,0 +1,472 @@ + + + + + +README.rst + + + +
+ + + +Odoo Community Association + +
+

Purchase Line Sale History

+ +

Beta License: LGPL-3 OCA/purchase-workflow Translate me on Weblate Try me on Runboat

+

This module lets purchasers consult the sales history of a product while +filling a purchase order, without leaving the order form.

+

Each purchase order line gets a Sales History checkbox. When checked, +a pivot table is displayed below the order lines with the quantities of +that product sold per month (columns) and year (rows), based on posted +customer invoices (credit notes are subtracted). Only one line per order +can be active at a time.

+

The history is computed for the exact product variant of the line, so +different variants of the same product template are never mixed.

+

Table of contents

+ +
+

Configuration

+
    +
  1. Go to Purchase > Configuration > Settings.
  2. +
  3. Set Sales History Years to the number of past years to display in +addition to the current one (default: 2, i.e. three year rows in +total).
  4. +
+

A sale is any line of a posted customer invoice; quantities from +customer credit notes are subtracted.

+
+
+

Usage

+
    +
  1. Open or create a purchase order.
  2. +
  3. Check the Sales History box on the line whose product you want to +analyze. The monthly sales pivot table appears below the order lines.
  4. +
  5. Check the box on another line to switch the table to that product; +the previous checkbox is unchecked automatically.
  6. +
  7. Future months of the current year are displayed as a dash (—), +distinct from months with zero sales.
  8. +
+
+
+

Known issues / Roadmap

+
    +
  • Add an option to aggregate the history by product template instead of +the exact product variant.
  • +
  • Consider sourcing the history from sale orders or stock moves as an +alternative to posted customer invoices.
  • +
+
+
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • Jarsa
  • +
+
+
+

Contributors

+ +
+
+

Maintainers

+

This module is maintained by the OCA.

+ +Odoo Community Association + +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

This module is part of the OCA/purchase-workflow project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+
+ + diff --git a/purchase_line_sale_history/static/src/js/purchase_order_sales_history_field.esm.js b/purchase_line_sale_history/static/src/js/purchase_order_sales_history_field.esm.js new file mode 100644 index 00000000000..25f9762f630 --- /dev/null +++ b/purchase_line_sale_history/static/src/js/purchase_order_sales_history_field.esm.js @@ -0,0 +1,96 @@ +import {Component} from "@odoo/owl"; +import {registry} from "@web/core/registry"; +import {standardFieldProps} from "@web/views/fields/standard_field_props"; + +/** + * Renders purchase.order.sales_history_data (Json field) as a + * year x month pivot table. Expected shape: + * { + * "product_name": "...", + * "years": [2026, 2025, 2024], + * "months": ["Jan", "Feb", ..., "Dec"], + * "data": {"2026": [12, 0, 5, null, ...], "2025": [...], ...}, + * } + * `null` means "no data yet" (future month of the current year); + * distinct from 0, which means "no sales that month". + */ +export class PurchaseSalesHistoryField extends Component { + static template = "purchase_line_sale_history.SalesHistoryField"; + static props = {...standardFieldProps}; + + get historyData() { + const raw = this.props.record.data[this.props.name]; + if (!raw) { + return null; + } + return typeof raw === "string" ? JSON.parse(raw) : raw; + } + + get years() { + return this.historyData?.years ?? []; + } + + get months() { + return this.historyData?.months ?? []; + } + + /** 0-based index (Jan=0) of the current month, to highlight the header. */ + get currentMonthIndex() { + return new Date().getMonth(); + } + + valueFor(year, monthIndex) { + const row = this.historyData?.data?.[year]; + return row ? row[monthIndex] : null; + } + + /** Max value across the whole pivot, used to scale heatmap intensity. */ + get maxValue() { + // Start at 1 to avoid division by zero. + let max = 1; + for (const year of this.years) { + for (const v of this.historyData?.data?.[year] ?? []) { + if (v !== null && v > max) { + max = v; + } + } + } + return max; + } + + /** 0..1 background intensity for a given cell, relative to maxValue. */ + intensityFor(year, monthIndex) { + const v = this.valueFor(year, monthIndex); + if (v === null) { + return 0; + } + return Math.min(1, v / this.maxValue); + } + + cellStyle(year, monthIndex) { + const intensity = this.intensityFor(year, monthIndex); + return `background-color: rgba(113, 75, 103, ${(intensity * 0.16).toFixed(3)});`; + } + + rowTotal(year) { + const row = this.historyData?.data?.[year] ?? []; + return row.reduce((acc, v) => acc + (v ?? 0), 0); + } + + colTotal(monthIndex) { + return this.years.reduce( + (acc, year) => acc + (this.valueFor(year, monthIndex) ?? 0), + 0 + ); + } + + get grandTotal() { + return this.years.reduce((acc, year) => acc + this.rowTotal(year), 0); + } +} + +registry.category("fields").add("purchase_sales_history", { + component: PurchaseSalesHistoryField, + // Only makes sense as a readonly/inline widget, never in edition mode. + supportedTypes: ["json", "jsonb"], +}); diff --git a/purchase_line_sale_history/static/src/scss/purchase_order_sales_history.scss b/purchase_line_sale_history/static/src/scss/purchase_order_sales_history.scss new file mode 100644 index 00000000000..e04aff5fe00 --- /dev/null +++ b/purchase_line_sale_history/static/src/scss/purchase_order_sales_history.scss @@ -0,0 +1,97 @@ +// Copyright 2026 Jarsa +// License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). +// Odoo backend palette reference: primary #714B67 + +.o_purchase_sales_history { + margin: 4px 0 16px; + border: 1px solid $border-color; + border-radius: 4px; + background-color: $o-view-background-color; + + .o_purchase_sales_history_header { + display: flex; + flex-direction: column; + padding: 8px 12px 4px; + + strong { + font-size: 0.9rem; + } + } + + .o_purchase_sales_history_scroll { + overflow-x: auto; + padding: 0 12px 12px; + } + + .o_purchase_sales_history_table { + font-size: 0.75rem; + border-collapse: collapse; + margin-bottom: 0; + + th, + td { + white-space: nowrap; + padding: 4px 10px; + } + + thead th { + color: $text-muted; + font-weight: 500; + border-bottom: 1px solid $border-color; + } + + // Fixed "Year" column: solid background required so it never blends + // with the data cells scrolling behind it. Do NOT use a + // transparent/inherited background here. + .o_purchase_sales_history_sticky_col { + position: sticky; + left: 0; + z-index: 2; + font-weight: 500; + background-color: $o-view-background-color; + // Subtle right-edge shadow, only visible once content scrolls + // underneath — reinforces the "frozen column" affordance. + box-shadow: 2px 0 4px -1px rgba(0, 0, 0, 0.12); + } + + thead .o_purchase_sales_history_sticky_col { + background-color: darken($o-view-background-color, 3%); + } + + tbody .o_purchase_sales_history_sticky_col.o_row_even { + background-color: darken($o-view-background-color, 4%); + } + + tbody .o_purchase_sales_history_sticky_col.o_row_odd { + background-color: darken($o-view-background-color, 1%); + } + + tfoot .o_purchase_sales_history_sticky_col { + background-color: darken($o-view-background-color, 3%); + } + + tbody tr.o_row_odd { + background-color: $o-view-background-color; + } + + .o_purchase_sales_history_current_month { + color: $o-brand-primary; + } + + .o_purchase_sales_history_cell { + display: inline-block; + min-width: 100%; + border-radius: 3px; + padding: 0 4px; + } + + .o_purchase_sales_history_total { + border-left: 1px solid $border-color; + font-weight: 600; + } + + tfoot .o_purchase_sales_history_total { + color: $o-brand-primary; + } + } +} diff --git a/purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml b/purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml new file mode 100644 index 00000000000..cc222cc0bde --- /dev/null +++ b/purchase_line_sale_history/static/src/xml/purchase_order_sales_history_field.xml @@ -0,0 +1,89 @@ + + + + +
+
+ + Sales History + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Year + + Total
+ + + + + + + +
+ Total + + + +
+
+
+
+ Check the Sales History box on a line to see its product's sales history. +
+
+ +
diff --git a/purchase_line_sale_history/tests/__init__.py b/purchase_line_sale_history/tests/__init__.py new file mode 100644 index 00000000000..056c30bb126 --- /dev/null +++ b/purchase_line_sale_history/tests/__init__.py @@ -0,0 +1 @@ +from . import test_purchase_line_sale_history diff --git a/purchase_line_sale_history/tests/test_purchase_line_sale_history.py b/purchase_line_sale_history/tests/test_purchase_line_sale_history.py new file mode 100644 index 00000000000..98a8961da06 --- /dev/null +++ b/purchase_line_sale_history/tests/test_purchase_line_sale_history.py @@ -0,0 +1,153 @@ +# Copyright 2026 Jarsa +# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). + +from odoo import Command +from odoo.tests import Form, tagged + +from odoo.addons.account.tests.common import AccountTestInvoicingCommon + + +@tagged("post_install", "-at_install") +class TestPurchaseLineSaleHistory(AccountTestInvoicingCommon): + @classmethod + def setUpClass(cls): + super().setUpClass() + attribute = cls.env["product.attribute"].create( + { + "name": "Size", + "value_ids": [ + Command.create({"name": "S"}), + Command.create({"name": "L"}), + ], + } + ) + template = cls.env["product.template"].create( + { + "name": "Test History Product", + "attribute_line_ids": [ + Command.create( + { + "attribute_id": attribute.id, + "value_ids": [Command.set(attribute.value_ids.ids)], + } + ) + ], + } + ) + cls.variant_1, cls.variant_2 = template.product_variant_ids + cls.order = cls.env["purchase.order"].create( + { + "partner_id": cls.partner_a.id, + "date_order": "2026-07-10 10:00:00", + "order_line": [ + Command.create({"product_id": cls.variant_1.id, "product_qty": 1}), + Command.create({"product_id": cls.variant_2.id, "product_qty": 1}), + ], + } + ) + cls.line_1, cls.line_2 = cls.order.order_line + + @classmethod + def _create_invoice( + cls, product, invoice_date, qty, move_type="out_invoice", post=True + ): + move = cls.env["account.move"].create( + { + "move_type": move_type, + "partner_id": cls.partner_a.id, + "invoice_date": invoice_date, + "invoice_line_ids": [ + Command.create( + { + "product_id": product.id, + "quantity": qty, + "price_unit": 10.0, + } + ) + ], + } + ) + if post: + move.action_post() + return move + + def _history(self): + self.order.invalidate_recordset(["sales_history_data"]) + return self.order.sales_history_data + + def test_only_one_checkbox_active(self): + self.line_1.show_sales_history = True + self.line_2.show_sales_history = True + self.assertFalse(self.line_1.show_sales_history) + self.assertTrue(self.line_2.show_sales_history) + + def test_only_one_checkbox_active_form(self): + with Form(self.order) as order_form: + with order_form.order_line.edit(0) as line: + line.show_sales_history = True + with order_form.order_line.edit(1) as line: + line.show_sales_history = True + # The exclusivity must be applied live, before saving. + with order_form.order_line.edit(0) as line: + self.assertFalse(line.show_sales_history) + self.assertFalse(self.line_1.show_sales_history) + self.assertTrue(self.line_2.show_sales_history) + self.assertEqual(self.order.sales_history_line_id, self.line_2) + + def test_sales_history_hidden_without_active_line(self): + self.assertFalse(self.order.sales_history_data) + + def test_sales_history_data_computation(self): + self._create_invoice(self.variant_1, "2026-02-14", 5) + self._create_invoice(self.variant_1, "2026-02-20", 2, move_type="out_refund") + self._create_invoice(self.variant_1, "2025-11-03", 3) + self.line_1.show_sales_history = True + history = self._history() + self.assertEqual(history["product_name"], self.variant_1.display_name) + self.assertEqual(history["years"], [2026, 2025, 2024]) + self.assertEqual(history["data"]["2026"][1], 3) # Feb: 5 - 2 refund + self.assertEqual(history["data"]["2025"][10], 3) # Nov 2025 + self.assertEqual(history["data"]["2026"][0], 0) # Jan: no sales + # Months after the order date (July) have no data yet. + self.assertIsNone(history["data"]["2026"][11]) + self.assertEqual(history["data"]["2024"], [0] * 12) + + def test_sales_history_excludes_draft_invoices(self): + self._create_invoice(self.variant_1, "2026-03-10", 7, post=False) + self.line_1.show_sales_history = True + history = self._history() + self.assertEqual(history["data"]["2026"][2], 0) + + def test_sales_history_year_range(self): + self.order.date_order = "2026-01-15 10:00:00" + self.line_1.show_sales_history = True + history = self._history() + self.assertEqual(history["years"], [2026, 2025, 2024]) + # Every month after January of the current year is still unknown. + self.assertEqual(history["data"]["2026"][1:], [None] * 11) + + def test_sales_history_years_back_configurable(self): + default_years = self.env["res.config.settings"].default_get( + ["purchase_sales_history_years"] + )["purchase_sales_history_years"] + self.assertEqual(default_years, 2) + self.line_1.show_sales_history = True + self.assertEqual(self._history()["years"], [2026, 2025, 2024]) + self.env["res.config.settings"].create( + {"purchase_sales_history_years": 4} + ).execute() + self.assertEqual(self._history()["years"], [2026, 2025, 2024, 2023, 2022]) + self.env["res.config.settings"].create( + {"purchase_sales_history_years": 1} + ).execute() + self.assertEqual(self._history()["years"], [2026, 2025]) + + def test_sales_history_exact_product_id(self): + self._create_invoice(self.variant_1, "2026-05-05", 5) + self._create_invoice(self.variant_2, "2026-05-06", 8) + self.line_1.show_sales_history = True + self.assertEqual(self._history()["data"]["2026"][4], 5) + self.line_2.show_sales_history = True + history = self._history() + self.assertEqual(history["product_name"], self.variant_2.display_name) + self.assertEqual(history["data"]["2026"][4], 8) diff --git a/purchase_line_sale_history/views/purchase_order_views.xml b/purchase_line_sale_history/views/purchase_order_views.xml new file mode 100644 index 00000000000..a5e41efad61 --- /dev/null +++ b/purchase_line_sale_history/views/purchase_order_views.xml @@ -0,0 +1,31 @@ + + + + + purchase.order.form - purchase_line_sale_history + purchase.order + + + + + + + + + + + + diff --git a/purchase_line_sale_history/views/res_config_settings_views.xml b/purchase_line_sale_history/views/res_config_settings_views.xml new file mode 100644 index 00000000000..4cd89f88c4d --- /dev/null +++ b/purchase_line_sale_history/views/res_config_settings_views.xml @@ -0,0 +1,23 @@ + + + + + res.config.settings.form - purchase_line_sale_history + res.config.settings + + + + + + + + + +