1204 lines
48 KiB
Python
1204 lines
48 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""DN Financial Reports — original engine for Odoo 20 Community.
|
|
|
|
This module is an independent, clean-room implementation. It does not contain
|
|
or derive from any Odoo Enterprise source file.
|
|
|
|
Design
|
|
------
|
|
A report is pure data:
|
|
|
|
dn.fr (report)
|
|
└── dn.fr.line (tree, unlimited depth)
|
|
└── dn.fr.expression (one value per column)
|
|
|
|
An expression pairs an *engine* with a *formula*. For every date period
|
|
(called a column group) the engine evaluates each expression and then assembles
|
|
the line tree that the web client renders.
|
|
|
|
Engines
|
|
-------
|
|
domain Python domain on account.move.line -> aggregate
|
|
account_codes Comma separated account code prefixes -> aggregate
|
|
aggregation Arithmetic over other expression labels
|
|
text A literal caption
|
|
reference A field value taken from a record
|
|
external A manually entered figure (budget, carry-over, ...)
|
|
ledger One expandable child row per journal item
|
|
agecalc Aging bucket total for receivable/payable items
|
|
custom Python callable registered by name on the report model
|
|
"""
|
|
import ast
|
|
import json
|
|
import logging
|
|
from datetime import date
|
|
|
|
from odoo import _, api, fields, models
|
|
from odoo.exceptions import UserError, ValidationError
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
# Aggregation formulas are evaluated with a restricted namespace: no builtins,
|
|
# no attribute access on arbitrary objects. Only arithmetic on numbers.
|
|
_SAFE_GLOBALS = {
|
|
"__builtins__": {},
|
|
"abs": abs, "round": round, "max": max, "min": min, "sum": sum,
|
|
"float": float, "int": int,
|
|
}
|
|
|
|
FIGURE_TYPES = [
|
|
("monetary", "Monetary"),
|
|
("integer", "Integer"),
|
|
("percent", "Percentage"),
|
|
("ratio", "Ratio"),
|
|
("string", "String"),
|
|
("date", "Date"),
|
|
]
|
|
|
|
DATE_SCOPES = [
|
|
("strict_range", "Strict range"),
|
|
("from_beginning", "From the beginning"),
|
|
("before_period", "Everything before the period (opening balance)"),
|
|
("previous_period", "Previous period"),
|
|
("previous_year", "Previous year"),
|
|
("today", "Today"),
|
|
("now", "Now"),
|
|
]
|
|
|
|
# How a set of journal items is reduced to a single figure. `balance` is the
|
|
# usual choice for statements; journal audits and turnover reports need the
|
|
# debit / credit columns instead, because their balances net out to zero.
|
|
MEASURES = [
|
|
("balance", "Net balance (debit - credit)"),
|
|
("debit", "Total debit"),
|
|
("credit", "Total credit"),
|
|
("abs_balance", "Net balance, absolute value"),
|
|
]
|
|
|
|
|
|
def _eval_aggregation(formula, variables):
|
|
"""Evaluate an arithmetic aggregation formula against a label -> number map."""
|
|
try:
|
|
return eval(formula, _SAFE_GLOBALS, dict(variables)) # noqa: S307
|
|
except ZeroDivisionError:
|
|
return 0.0
|
|
except Exception as exc:
|
|
raise UserError(
|
|
_("Invalid aggregation formula “%(formula)s”: %(error)s",
|
|
formula=formula, error=exc)
|
|
) from exc
|
|
|
|
|
|
class DnFr(models.Model):
|
|
_name = "dn.fr"
|
|
_description = "DN Financial Report"
|
|
_order = "sequence, id"
|
|
_parent_store = False
|
|
|
|
# ------------------------------------------------------------------ fields
|
|
name = fields.Char(required=True, translate=True)
|
|
code = fields.Char(required=True, index=True)
|
|
description = fields.Text(translate=True)
|
|
sequence = fields.Integer(default=10)
|
|
active = fields.Boolean(default=True)
|
|
line_ids = fields.One2many("dn.fr.line", "report_id", string="Lines")
|
|
|
|
root_report_id = fields.Many2one(
|
|
"dn.fr", string="Root Report", index=True, ondelete="cascade",
|
|
help="This report is a variant of the root report.",
|
|
)
|
|
variant_report_ids = fields.One2many(
|
|
"dn.fr", "root_report_id", string="Variants",
|
|
)
|
|
|
|
# Date defaults offered to the client
|
|
default_date_from = fields.Selection([
|
|
("start_of_fiscal_year", "Start of fiscal year"),
|
|
("start_of_month", "Start of month"),
|
|
("start_of_quarter", "Start of quarter"),
|
|
("start_of_year", "Start of year"),
|
|
("today", "Today"),
|
|
("none", "No start date"),
|
|
], default="start_of_fiscal_year", required=True)
|
|
default_date_to = fields.Selection([
|
|
("today", "Today"),
|
|
("end_of_month", "End of month"),
|
|
("end_of_quarter", "End of quarter"),
|
|
("end_of_year", "End of year"),
|
|
("none", "No end date"),
|
|
], default="today", required=True)
|
|
|
|
# Behaviours exposed to the client
|
|
allow_comparison = fields.Boolean(
|
|
default=True, help="Offer previous period / previous year comparison columns.",
|
|
)
|
|
allow_custom_periods = fields.Boolean(
|
|
default=True, help="Offer arbitrary column date ranges.",
|
|
)
|
|
allow_hierarchy = fields.Boolean(
|
|
default=True, help="Offer the grouping-by-account hierarchy filter.",
|
|
)
|
|
allow_unreconciled_only = fields.Boolean(
|
|
default=True, help="Offer the “unreconciled items only” filter.",
|
|
)
|
|
allow_draft_entries = fields.Boolean(
|
|
default=True, help="Offer the “include draft entries” filter.",
|
|
)
|
|
allow_journal_filter = fields.Boolean(
|
|
default=True, help="Offer the journal filter.",
|
|
)
|
|
allow_partner_filter = fields.Boolean(
|
|
default=True, help="Offer the partner filter.",
|
|
)
|
|
allow_multi_company = fields.Boolean(
|
|
default=False, help="Offer the multi-company selector.",
|
|
)
|
|
allow_export = fields.Boolean(default=True)
|
|
hide_zero_lines = fields.Boolean(
|
|
default=False, help="Hide lines whose every column is zero.",
|
|
)
|
|
unfold_all_by_default = fields.Boolean(default=False)
|
|
|
|
_code_uniq = models.Constraint("unique(code)", "Report code must be unique.")
|
|
|
|
# ------------------------------------------------------------- public API
|
|
def action_open(self):
|
|
"""Open this report in the web client."""
|
|
self.ensure_one()
|
|
return {
|
|
"type": "ir.actions.client",
|
|
"tag": "dn_fr_view",
|
|
"name": self.name,
|
|
"params": {"report_id": self.id},
|
|
}
|
|
|
|
@api.model
|
|
def get_default_dates(self, report_ids=None):
|
|
"""Expose the report's default period to the client renderer."""
|
|
report = self
|
|
if report_ids:
|
|
report = self.browse(report_ids[0] if isinstance(report_ids, (list, tuple))
|
|
else report_ids)
|
|
report.ensure_one()
|
|
date_from, date_to = report._default_dates()
|
|
return {"date_from": date_from, "date_to": date_to}
|
|
|
|
def get_report_data(self, options=None):
|
|
"""Return the fully computed report, ready for the client renderer."""
|
|
self.ensure_one()
|
|
options = self._normalize_options(options or {})
|
|
groups = self._column_groups(options)
|
|
|
|
column_keys = ["c%d" % idx for idx in range(len(groups))]
|
|
columns = []
|
|
for idx, group in enumerate(groups):
|
|
columns.append({
|
|
"key": column_keys[idx],
|
|
"label": group["label"],
|
|
"date_from": group.get("date_from"),
|
|
"date_to": group.get("date_to"),
|
|
"figure_type": group.get("figure_type", "monetary"),
|
|
})
|
|
|
|
expr_values = {key: {} for key in column_keys}
|
|
ledger_rows = {key: {} for key in column_keys}
|
|
for idx, group in enumerate(groups):
|
|
key = column_keys[idx]
|
|
scope = self._scope_options(options, group)
|
|
expression_values = self._compute_expressions(scope)
|
|
expr_values[key] = expression_values
|
|
ledger_rows[key] = self._compute_ledger(scope)
|
|
|
|
lines = [
|
|
self._serialize_line(line, expr_values, ledger_rows, column_keys, level=0)
|
|
for line in self.line_ids.filtered(lambda l: not l.parent_id).sorted(
|
|
lambda l: (l.sequence, l.id)
|
|
)
|
|
]
|
|
if options.get("hide_zero_lines") or self.hide_zero_lines:
|
|
lines = self._prune_zero_lines(lines)
|
|
|
|
return {
|
|
"report_id": self.id,
|
|
"code": self.code,
|
|
"name": self.name,
|
|
"description": self.description or "",
|
|
"columns": columns,
|
|
"headers": [c["label"] for c in columns],
|
|
"options": options,
|
|
"lines": lines,
|
|
"features": self._features(),
|
|
}
|
|
|
|
def _features(self):
|
|
return {
|
|
"comparison": self.allow_comparison,
|
|
"custom_periods": self.allow_custom_periods,
|
|
"hierarchy": self.allow_hierarchy,
|
|
"unreconciled_only": self.allow_unreconciled_only,
|
|
"draft_entries": self.allow_draft_entries,
|
|
"journal_filter": self.allow_journal_filter,
|
|
"partner_filter": self.allow_partner_filter,
|
|
"multi_company": self.allow_multi_company,
|
|
"export": self.allow_export,
|
|
"unfold_all": self.unfold_all_by_default,
|
|
}
|
|
|
|
# ------------------------------------------------------------- options
|
|
def _normalize_options(self, options):
|
|
options = dict(options or {})
|
|
if not options.get("company_ids"):
|
|
options["company_ids"] = self.env.company.ids
|
|
if "date_from" not in options or "date_to" not in options:
|
|
default_from, default_to = self._default_dates()
|
|
options.setdefault("date_from", default_from)
|
|
options.setdefault("date_to", default_to)
|
|
options.setdefault("unreconciled", False)
|
|
options.setdefault("include_draft", False)
|
|
options.setdefault("journal_ids", [])
|
|
options.setdefault("partner_ids", [])
|
|
options.setdefault("hidden_account_types", [])
|
|
return options
|
|
|
|
def _default_dates(self):
|
|
"""Compute the default date bounds requested by the report definition."""
|
|
today = fields.Date.context_today(self)
|
|
company = self.env.company
|
|
|
|
def _start_of(reference, unit):
|
|
if unit == "month":
|
|
return reference.replace(day=1)
|
|
if unit == "quarter":
|
|
month = ((reference.month - 1) // 3) * 3 + 1
|
|
return date(reference.year, month, 1)
|
|
return date(reference.year, 1, 1)
|
|
|
|
def _end_of(reference, unit):
|
|
if unit == "month":
|
|
return _shift_months(reference.replace(day=1), 1) - _one_day()
|
|
if unit == "quarter":
|
|
month = ((reference.month - 1) // 3) * 3 + 1
|
|
return _shift_months(date(reference.year, month, 1), 3) - _one_day()
|
|
return date(reference.year, 12, 31)
|
|
|
|
date_from = False
|
|
if self.default_date_from == "start_of_fiscal_year":
|
|
fiscal = company.compute_fiscalyear_dates(today)
|
|
date_from = fiscal["date_from"]
|
|
elif self.default_date_from == "start_of_month":
|
|
date_from = _start_of(today, "month")
|
|
elif self.default_date_from == "start_of_quarter":
|
|
date_from = _start_of(today, "quarter")
|
|
elif self.default_date_from == "start_of_year":
|
|
date_from = _start_of(today, "year")
|
|
elif self.default_date_from == "today":
|
|
date_from = today
|
|
|
|
date_to = False
|
|
if self.default_date_to == "today":
|
|
date_to = today
|
|
elif self.default_date_to == "end_of_month":
|
|
date_to = _end_of(today, "month")
|
|
elif self.default_date_to == "end_of_quarter":
|
|
date_to = _end_of(today, "quarter")
|
|
elif self.default_date_to == "end_of_year":
|
|
date_to = _end_of(today, "year")
|
|
|
|
return (
|
|
fields.Date.to_string(date_from) if date_from else False,
|
|
fields.Date.to_string(date_to) if date_to else False,
|
|
)
|
|
|
|
def _column_groups(self, options):
|
|
"""Build the list of column groups (each one is a period)."""
|
|
groups = options.get("column_groups")
|
|
if groups:
|
|
normalized = []
|
|
for idx, group in enumerate(groups):
|
|
normalized.append({
|
|
"label": group.get("label") or _("Period %s", idx + 1),
|
|
"date_from": group.get("date_from") or options.get("date_from"),
|
|
"date_to": group.get("date_to") or options.get("date_to"),
|
|
"figure_type": group.get("figure_type", "monetary"),
|
|
})
|
|
return normalized
|
|
|
|
base_from = options.get("date_from") or False
|
|
base_to = options.get("date_to") or False
|
|
label = options.get("column_label") or self._period_label(base_from, base_to)
|
|
groups = [{"label": label, "date_from": base_from, "date_to": base_to}]
|
|
|
|
comparison = options.get("comparison") or ""
|
|
if comparison and self.allow_comparison:
|
|
if comparison == "previous_period":
|
|
shift = _period_length(base_from, base_to)
|
|
groups.append({
|
|
"label": _("Previous Period"),
|
|
"date_from": _shift_days(base_from, -shift - 1),
|
|
"date_to": _shift_days(base_from, -1),
|
|
})
|
|
elif comparison == "previous_year":
|
|
groups.append({
|
|
"label": _("Previous Year"),
|
|
"date_from": _shift_years(base_from, -1),
|
|
"date_to": _shift_years(base_to, -1),
|
|
})
|
|
elif comparison == "both" and base_from and base_to:
|
|
shift = _period_length(base_from, base_to)
|
|
groups.append({
|
|
"label": _("Previous Period"),
|
|
"date_from": _shift_days(base_from, -shift - 1),
|
|
"date_to": _shift_days(base_from, -1),
|
|
})
|
|
groups.append({
|
|
"label": _("Previous Year"),
|
|
"date_from": _shift_years(base_from, -1),
|
|
"date_to": _shift_years(base_to, -1),
|
|
})
|
|
return groups
|
|
|
|
@staticmethod
|
|
def _period_label(date_from, date_to):
|
|
if date_from and date_to:
|
|
return "%s → %s" % (date_from, date_to)
|
|
if date_to:
|
|
return _("As of %s", date_to)
|
|
if date_from:
|
|
return _("From %s", date_from)
|
|
return _("All dates")
|
|
|
|
def _scope_options(self, options, group):
|
|
"""Options narrowed to a single column group."""
|
|
scope = dict(options)
|
|
scope["date_from"] = group.get("date_from")
|
|
scope["date_to"] = group.get("date_to")
|
|
return scope
|
|
|
|
# ---------------------------------------------------------- calculation
|
|
def _compute_expressions(self, options):
|
|
"""Evaluate every non-ledger expression, honouring date scopes."""
|
|
expressions = self.line_ids.expression_ids
|
|
values = {}
|
|
|
|
simple = expressions.filtered(
|
|
lambda e: e.engine in ("domain", "account_codes", "reference", "external")
|
|
)
|
|
for expr in simple:
|
|
scope = self._expression_options(options, expr)
|
|
values[expr.id] = {
|
|
"value": self._apply_sign(expr, self._run_value_engine(expr, scope)),
|
|
"is_text": False,
|
|
}
|
|
|
|
for expr in expressions.filtered(lambda e: e.engine == "text"):
|
|
values[expr.id] = {"value": expr.formula or "", "is_text": True}
|
|
|
|
for expr in expressions.filtered(lambda e: e.engine == "agecalc"):
|
|
scope = self._expression_options(options, expr)
|
|
values[expr.id] = {
|
|
"value": self._apply_sign(expr, self._run_age_engine(expr, scope)),
|
|
"is_text": False,
|
|
}
|
|
|
|
# Aggregations may reference each other: iterate until stable.
|
|
pending = expressions.filtered(lambda e: e.engine in ("aggregation", "custom"))
|
|
for _attempt in range(len(pending) + 2):
|
|
if not pending:
|
|
break
|
|
label_map = self._label_value_map(expressions, values)
|
|
resolved = self.env["dn.fr.expression"]
|
|
for expr in pending:
|
|
if expr.engine == "custom":
|
|
computed = self._run_custom_engine(expr, options, label_map)
|
|
else:
|
|
try:
|
|
computed = _eval_aggregation(expr.formula, label_map)
|
|
except UserError:
|
|
continue
|
|
values[expr.id] = {"value": self._round_amount(computed), "is_text": False}
|
|
resolved |= expr
|
|
if expr.label:
|
|
label_map[expr.label] = computed
|
|
pending -= resolved
|
|
if not resolved:
|
|
break
|
|
return values
|
|
|
|
@staticmethod
|
|
def _round_amount(value):
|
|
"""Normalise a computed amount: kill float noise and negative zero."""
|
|
if isinstance(value, str) or value is None:
|
|
return value
|
|
try:
|
|
return round(float(value), 2) + 0.0
|
|
except (TypeError, ValueError):
|
|
return value
|
|
|
|
@staticmethod
|
|
def _apply_sign(expression, value):
|
|
"""Flip a debit-positive balance so credit accounts read as positive."""
|
|
if isinstance(value, str):
|
|
return value
|
|
try:
|
|
amount = float(value or 0.0)
|
|
except (TypeError, ValueError):
|
|
return value
|
|
if expression.sign == "-1":
|
|
amount = -amount
|
|
# Round here so the renderer never shows a "-0.00" left over from
|
|
# floating point noise (e.g. -1e-15 after a sign flip).
|
|
return round(amount, 2) + 0.0
|
|
|
|
def _expression_options(self, options, expression):
|
|
scope = dict(options)
|
|
date_from = options.get("date_from")
|
|
date_to = options.get("date_to")
|
|
kind = expression.date_scope or "strict_range"
|
|
|
|
if kind == "from_beginning":
|
|
scope["date_from"] = False
|
|
elif kind == "before_period":
|
|
# Opening balance: everything posted strictly before day one.
|
|
scope["date_from"] = False
|
|
scope["date_to"] = _shift_days(date_from, -1) if date_from else False
|
|
elif kind == "previous_period":
|
|
length = _period_length(date_from, date_to)
|
|
scope["date_from"] = _shift_days(date_from, -length - 1) if date_from else False
|
|
scope["date_to"] = _shift_days(date_from, -1) if date_from else False
|
|
elif kind == "previous_year":
|
|
scope["date_from"] = _shift_years(date_from, -1)
|
|
scope["date_to"] = _shift_years(date_to, -1)
|
|
elif kind == "today":
|
|
today = fields.Date.to_string(fields.Date.context_today(self))
|
|
scope["date_from"] = today
|
|
scope["date_to"] = today
|
|
elif kind == "now":
|
|
today = fields.Date.to_string(fields.Date.context_today(self))
|
|
scope["date_from"] = today
|
|
scope["date_to"] = today
|
|
return scope
|
|
|
|
@staticmethod
|
|
def _label_value_map(expressions, values):
|
|
label_map = {}
|
|
for expr in expressions:
|
|
payload = values.get(expr.id)
|
|
if not payload or payload["is_text"] or not expr.label:
|
|
continue
|
|
try:
|
|
label_map[expr.label] = label_map.get(expr.label, 0.0) + float(
|
|
payload["value"] or 0.0
|
|
)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
return label_map
|
|
|
|
# ------------------------------------------------------------- engines
|
|
def _run_value_engine(self, expression, options):
|
|
engine = expression.engine
|
|
if engine == "domain":
|
|
return self._sum_balance(
|
|
options, self._parse_domain(expression.formula), expression.measure
|
|
)
|
|
if engine == "account_codes":
|
|
return self._sum_balance(
|
|
options,
|
|
self._account_code_domain(expression.formula),
|
|
expression.measure,
|
|
)
|
|
if engine == "external":
|
|
return self._external_value(expression, options)
|
|
if engine == "reference":
|
|
return self._reference_value(expression, options)
|
|
return 0.0
|
|
|
|
def _sum_balance(self, options, extra_domain, measure="balance"):
|
|
return self._aggregate_measure(
|
|
self._base_domain(options) + extra_domain, measure
|
|
)
|
|
|
|
def _aggregate_measure(self, domain, measure="balance"):
|
|
"""Aggregate journal items using the requested measure."""
|
|
aggregate = "%s:sum" % (measure if measure != "abs_balance" else "balance")
|
|
rows = self.env["account.move.line"].sudo()._read_group(
|
|
domain, aggregates=[aggregate],
|
|
)
|
|
value = float(rows[0][0] or 0.0) if rows else 0.0
|
|
if measure == "abs_balance":
|
|
value = abs(value)
|
|
return value
|
|
|
|
def _external_value(self, expression, options):
|
|
"""Sum manually entered figures matching the expression and period."""
|
|
domain = [("expression_id", "=", expression.id)]
|
|
date_from = options.get("date_from")
|
|
date_to = options.get("date_to")
|
|
if date_from:
|
|
domain.append(("date", ">=", date_from))
|
|
if date_to:
|
|
domain.append(("date", "<=", date_to))
|
|
values = self.env["dn.fr.external.value"].sudo().search(domain)
|
|
return float(sum(values.mapped("amount") or [0.0]))
|
|
|
|
def _reference_value(self, expression, options):
|
|
"""Read a numeric field from a record referenced by the formula."""
|
|
try:
|
|
model_name, res_id, field_name = (expression.formula or "").split(",", 2)
|
|
record = self.env[model_name.strip()].sudo().browse(int(res_id.strip()))
|
|
if not record.exists():
|
|
return 0.0
|
|
value = record[field_name.strip()]
|
|
return float(value or 0.0)
|
|
except Exception:
|
|
_logger.warning("Invalid reference formula: %s", expression.formula)
|
|
return 0.0
|
|
|
|
def _run_age_engine(self, expression, options):
|
|
"""Aging bucket total for receivable / payable items.
|
|
|
|
Formula format: ``receivable:0-30``, ``payable:61-90``, ``receivable:current``.
|
|
"""
|
|
try:
|
|
kind, bucket = (expression.formula or "").split(":", 1)
|
|
except ValueError:
|
|
raise UserError(
|
|
_("Aging formula must look like “receivable:0-30”: %s",
|
|
expression.formula)
|
|
)
|
|
kind = kind.strip().lower()
|
|
if kind not in ("receivable", "payable"):
|
|
raise UserError(_("Aging formula must start with receivable or payable."))
|
|
account_type = (
|
|
"asset_receivable" if kind == "receivable" else "liability_payable"
|
|
)
|
|
domain = self._base_domain(options)
|
|
domain += [
|
|
("account_id.account_type", "=", account_type),
|
|
("amount_residual", "!=", 0.0),
|
|
("full_reconcile_id", "=", False),
|
|
]
|
|
lines = self.env["account.move.line"].sudo().search(domain)
|
|
today = fields.Date.context_today(self)
|
|
low, high = self._bucket_range(bucket.strip())
|
|
total = 0.0
|
|
for line in lines:
|
|
due = line.date_maturity or line.date or today
|
|
days = (today - due).days
|
|
if low <= days <= high:
|
|
total += float(line.amount_residual or 0.0)
|
|
return total
|
|
|
|
def _run_custom_engine(self, expression, options, label_map):
|
|
"""Dispatch to a Python callable named by the formula."""
|
|
handler = getattr(self, expression.formula or "", None)
|
|
if not callable(handler):
|
|
raise UserError(
|
|
_("Custom engine formula must name a method on the report: %s",
|
|
expression.formula)
|
|
)
|
|
result = handler(options, label_map)
|
|
return float(result or 0.0)
|
|
|
|
# -------------------------------------------------------------- ledger
|
|
def _compute_ledger(self, options):
|
|
"""Return {expression_id: [journal item row, ...]} for ledger engines."""
|
|
result = {}
|
|
ledger_exprs = self.line_ids.expression_ids.filtered(
|
|
lambda e: e.engine == "ledger"
|
|
)
|
|
for expr in ledger_exprs:
|
|
scope = self._expression_options(options, expr)
|
|
extra = self._parse_domain(expr.formula) if expr.formula else []
|
|
domain = self._base_domain(scope) + extra
|
|
lines = self.env["account.move.line"].sudo().search(
|
|
domain, order="date, move_name, id",
|
|
)
|
|
rows = []
|
|
running = 0.0
|
|
flip = expr.sign == "-1"
|
|
for line in lines:
|
|
balance = float(line.balance or 0.0)
|
|
running += balance
|
|
rows.append({
|
|
"id": "aml-%s" % line.id,
|
|
"line_id": line.id,
|
|
"date": fields.Date.to_string(line.date) if line.date else "",
|
|
"move_name": line.move_id.name or "",
|
|
"partner": line.partner_id.display_name or "",
|
|
"account_code": line.account_id.code or "",
|
|
"account_name": line.account_id.name or "",
|
|
"label": line.name or "",
|
|
"currency": line.currency_id.name or "",
|
|
"amount_currency": float(line.amount_currency or 0.0),
|
|
"debit": float(line.debit or 0.0),
|
|
"credit": float(line.credit or 0.0),
|
|
# The balance and the running total follow the expression's
|
|
# sign convention so a payable ledger reads positive too.
|
|
"balance": -balance if flip else balance,
|
|
"cumulative": -running if flip else running,
|
|
"residual": float(line.amount_residual or 0.0),
|
|
})
|
|
result[expr.id] = rows
|
|
return result
|
|
|
|
# -------------------------------------------------------------- domains
|
|
def _base_domain(self, options):
|
|
# Exclude pure presentation lines (section headers and notes); they
|
|
# carry no amount. In Odoo 20 a real journal item has display_type set
|
|
# to 'product' / 'cogs' / 'tax' / ... rather than False.
|
|
domain = [("display_type", "not in", ["line_section", "line_note", "line_subsection"])]
|
|
states = ["posted"]
|
|
if options.get("include_draft"):
|
|
states.append("draft")
|
|
domain.append(("parent_state", "in", states))
|
|
company_ids = options.get("company_ids") or self.env.company.ids
|
|
domain.append(("company_id", "in", company_ids))
|
|
date_from = options.get("date_from")
|
|
date_to = options.get("date_to")
|
|
if date_from:
|
|
domain.append(("date", ">=", date_from))
|
|
if date_to:
|
|
domain.append(("date", "<=", date_to))
|
|
if options.get("unreconciled"):
|
|
domain += [("reconciled", "=", False),
|
|
("account_id.reconcile", "=", True)]
|
|
journal_ids = options.get("journal_ids")
|
|
if journal_ids:
|
|
domain.append(("journal_id", "in", journal_ids))
|
|
hidden_types = options.get("hidden_account_types")
|
|
if hidden_types:
|
|
domain.append(("account_id.account_type", "not in", hidden_types))
|
|
return domain + self._partner_domain(options)
|
|
|
|
@staticmethod
|
|
def _partner_domain(options):
|
|
partner_ids = options.get("partner_ids")
|
|
if partner_ids:
|
|
return [("partner_id", "in", partner_ids)]
|
|
return []
|
|
|
|
@staticmethod
|
|
def _account_code_domain(formula):
|
|
"""Turn “60,61,62” into an OR-ed prefix domain on the account code."""
|
|
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):
|
|
text = (formula or "").strip()
|
|
if not text:
|
|
return []
|
|
try:
|
|
parsed = ast.literal_eval(text)
|
|
except (ValueError, SyntaxError) as exc:
|
|
raise UserError(
|
|
_("Invalid domain formula: %s", text)
|
|
) from exc
|
|
if not isinstance(parsed, (list, tuple)):
|
|
raise UserError(_("Domain formula must be a list: %s", text))
|
|
return list(parsed)
|
|
|
|
@staticmethod
|
|
def _bucket_range(bucket):
|
|
ranges = {
|
|
"current": (-10 ** 9, 0),
|
|
"0-30": (1, 30),
|
|
"31-60": (31, 60),
|
|
"61-90": (61, 90),
|
|
"91-120": (91, 120),
|
|
"121+": (121, 10 ** 9),
|
|
"not_due": (-10 ** 9, 0),
|
|
}
|
|
if bucket not in ranges:
|
|
raise UserError(_("Unknown aging bucket: %s", bucket))
|
|
return ranges[bucket]
|
|
|
|
# ----------------------------------------------------------- rendering
|
|
def _serialize_line(self, line, expr_values, ledger_rows, column_keys, level):
|
|
children = [
|
|
self._serialize_line(child, expr_values, ledger_rows, column_keys, level + 1)
|
|
for child in line.children_ids.sorted(lambda c: (c.sequence, c.id))
|
|
]
|
|
values = {}
|
|
for key in column_keys:
|
|
payload = self._line_payload(line, expr_values.get(key, {}))
|
|
values[key] = payload
|
|
|
|
row = {
|
|
"id": line.id,
|
|
"code": line.code or "",
|
|
"name": line.name,
|
|
"level": level,
|
|
"is_total": bool(line.is_total),
|
|
"unfoldable": bool(children),
|
|
"hide_if_zero": bool(line.hide_if_zero),
|
|
"figure_type": line.figure_type or "monetary",
|
|
"action_id": line.action_id.id if line.action_id else False,
|
|
"values": {key: payload["value"] for key, payload in values.items()},
|
|
"is_text": {key: payload["is_text"] for key, payload in values.items()},
|
|
"children": children,
|
|
}
|
|
|
|
# A leaf line driven by a ledger expression expands into detail rows.
|
|
if not children:
|
|
ledger_expr = line.expression_ids.filtered(lambda e: e.engine == "ledger")
|
|
if ledger_expr:
|
|
detail = self._merge_ledger_rows(
|
|
ledger_expr, ledger_rows, column_keys, level + 1
|
|
)
|
|
if detail:
|
|
row["children"] = detail
|
|
row["unfoldable"] = True
|
|
row["ledger_columns"] = [
|
|
"date", "move_name", "account_code", "label",
|
|
"debit", "credit", "balance", "cumulative",
|
|
]
|
|
# A ledger line carries no expression value of its own; its
|
|
# figure is the sum of the journal items it expands into.
|
|
for key in column_keys:
|
|
row["values"][key] = self._round_amount(
|
|
sum(d["values"].get(key) or 0.0 for d in detail)
|
|
)
|
|
return row
|
|
|
|
def _line_payload(self, line, expr_values):
|
|
"""Pick the displayed expression: aggregation first, then the first one."""
|
|
ordered = line.expression_ids.sorted(lambda e: (e.sequence, e.id))
|
|
aggregation = ordered.filtered(lambda e: e.engine == "aggregation")
|
|
for expr in list(aggregation) + list(ordered):
|
|
payload = expr_values.get(expr.id)
|
|
if payload is not None:
|
|
return payload
|
|
return {"value": 0.0 if line.figure_type != "string" else "", "is_text": False}
|
|
|
|
@staticmethod
|
|
def _merge_ledger_rows(ledger_exprs, ledger_rows, column_keys, level):
|
|
"""Merge per-column ledger rows into one row per journal item."""
|
|
merged = {}
|
|
for key in column_keys:
|
|
for expr in ledger_exprs:
|
|
for item in ledger_rows.get(key, {}).get(expr.id, []):
|
|
row = merged.setdefault(item["id"], {
|
|
"id": item["id"],
|
|
"code": item.get("account_code", ""),
|
|
"name": "%s %s" % (item.get("date", ""), item.get("label", "")),
|
|
"level": level,
|
|
"is_total": False,
|
|
"unfoldable": False,
|
|
"hide_if_zero": False,
|
|
"figure_type": "monetary",
|
|
"detail": item,
|
|
"values": {},
|
|
"is_text": {},
|
|
"children": [],
|
|
})
|
|
row["values"][key] = item["balance"]
|
|
row["values"][key + "_debit"] = item["debit"]
|
|
row["values"][key + "_credit"] = item["credit"]
|
|
return sorted(
|
|
merged.values(),
|
|
key=lambda r: (r["detail"].get("date", ""), r["detail"].get("move_name", "")),
|
|
)
|
|
|
|
def _prune_zero_lines(self, lines):
|
|
kept = []
|
|
for line in lines:
|
|
line["children"] = self._prune_zero_lines(line.get("children") or [])
|
|
has_value = any(
|
|
isinstance(v, (int, float)) and abs(v) > 0.0001
|
|
for v in (line.get("values") or {}).values()
|
|
)
|
|
if has_value or line["children"] or line.get("is_total"):
|
|
kept.append(line)
|
|
return kept
|
|
|
|
# ------------------------------------------------------------ defaults
|
|
@api.model
|
|
def _get_or_create_report(self, code):
|
|
report = self.search([("code", "=", code)], limit=1)
|
|
if not report:
|
|
raise UserError(_("Report “%s” is not installed.", code))
|
|
return report
|
|
|
|
# ------------------------------------------------- custom engine library
|
|
# These methods are called from ``custom`` expressions. The formula field
|
|
# holds the method name, e.g. ``_custom_cash_flow_operating``.
|
|
|
|
def _custom_cash_flow_operating(self, options, label_map):
|
|
"""Cash movement generated by operating activities."""
|
|
return self._cash_flow_by_activity(options).get("operating", 0.0)
|
|
|
|
def _custom_cash_flow_investing(self, options, label_map):
|
|
"""Cash movement generated by investing activities."""
|
|
return self._cash_flow_by_activity(options).get("investing", 0.0)
|
|
|
|
def _custom_cash_flow_financing(self, options, label_map):
|
|
"""Cash movement generated by financing activities."""
|
|
return self._cash_flow_by_activity(options).get("financing", 0.0)
|
|
|
|
_CASH_ACCOUNT_TYPES = ("asset_cash", "liability_credit_card")
|
|
_INVESTING_ACCOUNT_TYPES = ("asset_fixed", "asset_non_current", "liability_credit")
|
|
_FINANCING_ACCOUNT_TYPES = ("equity", "equity_unaffected", "equity_retained",
|
|
"liability_non_current")
|
|
|
|
def _cash_flow_by_activity(self, options):
|
|
"""Split the period's cash movement into operating / investing / financing.
|
|
|
|
A cash movement is classified by the *counterpart* account of the entry,
|
|
not by the journal: a bank journal can book an equity injection just as
|
|
well as a customer receipt. When one entry mixes several counterparts,
|
|
the cash amount is allocated pro rata to their absolute amounts.
|
|
"""
|
|
Line = self.env["account.move.line"].sudo()
|
|
base = self._base_domain(options)
|
|
cash_domain = base + [("account_id.account_type", "in", list(self._CASH_ACCOUNT_TYPES))]
|
|
cash_lines = Line.search(cash_domain)
|
|
if not cash_lines:
|
|
return {"operating": 0.0, "investing": 0.0, "financing": 0.0}
|
|
|
|
totals = {"operating": 0.0, "investing": 0.0, "financing": 0.0}
|
|
by_move = {}
|
|
for line in cash_lines:
|
|
by_move.setdefault(line.move_id.id, {"cash": 0.0, "move": line.move_id})
|
|
by_move[line.move_id.id]["cash"] += line.balance
|
|
|
|
for entry in by_move.values():
|
|
move, cash_delta = entry["move"], entry["cash"]
|
|
if not cash_delta:
|
|
continue
|
|
counterparts = move.line_ids.filtered(
|
|
lambda l, mv=move: l.account_id.account_type not in self._CASH_ACCOUNT_TYPES
|
|
and l.display_type not in ("line_section", "line_note", "line_subsection")
|
|
)
|
|
weights = {}
|
|
for line in counterparts:
|
|
if line.account_id.account_type in self._INVESTING_ACCOUNT_TYPES:
|
|
bucket = "investing"
|
|
elif line.account_id.account_type in self._FINANCING_ACCOUNT_TYPES:
|
|
bucket = "financing"
|
|
else:
|
|
bucket = "operating"
|
|
weights[bucket] = weights.get(bucket, 0.0) + abs(line.balance)
|
|
|
|
total_weight = sum(weights.values())
|
|
if not total_weight:
|
|
totals["operating"] += cash_delta
|
|
continue
|
|
for bucket, weight in weights.items():
|
|
totals[bucket] += cash_delta * weight / total_weight
|
|
return totals
|
|
|
|
def _custom_net_profit(self, options, label_map):
|
|
domain = self._base_domain(options)
|
|
domain += [("account_id.internal_group", "in", ["income", "expense"])]
|
|
return -self._sum_with_domain(domain)
|
|
|
|
def _custom_balance_total(self, options, label_map):
|
|
return self._sum_with_domain(self._base_domain(options))
|
|
|
|
def _custom_partner_balance(self, options, label_map):
|
|
return self._sum_with_domain(self._base_domain(options))
|
|
|
|
def _sum_with_domain(self, domain):
|
|
return self._aggregate_measure(domain, "balance")
|
|
|
|
def _custom_deferred_amount(self, options, label_map):
|
|
"""Unrecognised portion of deferred entries inside the period."""
|
|
domain = self._base_domain(options)
|
|
domain += [
|
|
("account_id.account_type", "in", [
|
|
"asset_prepayments", "liability_prepayment",
|
|
]),
|
|
]
|
|
return self._sum_with_domain(domain)
|
|
|
|
def _custom_unrealized_gain_loss(self, options, label_map):
|
|
"""Residual on foreign-currency receivable/payable items."""
|
|
domain = self._base_domain(options)
|
|
domain += [
|
|
("account_id.account_type", "in", [
|
|
"asset_receivable", "liability_payable",
|
|
]),
|
|
("amount_residual", "!=", 0.0),
|
|
("currency_id", "!=", self.env.company.currency_id.id),
|
|
]
|
|
lines = self.env["account.move.line"].sudo().search(domain)
|
|
total = 0.0
|
|
company_currency = self.env.company.currency_id
|
|
for line in lines:
|
|
if not line.currency_id or not line.amount_currency:
|
|
continue
|
|
converted = line.currency_id._convert(
|
|
line.amount_currency, company_currency, line.company_id, line.date,
|
|
)
|
|
total += float(converted - line.balance)
|
|
return total
|
|
|
|
def _custom_sales_total(self, options, label_map):
|
|
"""Total income, expressed as a positive amount (credit balance)."""
|
|
domain = self._base_domain(options)
|
|
domain += [("account_id.internal_group", "=", "income")]
|
|
return -self._sum_with_domain(domain)
|
|
|
|
def _custom_purchase_total(self, options, label_map):
|
|
domain = self._base_domain(options)
|
|
domain += [("account_id.internal_group", "=", "expense")]
|
|
return self._sum_with_domain(domain)
|
|
|
|
# -------------------------------------------------------------- tax
|
|
#
|
|
# Tax amounts live on their own journal items. Odoo tags them with
|
|
# `tax_line_id` when the tax was generated by the tax engine, but a
|
|
# journal entry typed by hand only records `tax_ids` on the base line.
|
|
# Both cases must be covered, so we look at the tax tag on the line and fall
|
|
# back to the account's tax configuration.
|
|
|
|
def _tax_amount(self, options, use):
|
|
"""Net tax amount for sale or purchase taxes, as a positive figure.
|
|
|
|
Two data shapes must be handled:
|
|
|
|
1. Items created by the tax engine carry ``tax_line_id``. Sale tax sits
|
|
on the credit side, purchase tax on the debit side, so the sign of
|
|
the balance tells us the direction already.
|
|
2. Items typed by hand only tag ``tax_ids`` on the base line, so the tax
|
|
amount never gets its own ``tax_line_id``. For those we fall back to
|
|
the tax accounts declared on the tax definition.
|
|
"""
|
|
domain = self._base_domain(options) + [
|
|
("tax_line_id", "!=", False),
|
|
("tax_line_id.type_tax_use", "=", use),
|
|
]
|
|
# Output tax is a credit (negative balance), input tax is a debit.
|
|
amount = self._aggregate_measure(domain, "balance")
|
|
if amount:
|
|
return amount if use == "purchase" else -amount
|
|
|
|
taxes = self.env["account.tax"].search([("type_tax_use", "=", use)])
|
|
account_ids = taxes.mapped("invoice_repartition_line_ids.account_id") | taxes.mapped(
|
|
"refund_repartition_line_ids.account_id"
|
|
)
|
|
if not account_ids:
|
|
return 0.0
|
|
domain = self._base_domain(options) + [("account_id", "in", account_ids.ids)]
|
|
return abs(self._aggregate_measure(domain, "balance"))
|
|
|
|
def _custom_tax_output(self, options, label_map):
|
|
"""Output VAT collected on sales."""
|
|
return self._tax_amount(options, "sale")
|
|
|
|
def _custom_tax_input(self, options, label_map):
|
|
"""Input VAT paid on purchases."""
|
|
return self._tax_amount(options, "purchase")
|
|
|
|
def _custom_tax_base_sale(self, options, label_map):
|
|
"""Taxable sales base (income before tax)."""
|
|
domain = self._base_domain(options) + [
|
|
("account_id.internal_group", "=", "income"),
|
|
]
|
|
return -self._sum_with_domain(domain)
|
|
|
|
|
|
class DnFrLine(models.Model):
|
|
_name = "dn.fr.line"
|
|
_description = "DN Financial Report Line"
|
|
_order = "sequence, id"
|
|
|
|
report_id = fields.Many2one(
|
|
"dn.fr", required=True, ondelete="cascade", index=True,
|
|
)
|
|
parent_id = fields.Many2one(
|
|
"dn.fr.line", string="Parent Line", ondelete="cascade", index=True,
|
|
)
|
|
children_ids = fields.One2many("dn.fr.line", "parent_id", string="Child Lines")
|
|
name = fields.Char(required=True, translate=True)
|
|
code = fields.Char(help="Short identifier, displayed before the name.")
|
|
sequence = fields.Integer(default=10)
|
|
is_total = fields.Boolean(
|
|
default=False, help="Render this line in bold as a subtotal or total.",
|
|
)
|
|
hide_if_zero = fields.Boolean(
|
|
default=False, help="Hide this line when all its columns are zero.",
|
|
)
|
|
figure_type = fields.Selection(
|
|
FIGURE_TYPES, default="monetary", required=True,
|
|
)
|
|
action_id = fields.Many2one(
|
|
"ir.actions.actions", string="Drill-down Action",
|
|
help="When set, the line becomes a link opening this action.",
|
|
)
|
|
expression_ids = fields.One2many(
|
|
"dn.fr.expression", "report_line_id", string="Expressions",
|
|
)
|
|
|
|
@api.constrains("parent_id")
|
|
def _check_parent(self):
|
|
for line in self:
|
|
if line.parent_id and line.parent_id.report_id != line.report_id:
|
|
raise ValidationError(
|
|
_("A child line must belong to the same report as its parent.")
|
|
)
|
|
seen = self
|
|
node = line.parent_id
|
|
while node:
|
|
if node in seen:
|
|
raise ValidationError(_("Recursive line hierarchy detected."))
|
|
seen |= node
|
|
node = node.parent_id
|
|
|
|
|
|
class DnFrExpression(models.Model):
|
|
_name = "dn.fr.expression"
|
|
_description = "DN Financial Report Expression"
|
|
_order = "sequence, id"
|
|
|
|
report_line_id = fields.Many2one(
|
|
"dn.fr.line", required=True, ondelete="cascade", index=True,
|
|
)
|
|
label = fields.Char(
|
|
help="Unique name used by aggregation formulas to reference this value.",
|
|
)
|
|
formula = fields.Text(required=True)
|
|
engine = fields.Selection([
|
|
("domain", "Odoo Domain on Journal Items"),
|
|
("account_codes", "Prefixes of Account Codes"),
|
|
("aggregation", "Aggregate Other Formulas"),
|
|
("text", "Plain Text"),
|
|
("reference", "Record Reference"),
|
|
("external", "Manually Entered Value"),
|
|
("ledger", "Journal Item Details"),
|
|
("agecalc", "Aging Buckets"),
|
|
("custom", "Custom Python Method"),
|
|
], default="domain", required=True)
|
|
date_scope = fields.Selection(
|
|
DATE_SCOPES, default="strict_range", required=True,
|
|
help="Which dates to use, relative to the period of the column.",
|
|
)
|
|
sign = fields.Selection([
|
|
("1", "As computed (debit positive)"),
|
|
("-1", "Flipped (credit positive)"),
|
|
], default="1", required=True,
|
|
help="Journal item balances are debit-positive. Income, liability and "
|
|
"equity accounts carry credit balances, so flipping the sign makes "
|
|
"them read as positive amounts on a statement.",
|
|
)
|
|
measure = fields.Selection(
|
|
MEASURES, default="balance", required=True,
|
|
help="Which column of the journal items to add up. Statements use the "
|
|
"net balance; journal audits use the debit or credit totals "
|
|
"because a balanced entry always nets to zero.",
|
|
)
|
|
sequence = fields.Integer(default=10)
|
|
|
|
_label_uniq = models.Constraint(
|
|
"unique(report_line_id, label)",
|
|
"An expression label must be unique inside its line.",
|
|
)
|
|
|
|
@api.constrains("engine", "formula")
|
|
def _check_formula(self):
|
|
for expr in self:
|
|
if not (expr.formula or "").strip() and expr.engine != "text":
|
|
raise ValidationError(
|
|
_("Expression “%s” needs a formula.", expr.label or expr.id)
|
|
)
|
|
if expr.engine == "domain":
|
|
try:
|
|
parsed = ast.literal_eval((expr.formula or "").strip())
|
|
except (ValueError, SyntaxError) as exc:
|
|
raise ValidationError(
|
|
_("Invalid domain in expression “%s”: %s",
|
|
expr.label or expr.id, exc)
|
|
) from exc
|
|
if not isinstance(parsed, (list, tuple)):
|
|
raise ValidationError(
|
|
_("Domain expression “%s” must be a list.",
|
|
expr.label or expr.id)
|
|
)
|
|
|
|
|
|
class DnFrExternalValue(models.Model):
|
|
"""Manually entered figures: budgets, carry-over amounts, tax adjustments."""
|
|
|
|
_name = "dn.fr.external.value"
|
|
_description = "DN Financial Report External Value"
|
|
_order = "date desc, id desc"
|
|
|
|
expression_id = fields.Many2one(
|
|
"dn.fr.expression", required=True, ondelete="cascade", index=True,
|
|
)
|
|
report_id = fields.Many2one(
|
|
related="expression_id.report_line_id.report_id", store=True,
|
|
)
|
|
name = fields.Char(required=True)
|
|
date = fields.Date(required=True, default=fields.Date.context_today)
|
|
amount = fields.Float(digits=(16, 2), required=True)
|
|
company_id = fields.Many2one(
|
|
"res.company", required=True, default=lambda self: self.env.company,
|
|
)
|
|
currency_id = fields.Many2one(
|
|
related="company_id.currency_id", readonly=True,
|
|
)
|
|
|
|
|
|
# --------------------------------------------------------------- date helpers
|
|
def _safe_date(year, month, day):
|
|
"""Clamp an invalid day (e.g. 31 February) to the last valid day."""
|
|
import calendar
|
|
last = calendar.monthrange(year, month)[1]
|
|
return date(year, month, min(day, last))
|
|
|
|
|
|
def _one_day():
|
|
from datetime import timedelta
|
|
return timedelta(days=1)
|
|
|
|
|
|
def _shift_months(value, months):
|
|
"""Move a date by a number of months, clamping the day."""
|
|
if not value:
|
|
return value
|
|
if isinstance(value, str):
|
|
value = fields.Date.to_date(value)
|
|
month_index = value.month - 1 + months
|
|
year = value.year + month_index // 12
|
|
month = month_index % 12 + 1
|
|
return _safe_date(year, month, value.day)
|
|
|
|
|
|
def _shift_days(value, days):
|
|
from datetime import timedelta
|
|
if not value:
|
|
return value
|
|
if isinstance(value, str):
|
|
value = fields.Date.to_date(value)
|
|
return value + timedelta(days=days)
|
|
|
|
|
|
def _shift_years(value, years):
|
|
if not value:
|
|
return value
|
|
if isinstance(value, str):
|
|
value = fields.Date.to_date(value)
|
|
try:
|
|
return value.replace(year=value.year + years)
|
|
except ValueError: # 29 February
|
|
return value.replace(year=value.year + years, day=28)
|
|
|
|
|
|
def _period_length(date_from, date_to):
|
|
"""Inclusive number of days inside the period."""
|
|
if not date_from or not date_to:
|
|
return 0
|
|
if isinstance(date_from, str):
|
|
date_from = fields.Date.to_date(date_from)
|
|
if isinstance(date_to, str):
|
|
date_to = fields.Date.to_date(date_to)
|
|
return max((date_to - date_from).days + 1, 0)
|