diff --git a/spreadsheet_mis_builder/README.rst b/spreadsheet_mis_builder/README.rst new file mode 100644 index 00000000..a0f3ecca --- /dev/null +++ b/spreadsheet_mis_builder/README.rst @@ -0,0 +1,175 @@ +======================= +Spreadsheet MIS Builder +======================= + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:e0692bac1843b77b0af91ef74eb1e8c46b07f174602391ba28e5ce12866c6fad + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |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/licence-AGPL--3-blue.png + :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html + :alt: License: AGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fspreadsheet-lightgray.png?logo=github + :target: https://github.com/OCA/spreadsheet/tree/18.0/spreadsheet_mis_builder + :alt: OCA/spreadsheet +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/spreadsheet-18-0/spreadsheet-18-0-spreadsheet_mis_builder + :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/spreadsheet&target_branch=18.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module brings `MIS Builder `__ +KPIs into spreadsheets: + +- a ``MIS.KPI`` spreadsheet function returns the value of a KPI of a MIS + report template over any period; +- a *Spreadsheet* button on MIS report instances creates a spreadsheet + reproducing the report, where every KPI cell is a live formula. + +The data source is the report template (``mis.report``), not the report +instance: periods, companies and options are plain cells of the +spreadsheet, so they can be changed, computed or copied like any other +cell. + +**Table of contents** + +.. contents:: + :local: + +Usage +===== + +From a MIS report +----------------- + +Open a MIS report (*Accounting > Reporting > MIS Reports*) and click +*Spreadsheet*, either on the form or on the preview. + +|MIS report with the Spreadsheet button| + +A new spreadsheet is created with: + +- the parameters at the top: report template, companies, whether + unposted entries are included, and the base date; +- one column per column of the report, with its *From* and *To* dates. + Columns with relative periods are formulas based on the base date: + change the base date and the whole report moves; +- one row per KPI, with the style and number format of the report. Each + cell is a ``MIS.KPI`` formula; +- sum and comparison columns as plain cell formulas (``=C10-B10``), that + can be read and changed. + +|Spreadsheet created from a MIS report| + +Changing the base date recomputes the periods and all the KPIs: + +|Same spreadsheet with another base date| + +The spreadsheet does not depend on the report instance anymore: it only +refers to the report template. + +The MIS.KPI function +-------------------- + +``MIS.KPI(report, kpi, date_from, [date_to], [company_ids], [include_unposted], [subkpi])`` + +- ``report``: id of the MIS report template; +- ``kpi``: technical name of the KPI; +- ``date_from``, ``date_to``: the period. When ``date_to`` is empty, + ``date_from`` can be a whole period: ``"2026"``, ``"Q1/2026"`` or + ``"03/2026"``; +- ``company_ids``: ids of the companies separated by commas (the current + company when empty); +- ``include_unposted``: ``TRUE`` to include unposted entries; +- ``subkpi``: technical name of the sub-KPI, for reports with sub-KPIs. + +Examples: + +- ``=MIS.KPI(1, "revenue", "2026")`` +- ``=MIS.KPI(1, "revenue", B1, B2)`` with dates in ``B1`` and ``B2`` +- ``=MIS.KPI(1, "revenue", ODOO.FISCALYEAR.START(B2), B2)`` for a year + to date value + +All the cells of a spreadsheet are fetched in one request, and the +server evaluates each report once per period, whatever the number of +KPIs. + +Demo data +--------- + +With demo data, the *Spreadsheet demo P&L by month* MIS report and the +spreadsheet created from it are available. They rely on a few demo +journal entries of the last three months, posted on dedicated accounts +(codes starting with ``SMB``). + +.. |MIS report with the Spreadsheet button| image:: https://raw.githubusercontent.com/OCA/spreadsheet/18.0/spreadsheet_mis_builder/static/description/mis_report.png +.. |Spreadsheet created from a MIS report| image:: https://raw.githubusercontent.com/OCA/spreadsheet/18.0/spreadsheet_mis_builder/static/description/spreadsheet.png +.. |Same spreadsheet with another base date| image:: https://raw.githubusercontent.com/OCA/spreadsheet/18.0/spreadsheet_mis_builder/static/description/spreadsheet_base_date.png + +Known issues / Roadmap +====================== + +- Columns that ``MIS.KPI`` can not reproduce are exported as static + values, and flagged as such in their header: analytic filters, + alternative move line sources and budgets (``mis_builder_budget``). +- Details by account are not exported. +- Rows hidden when empty are evaluated at export time only. +- The divider, prefix and suffix of MIS styles are not converted. +- The export always creates a new spreadsheet: inserting into an + existing one is not supported. +- No autocompletion of report and KPI names, no drill-down to journal + items from a cell, and no side panel to manage the parameters. +- The base date is a cell; it is not linked to the global filters of the + spreadsheet. + +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 +------- + +* KMEE + +Contributors +------------ + +- `KMEE `__: + + - Luis Felipe Mileo + +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/spreadsheet `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/spreadsheet_mis_builder/__init__.py b/spreadsheet_mis_builder/__init__.py new file mode 100644 index 00000000..0650744f --- /dev/null +++ b/spreadsheet_mis_builder/__init__.py @@ -0,0 +1 @@ +from . import models diff --git a/spreadsheet_mis_builder/__manifest__.py b/spreadsheet_mis_builder/__manifest__.py new file mode 100644 index 00000000..e88dd896 --- /dev/null +++ b/spreadsheet_mis_builder/__manifest__.py @@ -0,0 +1,23 @@ +# Copyright 2026 KMEE +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +{ + "name": "Spreadsheet MIS Builder", + "summary": "Use MIS Builder KPIs in spreadsheets", + "version": "18.0.1.0.0", + "license": "AGPL-3", + "author": "KMEE, Odoo Community Association (OCA)", + "website": "https://github.com/OCA/spreadsheet", + "category": "Accounting", + "depends": ["spreadsheet_oca", "mis_builder"], + "data": ["views/mis_report_instance.xml"], + "demo": ["demo/account_move.xml", "demo/mis_report.xml"], + "assets": { + "spreadsheet.o_spreadsheet": [ + "spreadsheet_mis_builder/static/src/bundle/**/*.js", + ], + "web.assets_backend": [ + "spreadsheet_mis_builder/static/src/components/**/*", + ], + }, +} diff --git a/spreadsheet_mis_builder/demo/account_move.xml b/spreadsheet_mis_builder/demo/account_move.xml new file mode 100644 index 00000000..8114432c --- /dev/null +++ b/spreadsheet_mis_builder/demo/account_move.xml @@ -0,0 +1,183 @@ + + + + + SMB400 + Demo receivables + asset_receivable + + + + + SMB500 + Demo bank + asset_current + + + + SMB600 + Demo cost of revenue + expense_direct_cost + + + + SMB610 + Demo operating expenses + expense + + + + SMB700 + Demo revenue + income + + + + Spreadsheet MIS demo + SMBD + general + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spreadsheet_mis_builder/demo/mis_report.xml b/spreadsheet_mis_builder/demo/mis_report.xml new file mode 100644 index 00000000..6e25ce9c --- /dev/null +++ b/spreadsheet_mis_builder/demo/mis_report.xml @@ -0,0 +1,115 @@ + + + + + Spreadsheet demo total + + bold + + #E6F2F3 + + + Spreadsheet demo P&L + + + + revenue + Revenue + -balp[SMB700] + 10 + + + + cost + Cost of revenue + balp[SMB600] + 20 + + + + gross_profit + Gross profit + revenue - cost + + 30 + + + + expenses + Operating expenses + balp[SMB610] + 40 + + + + net_profit + Net profit + gross_profit - expenses + + 50 + + + + margin + Net margin + net_profit / revenue + pct + 60 + + + + receivable + Receivables (end balance) + bale[SMB400] + diff + 70 + + + + Spreadsheet demo P&L by month + + + + + Previous month + + relative + m + -1 + 10 + + + Current month + + relative + m + 0 + 20 + + + Year to date + + relative + m + 0 + + 30 + + + Variation + + none + cmpcol + + + 40 + + + + + diff --git a/spreadsheet_mis_builder/models/__init__.py b/spreadsheet_mis_builder/models/__init__.py new file mode 100644 index 00000000..7d56b027 --- /dev/null +++ b/spreadsheet_mis_builder/models/__init__.py @@ -0,0 +1,2 @@ +from . import mis_report +from . import mis_report_instance diff --git a/spreadsheet_mis_builder/models/mis_report.py b/spreadsheet_mis_builder/models/mis_report.py new file mode 100644 index 00000000..6aadaccf --- /dev/null +++ b/spreadsheet_mis_builder/models/mis_report.py @@ -0,0 +1,148 @@ +# Copyright 2026 KMEE +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import api, fields, models +from odoo.exceptions import UserError + +from odoo.addons.mis_builder.models.accounting_none import AccountingNone +from odoo.addons.mis_builder.models.mis_report_style import TYPE_NUM, TYPE_PCT + + +class MisReport(models.Model): + _inherit = "mis.report" + + @api.model + def _spreadsheet_number_format(self, var_type, style_props): + """Spreadsheet number format matching a KPI type and style.""" + if var_type not in (TYPE_NUM, TYPE_PCT): + return False + dp = style_props.dp or 0 + decimals = "." + "0" * dp if dp else "" + if var_type == TYPE_PCT: + return f"0{decimals}%" + return f"#,##0{decimals}" + + def _spreadsheet_kpi_format(self, kpi): + self.ensure_one() + style_model = self.env["mis.report.style"] + style_props = style_model.merge([self.style_id, kpi.style_id]) + return self._spreadsheet_number_format(kpi.type, style_props) + + def _spreadsheet_companies(self, company_ids): + if not company_ids: + return self.env.company + companies = self.env["res.company"].browse(company_ids).exists() + forbidden = companies - self.env.user.company_ids + if len(companies) != len(company_ids) or forbidden: + raise UserError( + self.env._( + "Unknown or unauthorized companies: %s", + ", ".join(str(c) for c in company_ids), + ) + ) + return companies + + @api.model + def _spreadsheet_evaluate(self, args, cache): + """Evaluate all the KPIs of a report for one set of parameters. + + The result is cached by parameters, so that all the cells of a + spreadsheet column cost one single report evaluation. + """ + company_ids = tuple(sorted(set(args.get("company_ids") or []))) + key = ( + args["report_id"], + args["date_from"], + args["date_to"], + company_ids, + bool(args.get("include_unposted")), + args.get("subkpi") or "", + ) + if key in cache: + return cache[key] + report = self.browse(args["report_id"]).exists() + if not report: + raise UserError( + self.env._("MIS report template %s not found.", args["report_id"]) + ) + companies = report._spreadsheet_companies(list(company_ids)) + report = report.with_context(allowed_company_ids=companies.ids) + companies = companies.with_context(allowed_company_ids=companies.ids) + date_from = fields.Date.to_date(args["date_from"]) + date_to = fields.Date.to_date(args["date_to"]) + if date_from > date_to: + raise UserError(self.env._("The start date is after the end date.")) + subkpi = report.env["mis.report.subkpi"] + if key[5]: + subkpi = report.subkpi_ids.filtered(lambda s: s.name == key[5]) + if not subkpi: + raise UserError( + self.env._( + "Sub-KPI %(subkpi)s not found in report %(report)s.", + subkpi=key[5], + report=report.display_name, + ) + ) + aep_key = ("aep", report.id, company_ids) + if aep_key not in cache: + cache[aep_key] = report._prepare_aep(companies) + values = report.evaluate( + cache[aep_key], + date_from, + date_to, + target_move="all" if key[4] else "posted", + subkpis_filter=subkpi or None, + ) + cache[key] = (report, values) + return cache[key] + + @api.model + def _spreadsheet_fetch_one_kpi(self, args, cache): + report, values = self._spreadsheet_evaluate(args, cache) + kpi = report.kpi_ids.filtered(lambda k: k.name == args["kpi"]) + if not kpi: + raise UserError( + self.env._( + "KPI %(kpi)s not found in report %(report)s.", + kpi=args["kpi"], + report=report.display_name, + ) + ) + if kpi.name not in values: + raise UserError( + self.env._("KPI %s could not be evaluated.", kpi.name), + ) + value = values[kpi.name] + if isinstance(value, tuple): + if len(value) != 1: + raise UserError( + self.env._( + "KPI %(kpi)s has several sub-KPIs (%(subkpis)s): " + "one of them must be given.", + kpi=kpi.name, + subkpis=", ".join(report.subkpi_ids.mapped("name")), + ) + ) + value = value[0] + if value is AccountingNone or value is None: + value = False + return {"value": value, "format": report._spreadsheet_kpi_format(kpi)} + + @api.model + def spreadsheet_fetch_kpi(self, args_list): + """Batch endpoint of the MIS.KPI spreadsheet function. + + :param args_list: list of dicts with keys ``report_id``, ``kpi``, + ``date_from``, ``date_to`` and optionally ``company_ids``, + ``include_unposted`` and ``subkpi`` + :return: list of dicts, in the same order, with either ``value`` + and ``format``, or ``error`` + """ + cache = {} + results = [] + for args in args_list: + try: + results.append(self._spreadsheet_fetch_one_kpi(args, cache)) + except UserError as e: + results.append({"error": str(e)}) + return results diff --git a/spreadsheet_mis_builder/models/mis_report_instance.py b/spreadsheet_mis_builder/models/mis_report_instance.py new file mode 100644 index 00000000..27865762 --- /dev/null +++ b/spreadsheet_mis_builder/models/mis_report_instance.py @@ -0,0 +1,358 @@ +# Copyright 2026 KMEE +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +import ast + +from odoo import fields, models + +from odoo.addons.mis_builder.models.accounting_none import AccountingNone +from odoo.addons.mis_builder.models.data_error import DataError +from odoo.addons.mis_builder.models.mis_report_instance import ( + MODE_REL, + SRC_ACTUALS, + SRC_CMPCOL, + SRC_SUMCOL, +) +from odoo.addons.mis_builder.models.mis_report_style import ( + CMP_DIFF, + CMP_PCT, + TYPE_NUM, + TYPE_PCT, +) + +FONT_SIZES = { + "xx-small": 7, + "x-small": 8, + "small": 9, + "medium": 10, + "large": 12, + "x-large": 14, + "xx-large": 18, +} +# Cells holding the parameters shared by all the formulas of the sheet. +CELL_REPORT = "$B$2" +CELL_COMPANIES = "$B$3" +CELL_UNPOSTED = "$B$4" +CELL_BASE_DATE = "$B$5" +ROW_FROM = 7 +ROW_TO = 8 +ROW_LABELS = 9 + + +def _col_letter(index): + """Zero-based column index to spreadsheet column letters.""" + letters = "" + index += 1 + while index: + index, remainder = divmod(index - 1, 26) + letters = chr(65 + remainder) + letters + return letters + + +def _xc(col, row): + return f"{_col_letter(col)}{row}" + + +def _date_formula(date): + return f"=DATE({date.year},{date.month},{date.day})" + + +class SheetBuilder: + """Accumulate the cells of one sheet in the o-spreadsheet data format.""" + + def __init__(self): + self.cells = {} + self.cell_styles = {} + self.cell_formats = {} + self.styles = {} + self.formats = {} + self.col_number = 1 + self.row_number = 1 + + @staticmethod + def _registry_id(registry, value): + for key, existing in registry.items(): + if existing == value: + return key + key = len(registry) + 1 + registry[key] = value + return key + + def set(self, col, row, content=None, style=None, number_format=None): + xc = _xc(col, row) + if content not in (None, False, ""): + self.cells[xc] = {"content": str(content)} + if style: + self.cell_styles[xc] = self._registry_id(self.styles, style) + if number_format: + self.cell_formats[xc] = self._registry_id(self.formats, number_format) + self.col_number = max(self.col_number, col + 1) + self.row_number = max(self.row_number, row) + + +class MisReportInstance(models.Model): + _inherit = "mis.report.instance" + + def action_export_spreadsheet(self): + """Create a spreadsheet with live formulas from this report.""" + self.ensure_one() + spreadsheet = self.env["spreadsheet.spreadsheet"].create( + {"name": self.name, "spreadsheet_raw": self._spreadsheet_data()} + ) + return spreadsheet.open_spreadsheet() + + # ------------------------------------------------------------------ + # Columns + # ------------------------------------------------------------------ + + def _spreadsheet_is_live_period(self, period): + """Tell if the values of a column can be computed by MIS.KPI. + + Columns the function can not reproduce (alternative move line + sources, analytic filters, budgets...) are exported as static values. + """ + return ( + period.source == SRC_ACTUALS + and period.source_aml_model_name in (False, "account.move.line") + and not ast.literal_eval(self.analytic_domain or "[]") + and not ast.literal_eval(period.analytic_domain or "[]") + and not self.env.context.get("mis_analytic_domain") + and bool(period.date_from and period.date_to) + ) + + def _spreadsheet_period_dates(self, period, col): + """Formulas for the start and end dates of a live column.""" + date_from = fields.Date.to_date(period.date_from) + date_to = fields.Date.to_date(period.date_to) + formula_from = _date_formula(date_from) + formula_to = _date_formula(date_to) + if not self.comparison_mode or period.mode != MODE_REL: + return formula_from, formula_to + base = CELL_BASE_DATE + offset = period.offset + duration = period.duration + cell_from = _xc(col, ROW_FROM) + if period.type == "d": + formula_from = f"={base}+{offset}" + formula_to = f"={cell_from}+{duration - 1}" + elif period.type == "w": + formula_from = f"={base}-WEEKDAY({base},2)+1+{7 * offset}" + formula_to = f"={cell_from}+{7 * duration - 1}" + elif period.type == "m": + formula_from = f"=EDATE(EOMONTH({base},-1)+1,{offset})" + formula_to = f"=EOMONTH({base},{offset + duration - 1})" + elif period.type == "y": + formula_from = f"=DATE(YEAR({base})+{offset},1,1)" + formula_to = f"=DATE(YEAR({base})+{offset + duration - 1},12,31)" + if period.is_ytd: + formula_from = f"=DATE(YEAR({_xc(col, ROW_TO)}),1,1)" + return formula_from, formula_to + + # ------------------------------------------------------------------ + # Cells + # ------------------------------------------------------------------ + + def _spreadsheet_style(self, style_props): + style = {} + if style_props.font_weight == "bold": + style["bold"] = True + if style_props.font_style == "italic": + style["italic"] = True + if style_props.color: + style["textColor"] = style_props.color + if style_props.background_color: + style["fillColor"] = style_props.background_color + if style_props.font_size in FONT_SIZES: + style["fontSize"] = FONT_SIZES[style_props.font_size] + return style + + def _spreadsheet_static_value(self, cell): + if ( + cell is None + or cell.val is AccountingNone + or isinstance(cell.val, DataError) + ): + return None + if isinstance(cell.val, bool | int | float): + return repr(cell.val) + return cell.val + + def _spreadsheet_kpi_formula(self, kpi, col, subkpi): + formula = ( + f'=MIS.KPI({CELL_REPORT},"{kpi.name}",' + f"{_col_letter(col)}${ROW_FROM},{_col_letter(col)}${ROW_TO}," + f"{CELL_COMPANIES},{CELL_UNPOSTED}" + ) + if subkpi: + formula += f',"{subkpi.name}"' + return formula + ")" + + def _spreadsheet_comparison(self, kpi, style_props, cell_to, cell_from): + """Formula and format comparing two cells, as MIS Builder does.""" + report = self.report_id + if kpi.type == TYPE_PCT: + dp = style_props.dp or 0 + decimals = "." + "0" * dp if dp else "" + return f"=({cell_to}-{cell_from})*100", f"0{decimals}[$ pp]" + if kpi.type != TYPE_NUM: + return None, None + if kpi.compare_method == CMP_DIFF: + return ( + f"={cell_to}-{cell_from}", + report._spreadsheet_number_format(TYPE_NUM, style_props), + ) + if kpi.compare_method == CMP_PCT: + return ( + f'=IF({cell_from}=0,"",({cell_to}-{cell_from})/ABS({cell_from}))', + "0.0%", + ) + return None, None + + # ------------------------------------------------------------------ + # Sheet + # ------------------------------------------------------------------ + + def _spreadsheet_data(self): + """Spreadsheet (o-spreadsheet data) reproducing this report. + + KPI cells are MIS.KPI formulas, period dates are formulas relative + to a base date cell, and sum and comparison columns are plain cell + formulas, so that the spreadsheet stays live and editable. + """ + self.ensure_one() + report = self.report_id + matrix = self._compute_matrix() + periods = {period.id: period for period in self.period_ids} + sheet = SheetBuilder() + bold = {"bold": True} + muted = {"textColor": "#666666", "italic": True} + lang = self.env["res.lang"]._lang_get(self.env.user.lang) + locale = lang._odoo_lang_to_spreadsheet_locale() + date_format = locale.get("dateFormat") or "yyyy-mm-dd" + + # parameters + companies = self.query_company_ids + sheet.set(0, 1, self.name, {"bold": True, "fontSize": 14}) + sheet.set(0, 2, self.env._("Report"), bold) + sheet.set(1, 2, report.id) + sheet.set(2, 2, report.name, muted) + sheet.set(0, 3, self.env._("Companies"), bold) + company_ids = ",".join(str(c) for c in companies.ids) + sheet.set(1, 3, f'="{company_ids}"') + sheet.set(2, 3, ", ".join(companies.mapped("name")), muted) + sheet.set(0, 4, self.env._("Include unposted entries"), bold) + sheet.set(1, 4, "TRUE" if self.target_move == "all" else "FALSE") + if self.comparison_mode: + sheet.set(0, 5, self.env._("Base date"), bold) + base_date = _date_formula(self.pivot_date) if self.date else "=TODAY()" + sheet.set(1, 5, base_date, number_format=date_format) + sheet.set(0, ROW_FROM, self.env._("From"), bold) + sheet.set(0, ROW_TO, self.env._("To"), bold) + + # columns + has_subcols = any(col.subkpis for col in matrix.iter_cols()) + first_row = ROW_LABELS + (2 if has_subcols else 1) + col_index = {} # {(period id, sub column index): column} + next_col = 1 + for col in matrix.iter_cols(): + period = periods[col.key] + live = self._spreadsheet_is_live_period(period) + label = col.label + if not live and period.source not in (SRC_SUMCOL, SRC_CMPCOL): + label = self.env._("%s (static)", label) + for subcol in col.iter_subcols(): + col_index[(col.key, subcol.index)] = next_col + if subcol.index == 0: + sheet.set(next_col, ROW_LABELS, label, bold) + if has_subcols: + sheet.set(next_col, ROW_LABELS + 1, subcol.label, bold) + if live: + date_from, date_to = self._spreadsheet_period_dates( + period, next_col + ) + sheet.set(next_col, ROW_FROM, date_from, None, date_format) + sheet.set(next_col, ROW_TO, date_to, None, date_format) + next_col += 1 + + # rows + sheet_row = first_row + for row in matrix.iter_rows(): + if row.account_id: + # details by account are not exported + continue + props = row.style_props + if props.hide_always or (props.hide_empty and row.is_empty()): + continue + indent = " " * 4 * (props.indent_level or 0) + sheet.set(0, sheet_row, indent + row.label, self._spreadsheet_style(props)) + for col in matrix.iter_cols(): + period = periods[col.key] + live = self._spreadsheet_is_live_period(period) + for subcol in col.iter_subcols(): + self._spreadsheet_set_cell( + sheet, sheet_row, row, period, live, subcol, col_index + ) + sheet_row += 1 + + data = self.env["spreadsheet.spreadsheet"]._empty_spreadsheet_data() + data.update( + { + "version": 21, + "styles": {str(k): v for k, v in sheet.styles.items()}, + "formats": {str(k): v for k, v in sheet.formats.items()}, + } + ) + cols = {str(i): {"size": 130} for i in range(1, sheet.col_number)} + cols["0"] = {"size": 280} + data["sheets"][0].update( + { + "name": self.env._("MIS Report"), + "colNumber": max(sheet.col_number + 5, 26), + "rowNumber": max(sheet.row_number + 20, 100), + "cols": cols, + "cells": sheet.cells, + "styles": sheet.cell_styles, + "formats": sheet.cell_formats, + } + ) + return data + + def _spreadsheet_set_cell( + self, sheet, sheet_row, row, period, live, subcol, col_index + ): + kpi = row.kpi + report = self.report_id + sheet_col = col_index[(period.id, subcol.index)] + cell = subcol.get_cell_for_row(row) + props = cell.style_props if cell is not None else row.style_props + style = self._spreadsheet_style(props) + number_format = report._spreadsheet_number_format(kpi.type, props) + content = None + + def source_cell(source_period): + source_col = col_index.get((source_period.id, subcol.index)) + return _xc(source_col, sheet_row) if source_col else None + + if live: + content = self._spreadsheet_kpi_formula(kpi, sheet_col, subcol.subkpi) + elif period.source == SRC_SUMCOL: + terms = [ + (sumcol.sign, source_cell(sumcol.period_to_sum_id)) + for sumcol in period.source_sumcol_ids + ] + if terms and all(ref for _sign, ref in terms): + content = "=" + "".join(sign + ref for sign, ref in terms) + elif period.source == SRC_CMPCOL: + cell_to = source_cell(period.source_cmpcol_to_id) + cell_from = source_cell(period.source_cmpcol_from_id) + if cell_to and cell_from: + content, number_format = self._spreadsheet_comparison( + kpi, props, cell_to, cell_from + ) + else: + number_format = None + if content is None and period.source != SRC_CMPCOL: + content = self._spreadsheet_static_value(cell) + if cell is not None and cell.val_type != kpi.type: + number_format = report._spreadsheet_number_format(cell.val_type, props) + sheet.set(sheet_col, sheet_row, content, style, number_format) diff --git a/spreadsheet_mis_builder/pyproject.toml b/spreadsheet_mis_builder/pyproject.toml new file mode 100644 index 00000000..4231d0cc --- /dev/null +++ b/spreadsheet_mis_builder/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/spreadsheet_mis_builder/readme/CONTRIBUTORS.md b/spreadsheet_mis_builder/readme/CONTRIBUTORS.md new file mode 100644 index 00000000..39978b42 --- /dev/null +++ b/spreadsheet_mis_builder/readme/CONTRIBUTORS.md @@ -0,0 +1,2 @@ +- [KMEE](https://kmee.com.br): + - Luis Felipe Mileo \ diff --git a/spreadsheet_mis_builder/readme/DESCRIPTION.md b/spreadsheet_mis_builder/readme/DESCRIPTION.md new file mode 100644 index 00000000..9fd06cb6 --- /dev/null +++ b/spreadsheet_mis_builder/readme/DESCRIPTION.md @@ -0,0 +1,12 @@ +This module brings [MIS Builder](https://github.com/OCA/mis-builder) KPIs +into spreadsheets: + +- a `MIS.KPI` spreadsheet function returns the value of a KPI of a MIS + report template over any period; +- a *Spreadsheet* button on MIS report instances creates a spreadsheet + reproducing the report, where every KPI cell is a live formula. + +The data source is the report template (`mis.report`), not the report +instance: periods, companies and options are plain cells of the +spreadsheet, so they can be changed, computed or copied like any other +cell. diff --git a/spreadsheet_mis_builder/readme/ROADMAP.md b/spreadsheet_mis_builder/readme/ROADMAP.md new file mode 100644 index 00000000..4744903a --- /dev/null +++ b/spreadsheet_mis_builder/readme/ROADMAP.md @@ -0,0 +1,12 @@ +- Columns that `MIS.KPI` can not reproduce are exported as static + values, and flagged as such in their header: analytic filters, + alternative move line sources and budgets (`mis_builder_budget`). +- Details by account are not exported. +- Rows hidden when empty are evaluated at export time only. +- The divider, prefix and suffix of MIS styles are not converted. +- The export always creates a new spreadsheet: inserting into an + existing one is not supported. +- No autocompletion of report and KPI names, no drill-down to journal + items from a cell, and no side panel to manage the parameters. +- The base date is a cell; it is not linked to the global filters of the + spreadsheet. diff --git a/spreadsheet_mis_builder/readme/USAGE.md b/spreadsheet_mis_builder/readme/USAGE.md new file mode 100644 index 00000000..69fd2c89 --- /dev/null +++ b/spreadsheet_mis_builder/readme/USAGE.md @@ -0,0 +1,59 @@ +## From a MIS report + +Open a MIS report (*Accounting \> Reporting \> MIS Reports*) and click +*Spreadsheet*, either on the form or on the preview. + +![MIS report with the Spreadsheet button](../static/description/mis_report.png) + +A new spreadsheet is created with: + +- the parameters at the top: report template, companies, whether + unposted entries are included, and the base date; +- one column per column of the report, with its *From* and *To* dates. + Columns with relative periods are formulas based on the base date: + change the base date and the whole report moves; +- one row per KPI, with the style and number format of the report. Each + cell is a `MIS.KPI` formula; +- sum and comparison columns as plain cell formulas (`=C10-B10`), that + can be read and changed. + +![Spreadsheet created from a MIS report](../static/description/spreadsheet.png) + +Changing the base date recomputes the periods and all the KPIs: + +![Same spreadsheet with another base date](../static/description/spreadsheet_base_date.png) + +The spreadsheet does not depend on the report instance anymore: it only +refers to the report template. + +## The MIS.KPI function + +`MIS.KPI(report, kpi, date_from, [date_to], [company_ids], [include_unposted], [subkpi])` + +- `report`: id of the MIS report template; +- `kpi`: technical name of the KPI; +- `date_from`, `date_to`: the period. When `date_to` is empty, + `date_from` can be a whole period: `"2026"`, `"Q1/2026"` or + `"03/2026"`; +- `company_ids`: ids of the companies separated by commas (the current + company when empty); +- `include_unposted`: `TRUE` to include unposted entries; +- `subkpi`: technical name of the sub-KPI, for reports with sub-KPIs. + +Examples: + +- `=MIS.KPI(1, "revenue", "2026")` +- `=MIS.KPI(1, "revenue", B1, B2)` with dates in `B1` and `B2` +- `=MIS.KPI(1, "revenue", ODOO.FISCALYEAR.START(B2), B2)` for a year to + date value + +All the cells of a spreadsheet are fetched in one request, and the +server evaluates each report once per period, whatever the number of +KPIs. + +## Demo data + +With demo data, the *Spreadsheet demo P&L by month* MIS report and the +spreadsheet created from it are available. They rely on a few demo +journal entries of the last three months, posted on dedicated accounts +(codes starting with `SMB`). diff --git a/spreadsheet_mis_builder/static/description/icon.png b/spreadsheet_mis_builder/static/description/icon.png new file mode 100644 index 00000000..0fcecf88 Binary files /dev/null and b/spreadsheet_mis_builder/static/description/icon.png differ diff --git a/spreadsheet_mis_builder/static/description/index.html b/spreadsheet_mis_builder/static/description/index.html new file mode 100644 index 00000000..a9c30b9f --- /dev/null +++ b/spreadsheet_mis_builder/static/description/index.html @@ -0,0 +1,519 @@ + + + + + +Spreadsheet MIS Builder + + + +
+

