# -*- coding: utf-8 -*- """ DN Financial Report Engine — original implementation for Odoo 20 Community. Design (written from scratch, inspired by the generic "report as data" pattern): A report is pure DATA: a tree of lines, each line owning expressions. An expression is one calculation unit with an "engine" and a "formula": domain Python domain on account.move.line -> SUM(balance) account_codes Comma separated account-code prefixes -> SUM(balance) aggregation Arithmetic over other expression labels, e.g. "CA + RE" text A literal label The engine evaluates every expression once per "column group" (a period), then assembles the line tree. Rendering is delegated to a client action so the same payload can later be drawn as HTML / PDF / XLSX. Only depends on the LGPL-3 community `account` module. Odoo 20 notes (these differ from 17/18 and are the reason for several choices): * `read_group()` returns *tuples* and takes `aggregates=` (not list-of-dicts). `_read_group()` is the modern entry point and is used here. * Backend view tag is ``, `` no longer exists. * `_sql_constraints` is deprecated -> `models.Constraint(...)`. * QWeb uses `t-out` (`t-esc` is legacy). """ import ast import logging import re from odoo import _, api, fields, models from odoo.exceptions import UserError _logger = logging.getLogger(__name__) # Aggregation formulas are arithmetic only; keep the sandbox deliberately tiny. _SAFE_GLOBALS = {"__builtins__": {}, "abs": abs, "round": round, "max": max, "min": min} _TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") _SIGNED_NUMBER_RE = re.compile(r"^\s*-\s*\d") def _eval_aggregation(formula, variables): """Evaluate an arithmetic formula (e.g. ``CA + RE``) over `variables`.""" try: return eval(formula, _SAFE_GLOBALS, dict(variables)) # noqa: S307 - sandboxed except Exception as exc: # noqa: BLE001 - turn into a readable report error raise UserError( _("Invalid aggregation formula '%(f)s': %(e)s", f=formula, e=exc) ) from exc class DnReport(models.Model): _name = "dn.report" _description = "DN Financial Report" _order = "sequence, id" name = fields.Char(required=True, translate=True) code = fields.Char(required=True, help="Unique technical code of the report.") sequence = fields.Integer(default=10) active = fields.Boolean(default=True) description = fields.Text(translate=True) line_ids = fields.One2many("dn.report.line", "report_id", string="Lines") column_ids = fields.One2many("dn.report.column", "report_id", string="Columns") group_by_account = fields.Boolean( default=False, help="Generate one dynamic line per account (for ledgers)." ) _code_uniq = models.Constraint("unique(code)", "Report code must be unique.") # ------------------------------------------------------------------ # Public entry point (client action / controller) # ------------------------------------------------------------------ def get_report_data(self, options=None): """Return ``{columns, headers, lines}`` ready for rendering. :param options: dict with date_from, date_to, company_ids, column_groups, unfold_all """ self.ensure_one() options = self._normalize_options(options or {}) groups = self._column_groups(options) columns = [ { "key": "c%d" % idx, "label": g["label"], "date_from": g.get("date_from"), "date_to": g.get("date_to"), } for idx, g in enumerate(groups) ] return { "report_id": self.id, "name": self.name, "code": self.code, "columns": columns, "headers": [c["label"] for c in columns], "lines": self._compute_lines(options, groups), } # ------------------------------------------------------------------ # Options & columns # ------------------------------------------------------------------ def _normalize_options(self, options): options = dict(options or {}) if not options.get("company_ids"): options["company_ids"] = self.env.company.ids return options def _column_groups(self, options): groups = options.get("column_groups") if groups: normalized = [] for idx, g in enumerate(groups): normalized.append( { "label": g.get("label") or _("Period %s", idx + 1), "date_from": g.get("date_from"), "date_to": g.get("date_to"), } ) return normalized return [ { "label": options.get("column_label") or _("Amount of the period"), "date_from": options.get("date_from"), "date_to": options.get("date_to"), } ] # ------------------------------------------------------------------ # Calculation # ------------------------------------------------------------------ def _compute_lines(self, options, column_groups): expressions = self.line_ids.expression_ids values_per_column = {} for idx, group in enumerate(column_groups): values_per_column["c%d" % idx] = self._compute_expressions( options, group, expressions ) account_breakdown = None if self.group_by_account: account_breakdown = [ self._account_breakdown(options, group) for group in column_groups ] result = [] for line in self.line_ids.filtered(lambda l: not l.parent_id).sorted("sequence"): result.append( self._serialize_line(line, values_per_column, level=0, account_breakdown=account_breakdown) ) return result def _serialize_line(self, line, values_per_column, level, account_breakdown=None): children = [ self._serialize_line(child, values_per_column, level + 1) for child in line.children_ids.sorted("sequence") ] # Leaf ledger lines can be drilled down to one row per account. if not children and account_breakdown and not line.is_total: children = self._account_children(line, account_breakdown, level + 1) row = { "id": line.id, "code": line.code or "", "name": line.name, "level": level, "is_total": line.is_total, "foldable": bool(children), "values": { key: self._line_value(line, expr_values) for key, expr_values in values_per_column.items() }, "children": children, } return row # ------------------------------------------------------------------ # Optional drill-down: one child row per account # ------------------------------------------------------------------ def _account_breakdown(self, options, group): """Return {account_id: {code, name, balance}} for the period.""" domain = self._base_domain(options, group) rows = self.env["account.move.line"].sudo()._read_group( domain, groupby=["account_id"], aggregates=["balance:sum"], ) breakdown = {} for account, balance in rows: if not account: continue breakdown[account.id] = { "code": account.code or "", "name": account.name or "", "balance": float(balance or 0.0), } return breakdown def _account_children(self, line, account_breakdown, level): """Build one child row per account matching the line's expressions.""" matching = self._matching_account_ids(line, account_breakdown) if not matching: return [] children = [] for col_idx, breakdown in enumerate(account_breakdown): for account_id in matching: if account_id not in breakdown: continue info = breakdown[account_id] children.append( { "id": "acc-%s-%s" % (line.id, account_id), "code": info["code"], "name": info["name"], "level": level, "is_total": False, "foldable": False, "values": {"c%d" % col_idx: info["balance"]}, "children": [], } ) # Merge rows coming from several periods into a single row per account. merged = {} for child in children: existing = merged.setdefault( child["id"], dict(child, values={}, level=level, foldable=False, children=[]), ) existing["values"].update(child["values"]) return sorted(merged.values(), key=lambda c: (c["code"] or "", c["name"] or "")) def _matching_account_ids(self, line, account_breakdown): """Accounts whose journal items satisfy at least one expression. The discovery query runs on ``account.move.line`` (the expressions are written for that model), then the resulting accounts are intersected with the accounts that actually have a balance in the period. """ ids = set() ledger_exprs = line.expression_ids.filtered( lambda e: e.engine in ("domain", "account_codes") ) if not ledger_exprs: return ids for expr in ledger_exprs: try: if expr.engine == "domain": domain = self._parse_domain(expr.formula) else: domain = self._account_code_domain(expr.formula) except UserError: continue rows = self.env["account.move.line"].sudo()._read_group( domain, groupby=["account_id"] ) ids.update(account.id for account, in rows if account) if account_breakdown: ids &= set(account_breakdown[0]) return ids def _line_value(self, line, expr_values): """An explicit aggregation wins, otherwise the line's own sum.""" aggregation = line.expression_ids.filtered(lambda e: e.engine == "aggregation") for expr in aggregation: if expr.id in expr_values: return expr_values[expr.id]["value"] for expr in line.expression_ids: if expr.id in expr_values: return expr_values[expr.id]["value"] return 0.0 def _compute_expressions(self, options, group, expressions): """Evaluate every expression of the report for one column group.""" values = {} # 1) Ledger engines for expr in expressions.filtered(lambda e: e.engine in ("domain", "account_codes")): values[expr.id] = { "value": self._run_balance_engine(expr, options, group), "is_text": False, } # 2) Text engine for expr in expressions.filtered(lambda e: e.engine == "text"): values[expr.id] = {"value": expr.formula or "", "is_text": True} # 3) Aggregation — a formula may reference a label produced by another # aggregation, so keep looping until a round resolves nothing. pending = expressions.filtered(lambda e: e.engine == "aggregation") for _round in range(len(pending) + 1): if not pending: break resolved = self.env["dn.report.expression"] label_map = self._label_value_map(expressions, values) for expr in pending: try: computed = _eval_aggregation(expr.formula, label_map) except UserError: # Probably a label that is not computed yet: retry next round. continue values[expr.id] = {"value": computed, "is_text": False} resolved |= expr if expr.label: label_map[expr.label] = computed pending -= resolved if not resolved: _logger.warning( "DN report %s: unresolved aggregation formulas %s", self.code, pending.mapped("label"), ) break return values @staticmethod def _label_value_map(expressions, values): """Map expression label -> numeric value for aggregation formulas.""" label_map = {} for expr in expressions: payload = values.get(expr.id) if not payload or payload["is_text"] or not expr.label: continue label_map[expr.label] = label_map.get(expr.label, 0.0) + payload["value"] return label_map # ------------------------------------------------------------------ # Ledger engine — the only place that reads account.move.line # ------------------------------------------------------------------ def _run_balance_engine(self, expr, options, group): domain = self._base_domain(options, group) if expr.engine == "domain": domain = domain + self._parse_domain(expr.formula) else: # account_codes domain = domain + self._account_code_domain(expr.formula) if not domain: return 0.0 rows = self.env["account.move.line"].sudo()._read_group( domain, aggregates=["balance:sum"] ) # With no groupby, _read_group returns a single (sum,) row; an empty # recordset yields (None,) or (0,). return float(rows[0][0] or 0.0) if rows else 0.0 def _base_domain(self, options, group): domain = [("parent_state", "=", "posted")] company_ids = options.get("company_ids") or self.env.company.ids domain.append(("company_id", "in", company_ids)) date_from = group.get("date_from") or options.get("date_from") date_to = group.get("date_to") or options.get("date_to") if date_from: domain.append(("date", ">=", date_from)) if date_to: domain.append(("date", "<=", date_to)) return domain @staticmethod def _account_code_domain(formula): """Build an OR-ed prefix domain: ``"60,62"`` -> 60* or 62*.""" prefixes = [p.strip() for p in (formula or "").split(",") if p.strip()] if not prefixes: return [] domain = [] for prefix in prefixes[:-1]: domain += ["|", ("account_id.code", "=like", prefix + "%")] domain.append(("account_id.code", "=like", prefixes[-1] + "%")) return domain @staticmethod def _parse_domain(formula): try: parsed = ast.literal_eval((formula or "").strip()) except (ValueError, SyntaxError) as exc: raise UserError(_("Invalid domain formula: %s", formula)) from exc if not isinstance(parsed, (list, tuple)): raise UserError(_("Domain formula must be a list: %s", formula)) return list(parsed) class DnReportLine(models.Model): _name = "dn.report.line" _description = "DN Report Line" _order = "sequence, id" report_id = fields.Many2one("dn.report", required=True, ondelete="cascade") parent_id = fields.Many2one("dn.report.line", ondelete="cascade") children_ids = fields.One2many("dn.report.line", "parent_id") name = fields.Char(required=True, translate=True) code = fields.Char(help="Line code, unique within a report.") sequence = fields.Integer(default=10) is_total = fields.Boolean(default=False) expression_ids = fields.One2many("dn.report.expression", "report_line_id") class DnReportExpression(models.Model): _name = "dn.report.expression" _description = "DN Report Expression (calculation unit)" _order = "sequence, id" report_line_id = fields.Many2one("dn.report.line", required=True, ondelete="cascade") label = fields.Char(help="Name used by aggregation formulas.") formula = fields.Text(required=True) engine = fields.Selection( [ ("domain", "Domain on Journal Items"), ("account_codes", "Account Code Prefixes"), ("aggregation", "Aggregation"), ("text", "Text"), ], default="domain", required=True, ) sequence = fields.Integer(default=10) figure_type = fields.Selection( [("monetary", "Monetary"), ("integer", "Integer"), ("text", "Text")], default="monetary", ) class DnReportColumn(models.Model): _name = "dn.report.column" _description = "DN Report Column" _order = "sequence, id" report_id = fields.Many2one("dn.report", required=True, ondelete="cascade") name = fields.Char(required=True, translate=True) sequence = fields.Integer(default=10)