Spreadsheet MIS Builder

+ + +

Beta License: AGPL-3 OCA/spreadsheet Translate me on Weblate Try me on Runboat

+

This module brings MIS Builder +KPIs into spreadsheets:

+
    +
  • a MIS.KPI spreadsheet function returns the value of a KPI of a MIS +report template over any period;
  • +
  • a Spreadsheet button on MIS report instances creates a spreadsheet +reproducing the report, where every KPI cell is a live formula.
  • +
+

The data source is the report template (mis.report), not the report +instance: periods, companies and options are plain cells of the +spreadsheet, so they can be changed, computed or copied like any other +cell.

+

Table of contents

+ +
+

Usage

+
+

From a MIS report

+

Open a MIS report (Accounting > Reporting > MIS Reports) and click +Spreadsheet, either on the form or on the preview.

+

MIS report with the Spreadsheet button

+

A new spreadsheet is created with:

+
    +
  • the parameters at the top: report template, companies, whether +unposted entries are included, and the base date;
  • +
  • one column per column of the report, with its From and To dates. +Columns with relative periods are formulas based on the base date: +change the base date and the whole report moves;
  • +
  • one row per KPI, with the style and number format of the report. Each +cell is a MIS.KPI formula;
  • +
  • sum and comparison columns as plain cell formulas (=C10-B10), that +can be read and changed.
  • +
+

Spreadsheet created from a MIS report

+

Changing the base date recomputes the periods and all the KPIs:

+

Same spreadsheet with another base date

+

The spreadsheet does not depend on the report instance anymore: it only +refers to the report template.

+
+
+

The MIS.KPI function

+

MIS.KPI(report, kpi, date_from, [date_to], [company_ids], [include_unposted], [subkpi])

+
    +
  • report: id of the MIS report template;
  • +
  • kpi: technical name of the KPI;
  • +
  • date_from, date_to: the period. When date_to is empty, +date_from can be a whole period: "2026", "Q1/2026" or +"03/2026";
  • +
  • company_ids: ids of the companies separated by commas (the current +company when empty);
  • +
  • include_unposted: TRUE to include unposted entries;
  • +
  • subkpi: technical name of the sub-KPI, for reports with sub-KPIs.
  • +
+

Examples:

+
    +
  • =MIS.KPI(1, "revenue", "2026")
  • +
  • =MIS.KPI(1, "revenue", B1, B2) with dates in B1 and B2
  • +
  • =MIS.KPI(1, "revenue", ODOO.FISCALYEAR.START(B2), B2) for a year +to date value
  • +
+

All the cells of a spreadsheet are fetched in one request, and the +server evaluates each report once per period, whatever the number of +KPIs.

+
+
+

Demo data

+

With demo data, the Spreadsheet demo P&L by month MIS report and the +spreadsheet created from it are available. They rely on a few demo +journal entries of the last three months, posted on dedicated accounts +(codes starting with SMB).

+
+
+
+

Known issues / Roadmap

+
    +
  • Columns that MIS.KPI can not reproduce are exported as static +values, and flagged as such in their header: analytic filters, +alternative move line sources and budgets (mis_builder_budget).
  • +
  • Details by account are not exported.
  • +
  • Rows hidden when empty are evaluated at export time only.
  • +
  • The divider, prefix and suffix of MIS styles are not converted.
  • +
  • The export always creates a new spreadsheet: inserting into an +existing one is not supported.
  • +
  • No autocompletion of report and KPI names, no drill-down to journal +items from a cell, and no side panel to manage the parameters.
  • +
  • The base date is a cell; it is not linked to the global filters of the +spreadsheet.
  • +
+
+
+

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

+
    +
  • KMEE
  • +
+
+
+

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/spreadsheet project on GitHub.

+

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

+
+
+
+ + diff --git a/spreadsheet_mis_builder/static/description/mis_report.png b/spreadsheet_mis_builder/static/description/mis_report.png new file mode 100644 index 00000000..c3f0fbbd Binary files /dev/null and b/spreadsheet_mis_builder/static/description/mis_report.png differ diff --git a/spreadsheet_mis_builder/static/description/spreadsheet.png b/spreadsheet_mis_builder/static/description/spreadsheet.png new file mode 100644 index 00000000..6b5f9ee5 Binary files /dev/null and b/spreadsheet_mis_builder/static/description/spreadsheet.png differ diff --git a/spreadsheet_mis_builder/static/description/spreadsheet_base_date.png b/spreadsheet_mis_builder/static/description/spreadsheet_base_date.png new file mode 100644 index 00000000..f814f786 Binary files /dev/null and b/spreadsheet_mis_builder/static/description/spreadsheet_base_date.png differ diff --git a/spreadsheet_mis_builder/static/src/bundle/mis_builder_functions.esm.js b/spreadsheet_mis_builder/static/src/bundle/mis_builder_functions.esm.js new file mode 100644 index 00000000..75e56399 --- /dev/null +++ b/spreadsheet_mis_builder/static/src/bundle/mis_builder_functions.esm.js @@ -0,0 +1,145 @@ +import * as spreadsheet from "@odoo/o-spreadsheet"; +import {EvaluationError} from "@odoo/o-spreadsheet"; +import {MisBuilderPlugin} from "./mis_builder_plugin.esm"; +import {_t} from "@web/core/l10n/translation"; + +const {functionRegistry, featurePluginRegistry} = spreadsheet.registries; +const {arg, toBoolean, toJsDate, toNumber, toString} = spreadsheet.helpers; + +const QUARTER_REGEXP = /^q([1-4])\/(\d{4})$/i; +const MONTH_REGEXP = /^0?([1-9]|1[0-2])\/(\d{4})$/; +const YEAR_REGEXP = /^(\d{4})$/; + +function isEmpty(data) { + return data === undefined || data.value === null || data.value === ""; +} + +function serverDate(year, month, day) { + const pad = (number) => String(number).padStart(2, "0"); + return `${year}-${pad(month)}-${pad(day)}`; +} + +function jsDateToServer(date) { + return serverDate(date.getFullYear(), date.getMonth() + 1, date.getDate()); +} + +function lastDayOfMonth(year, month) { + return new Date(year, month, 0).getDate(); +} + +/** + * Convert the period arguments of MIS.KPI to server dates. + * + * @param {Object} dateFrom start date, or a period ("2026", "Q1/2026", + * "03/2026") when dateTo is empty + * @param {Object} dateTo end date + * @param {Object} locale + * @returns {{date_from: String, date_to: String}} + */ +export function parseMisPeriod(dateFrom, dateTo, locale) { + if (isEmpty(dateFrom)) { + throw new EvaluationError(_t("The start date of the period is missing.")); + } + if (!isEmpty(dateTo)) { + return { + date_from: jsDateToServer(toJsDate(dateFrom, locale)), + date_to: jsDateToServer(toJsDate(dateTo, locale)), + }; + } + const period = toString(dateFrom).trim(); + let found = period.match(QUARTER_REGEXP); + if (found) { + const year = Number(found[2]); + const lastMonth = Number(found[1]) * 3; + return { + date_from: serverDate(year, lastMonth - 2, 1), + date_to: serverDate(year, lastMonth, lastDayOfMonth(year, lastMonth)), + }; + } + found = period.match(MONTH_REGEXP); + if (found) { + const year = Number(found[2]); + const month = Number(found[1]); + return { + date_from: serverDate(year, month, 1), + date_to: serverDate(year, month, lastDayOfMonth(year, month)), + }; + } + found = period.match(YEAR_REGEXP); + if (found && Number(found[1]) < 3000) { + const year = Number(found[1]); + return {date_from: serverDate(year, 1, 1), date_to: serverDate(year, 12, 31)}; + } + // A single day + const day = jsDateToServer(toJsDate(dateFrom, locale)); + return {date_from: day, date_to: day}; +} + +function parseCompanyIds(companyIds) { + if (isEmpty(companyIds)) { + return []; + } + const ids = toString(companyIds) + .split(",") + .map((id) => Number(id.trim())); + if (ids.some((id) => !Number.isInteger(id) || id <= 0)) { + throw new EvaluationError( + _t("'%s' is not a valid list of company ids.", toString(companyIds)) + ); + } + return ids.sort((a, b) => a - b); +} + +featurePluginRegistry.add("misBuilder", MisBuilderPlugin); + +functionRegistry.add("MIS.KPI", { + description: _t("Get the value of a KPI of a MIS Builder report over a period."), + args: [ + arg("report (number)", _t("The id of the MIS report template.")), + arg("kpi (string)", _t("The technical name of the KPI.")), + arg( + "date_from (date, string)", + _t( + 'The start date of the period, or the whole period ("2026", "Q1/2026", "03/2026") when date_to is empty.' + ) + ), + arg("date_to (date, optional)", _t("The end date of the period.")), + arg( + "company_ids (string, optional)", + _t( + "The ids of the companies, separated by a comma (current company if empty)." + ) + ), + arg( + "include_unposted (boolean, default=FALSE)", + _t("Set to TRUE to include unposted entries.") + ), + arg("subkpi (string, optional)", _t("The technical name of the sub-KPI.")), + ], + category: "Odoo", + returns: ["NUMBER"], + compute: function ( + report, + kpi, + dateFrom, + dateTo = {value: ""}, + companyIds = {value: ""}, + includeUnposted = {value: false}, + subkpi = {value: ""} + ) { + const period = parseMisPeriod(dateFrom, dateTo, this.locale); + const result = this.getters.getMisKpi({ + report_id: toNumber(report, this.locale), + kpi: toString(kpi).trim(), + date_from: period.date_from, + date_to: period.date_to, + company_ids: parseCompanyIds(companyIds), + include_unposted: isEmpty(includeUnposted) + ? false + : toBoolean(includeUnposted), + subkpi: isEmpty(subkpi) ? "" : toString(subkpi).trim(), + }); + const value = result.value === false ? "" : result.value; + return result.format ? {value, format: result.format} : {value}; + }, +}); diff --git a/spreadsheet_mis_builder/static/src/bundle/mis_builder_plugin.esm.js b/spreadsheet_mis_builder/static/src/bundle/mis_builder_plugin.esm.js new file mode 100644 index 00000000..8c63865b --- /dev/null +++ b/spreadsheet_mis_builder/static/src/bundle/mis_builder_plugin.esm.js @@ -0,0 +1,47 @@ +import {EvaluationError} from "@odoo/o-spreadsheet"; +import {OdooUIPlugin} from "@spreadsheet/plugins"; + +export class MisBuilderPlugin extends OdooUIPlugin { + static getters = ["getMisKpi"]; + + constructor(config) { + super(config); + this._serverData = config.custom.odooDataProvider?.serverData; + } + + get serverData() { + if (!this._serverData) { + throw new Error( + "'serverData' is not defined, please make sure a 'OdooDataProvider' instance is provided to the model." + ); + } + return this._serverData; + } + + /** + * Value and format of a KPI of a MIS report template over a period. + * Calls are batched: all the cells evaluated in the same tick are sent + * in one request, and the server evaluates each report once per period. + * + * @param {Object} args + * @param {Number} args.report_id + * @param {String} args.kpi + * @param {String} args.date_from + * @param {String} args.date_to + * @param {Number[]} args.company_ids + * @param {Boolean} args.include_unposted + * @param {String} args.subkpi + * @returns {{value: Number|String|Boolean, format: String|Boolean}} + */ + getMisKpi(args) { + const result = this.serverData.batch.get( + "mis.report", + "spreadsheet_fetch_kpi", + args + ); + if (result.error) { + throw new EvaluationError(result.error); + } + return result; + } +} diff --git a/spreadsheet_mis_builder/static/src/components/mis_report_widget.esm.js b/spreadsheet_mis_builder/static/src/components/mis_report_widget.esm.js new file mode 100644 index 00000000..02f0ff81 --- /dev/null +++ b/spreadsheet_mis_builder/static/src/components/mis_report_widget.esm.js @@ -0,0 +1,14 @@ +import {MisReportWidget} from "@mis_builder/components/mis_report_widget.esm"; +import {patch} from "@web/core/utils/patch"; + +patch(MisReportWidget.prototype, { + async exportSpreadsheet() { + const action = await this.orm.call( + "mis.report.instance", + "action_export_spreadsheet", + [this._instanceId()], + {context: this.context} + ); + this.action.doAction(action); + }, +}); diff --git a/spreadsheet_mis_builder/static/src/components/mis_report_widget.xml b/spreadsheet_mis_builder/static/src/components/mis_report_widget.xml new file mode 100644 index 00000000..48eaf967 --- /dev/null +++ b/spreadsheet_mis_builder/static/src/components/mis_report_widget.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/spreadsheet_mis_builder/tests/__init__.py b/spreadsheet_mis_builder/tests/__init__.py new file mode 100644 index 00000000..ce1d136e --- /dev/null +++ b/spreadsheet_mis_builder/tests/__init__.py @@ -0,0 +1 @@ +from . import test_spreadsheet_mis_builder diff --git a/spreadsheet_mis_builder/tests/test_spreadsheet_mis_builder.py b/spreadsheet_mis_builder/tests/test_spreadsheet_mis_builder.py new file mode 100644 index 00000000..c9e82cf1 --- /dev/null +++ b/spreadsheet_mis_builder/tests/test_spreadsheet_mis_builder.py @@ -0,0 +1,356 @@ +# Copyright 2026 KMEE +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +import datetime +from unittest import mock + +from odoo import Command +from odoo.tests.common import TransactionCase + +from odoo.addons.mis_builder.models.mis_report import MisReport + + +class TestSpreadsheetMisBuilder(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.company = cls.env["res.company"].create({"name": "Spreadsheet MIS"}) + cls.env.user.company_ids = [Command.link(cls.company.id)] + cls.account_ar = cls.env["account.account"].create( + { + "company_ids": cls.company.ids, + "code": "400AR", + "name": "Receivable", + "account_type": "asset_receivable", + "reconcile": True, + } + ) + cls.account_in = cls.env["account.account"].create( + { + "company_ids": cls.company.ids, + "code": "700IN", + "name": "Income", + "account_type": "income", + } + ) + cls.journal = cls.env["account.journal"].create( + { + "company_id": cls.company.id, + "name": "Sale journal", + "code": "VEN", + "type": "sale", + } + ) + cls._create_move(datetime.date(2026, 1, 15), 100) + cls._create_move(datetime.date(2026, 2, 15), 300) + cls._create_move(datetime.date(2026, 2, 20), 50, post=False) + cls.style = cls.env["mis.report.style"].create( + { + "name": "Spreadsheet MIS bold", + "font_weight_inherit": False, + "font_weight": "bold", + "dp_inherit": False, + "dp": 2, + } + ) + cls.report = cls.env["mis.report"].create( + { + "name": "Spreadsheet MIS report", + "kpi_ids": [ + Command.create( + { + "name": "income", + "description": "Income", + "expression": "-balp[700IN]", + "style_id": cls.style.id, + "sequence": 1, + } + ), + Command.create( + { + "name": "receivable", + "description": "Receivable", + "expression": "bale[400AR]", + "compare_method": "diff", + "sequence": 2, + } + ), + Command.create( + { + "name": "margin", + "description": "Margin", + "expression": "income / receivable", + "type": "pct", + "sequence": 3, + } + ), + ], + } + ) + + @classmethod + def _create_move(cls, date, amount, post=True): + move = cls.env["account.move"].create( + { + "date": date, + "journal_id": cls.journal.id, + "line_ids": [ + Command.create( + {"account_id": cls.account_ar.id, "debit": amount}, + ), + Command.create( + {"account_id": cls.account_in.id, "credit": amount}, + ), + ], + } + ) + if post: + move.action_post() + return move + + def _args(self, kpi, date_from, date_to, **kwargs): + return dict( + report_id=self.report.id, + kpi=kpi, + date_from=date_from, + date_to=date_to, + company_ids=self.company.ids, + **kwargs, + ) + + def _fetch(self, *args_list): + return self.env["mis.report"].spreadsheet_fetch_kpi(list(args_list)) + + def test_fetch_kpi(self): + january, february, quarter, receivable, margin = self._fetch( + self._args("income", "2026-01-01", "2026-01-31"), + self._args("income", "2026-02-01", "2026-02-28"), + self._args("income", "2026-01-01", "2026-03-31"), + self._args("receivable", "2026-01-01", "2026-03-31"), + self._args("margin", "2026-01-01", "2026-03-31"), + ) + self.assertEqual(january, {"value": 100, "format": "#,##0.00"}) + self.assertEqual(february["value"], 300) + self.assertEqual(quarter["value"], 400) + self.assertEqual(receivable, {"value": 400, "format": "#,##0"}) + self.assertEqual(margin, {"value": 1, "format": "0%"}) + + def test_fetch_kpi_unposted(self): + posted, with_draft = self._fetch( + self._args("income", "2026-02-01", "2026-02-28"), + self._args("income", "2026-02-01", "2026-02-28", include_unposted=True), + ) + self.assertEqual(posted["value"], 300) + self.assertEqual(with_draft["value"], 350) + + def test_fetch_kpi_no_data(self): + (result,) = self._fetch(self._args("income", "2025-01-01", "2025-01-31")) + self.assertIs(result["value"], False) + + def test_fetch_kpi_one_evaluation_per_period(self): + with mock.patch.object( + MisReport, "evaluate", autospec=True, side_effect=MisReport.evaluate + ) as evaluate: + self._fetch( + self._args("income", "2026-01-01", "2026-01-31"), + self._args("receivable", "2026-01-01", "2026-01-31"), + self._args("margin", "2026-01-01", "2026-01-31"), + self._args("income", "2026-02-01", "2026-02-28"), + ) + self.assertEqual(evaluate.call_count, 2) + + def test_fetch_kpi_errors(self): + unknown_kpi, unknown_report, bad_dates, bad_company, ok = self._fetch( + self._args("unknown", "2026-01-01", "2026-01-31"), + dict(self._args("income", "2026-01-01", "2026-01-31"), report_id=0), + self._args("income", "2026-02-01", "2026-01-31"), + dict(self._args("income", "2026-01-01", "2026-01-31"), company_ids=[0]), + self._args("income", "2026-01-01", "2026-01-31"), + ) + self.assertIn("unknown", unknown_kpi["error"]) + self.assertIn("not found", unknown_report["error"]) + self.assertIn("start date", bad_dates["error"]) + self.assertIn("companies", bad_company["error"]) + self.assertEqual(ok["value"], 100) + + def test_fetch_kpi_subkpi(self): + report = self.env["mis.report"].create( + { + "name": "Spreadsheet MIS sub-KPI report", + "subkpi_ids": [ + Command.create({"name": "sk1", "description": "One"}), + Command.create({"name": "sk2", "description": "Two"}), + ], + } + ) + self.env["mis.report.kpi"].create( + { + "report_id": report.id, + "name": "multi", + "description": "Multi", + "multi": True, + "expression_ids": [ + Command.create( + {"name": "-balp[700IN]", "subkpi_id": report.subkpi_ids[0].id} + ), + Command.create( + {"name": "bale[400AR]", "subkpi_id": report.subkpi_ids[1].id} + ), + ], + } + ) + args = dict( + self._args("multi", "2026-01-01", "2026-01-31"), report_id=report.id + ) + missing, first, second, unknown = self._fetch( + args, + dict(args, subkpi="sk1"), + dict(args, subkpi="sk2"), + dict(args, subkpi="sk3"), + ) + self.assertIn("sub-KPIs", missing["error"]) + self.assertEqual(first["value"], 100) + self.assertEqual(second["value"], 100) + self.assertIn("sk3", unknown["error"]) + + def _create_instance(self): + instance = self.env["mis.report.instance"].create( + { + "name": "Spreadsheet MIS instance", + "report_id": self.report.id, + "company_id": self.company.id, + "comparison_mode": True, + "date": "2026-02-10", + "period_ids": [ + Command.create( + { + "name": "previous", + "mode": "relative", + "type": "m", + "offset": -1, + "duration": 1, + "sequence": 1, + } + ), + Command.create( + { + "name": "current", + "mode": "relative", + "type": "m", + "offset": 0, + "duration": 1, + "sequence": 2, + } + ), + Command.create( + { + "name": "fixed", + "mode": "fix", + "manual_date_from": "2026-01-01", + "manual_date_to": "2026-03-31", + "sequence": 3, + } + ), + ], + } + ) + previous, current, _fixed = instance.period_ids + instance.period_ids = [ + Command.create( + { + "name": "sum", + "mode": "none", + "source": "sumcol", + "source_sumcol_ids": [ + Command.create({"period_to_sum_id": previous.id, "sign": "+"}), + Command.create({"period_to_sum_id": current.id, "sign": "-"}), + ], + "sequence": 4, + } + ), + Command.create( + { + "name": "compare", + "mode": "none", + "source": "cmpcol", + "source_cmpcol_from_id": previous.id, + "source_cmpcol_to_id": current.id, + "sequence": 5, + } + ), + ] + return instance + + def test_export_spreadsheet(self): + instance = self._create_instance() + action = instance.action_export_spreadsheet() + self.assertEqual(action["tag"], "action_spreadsheet_oca") + spreadsheet = self.env["spreadsheet.spreadsheet"].browse( + action["params"]["spreadsheet_id"] + ) + self.assertEqual(spreadsheet.name, instance.name) + data = spreadsheet.spreadsheet_raw + sheet = data["sheets"][0] + cells = {xc: cell["content"] for xc, cell in sheet["cells"].items()} + # parameters + self.assertEqual(cells["B2"], str(self.report.id)) + self.assertEqual(cells["B3"], f'="{self.company.id}"') + self.assertEqual(cells["B4"], "FALSE") + self.assertEqual(cells["B5"], "=DATE(2026,2,10)") + # relative periods follow the base date, fixed ones do not + self.assertEqual(cells["B7"], "=EDATE(EOMONTH($B$5,-1)+1,-1)") + self.assertEqual(cells["B8"], "=EOMONTH($B$5,-1)") + self.assertEqual(cells["C7"], "=EDATE(EOMONTH($B$5,-1)+1,0)") + self.assertEqual(cells["C8"], "=EOMONTH($B$5,0)") + self.assertEqual(cells["D7"], "=DATE(2026,1,1)") + self.assertEqual(cells["D8"], "=DATE(2026,3,31)") + self.assertEqual( + [cells[xc] for xc in ("B9", "C9", "D9", "E9", "F9")], + ["previous", "current", "fixed", "sum", "compare"], + ) + # KPI rows + self.assertEqual(cells["A10"], "Income") + self.assertEqual(cells["B10"], '=MIS.KPI($B$2,"income",B$7,B$8,$B$3,$B$4)') + self.assertEqual(cells["D11"], '=MIS.KPI($B$2,"receivable",D$7,D$8,$B$3,$B$4)') + # sum and comparison columns are plain cell formulas + self.assertEqual(cells["E10"], "=+B10-C10") + self.assertEqual(cells["F10"], '=IF(B10=0,"",(C10-B10)/ABS(B10))') + self.assertEqual(cells["F11"], "=C11-B11") + self.assertEqual(cells["F12"], "=(C12-B12)*100") + # styles and formats + styles = data["styles"] + formats = data["formats"] + self.assertTrue(styles[str(sheet["styles"]["A10"])]["bold"]) + self.assertEqual(formats[str(sheet["formats"]["B10"])], "#,##0.00") + self.assertEqual(formats[str(sheet["formats"]["B12"])], "0%") + self.assertEqual(formats[str(sheet["formats"]["F10"])], "0.0%") + + def test_export_spreadsheet_static_column(self): + instance = self._create_instance() + instance.period_ids[0].analytic_domain = "[('partner_id', '=', False)]" + data = instance._spreadsheet_data() + sheet = data["sheets"][0] + cells = {xc: cell["content"] for xc, cell in sheet["cells"].items()} + self.assertEqual(cells["B9"], "previous (static)") + self.assertNotIn("B7", cells) + self.assertEqual(cells["B10"], "100.0") + self.assertTrue(cells["C10"].startswith("=MIS.KPI(")) + + def test_export_spreadsheet_no_comparison(self): + instance = self.env["mis.report.instance"].create( + { + "name": "Spreadsheet MIS simple", + "report_id": self.report.id, + "company_id": self.company.id, + "date_from": "2026-01-01", + "date_to": "2026-01-31", + "target_move": "all", + } + ) + instance.comparison_mode = False + data = instance._spreadsheet_data() + cells = {xc: cell["content"] for xc, cell in data["sheets"][0]["cells"].items()} + self.assertEqual(cells["B4"], "TRUE") + self.assertNotIn("B5", cells) + self.assertEqual(cells["B7"], "=DATE(2026,1,1)") + self.assertEqual(cells["B8"], "=DATE(2026,1,31)") diff --git a/spreadsheet_mis_builder/views/mis_report_instance.xml b/spreadsheet_mis_builder/views/mis_report_instance.xml new file mode 100644 index 00000000..ceee18b8 --- /dev/null +++ b/spreadsheet_mis_builder/views/mis_report_instance.xml @@ -0,0 +1,21 @@ + + + + + mis.report.instance + + + + + +