This commit is contained in:
2026-11-08 17:43:44 +08:00
parent 974a1fb10b
commit 3b5af1e3a6
483 changed files with 590466 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import common
from . import account_sales_report_common
from . import test_account_reports_annotations_export
from . import test_account_reports_filters
from . import test_account_reports_journal_filter
from . import test_account_reports_tours
from . import test_account_returns
from . import test_account_returns_tours
from . import test_account_sales_report
from . import test_cumulative_translation_adjustments
from . import test_general_ledger_report
from . import test_general_ledger_snapshots
from . import test_trial_balance_report
from . import test_partner_ledger_report
from . import test_partner_ledger_snapshots
from . import test_reconciliation_report
from . import test_aged_receivable_report
from . import test_aged_payable_report
from . import test_tax_report
from . import test_tax_report_default_part
from . import test_cash_flow_report
from . import test_financial_report
from . import test_multicurrencies_revaluation_report
from . import test_tour_account_reports
from . import test_tax_report_carryover
from . import test_balance_sheet_report
from . import test_balance_sheet_balanced
from . import test_interco_comparison_report
from . import test_journal_report
from . import test_report_engines
from . import test_all_reports_generation
from . import test_analytic_reports
from . import test_deferred_reports
from . import test_report_sections
from . import test_budget
from . import test_currency_table
from . import test_followup_report
from . import test_kpi_provider
from . import test_snapshots

View File

@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
from odoo import fields
from odoo.addons.account_reports.tests.common import TestAccountReportsCommon
class AccountSalesReportCommon(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner_a.write({
'name': 'Partner A',
'country_id': cls.env.ref('base.fr').id,
"vat": "FR23334175221",
})
cls.partner_b = cls.env['res.partner'].create({
'name': 'Partner B',
'country_id': cls.env.ref('base.be').id,
"vat": "BE0477472701",
})
cls.company.partner_id.update({
'email': 'jsmith@mail.com',
'phone': '+32475123456',
})
def _create_invoices(self, data, is_refund=False):
move_vals_list = []
for move_data in data:
partner, tax, price_unit = move_data[:3]
partner_shipping_id = move_data[3] if len(move_data) > 3 else None
move_vals_list.append({
'move_type': 'out_refund' if is_refund else 'out_invoice',
'partner_id': partner.id,
'partner_shipping_id': partner_shipping_id.id if partner_shipping_id else None,
'invoice_date': fields.Date.from_string('2019-12-01'),
'invoice_line_ids': [
(0, 0, {
'name': 'line_1',
'price_unit': price_unit,
'quantity': 1.0,
'account_id': self.company_data['default_account_revenue'].id,
'tax_ids': [(6, 0, tax.ids)],
}),
],
})
moves = self.env['account.move'].create(move_vals_list)
moves.action_post()

View File

@@ -0,0 +1,639 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import copy
import io
import unittest
from collections import Counter
from datetime import datetime, date
try:
from openpyxl import load_workbook
except ImportError:
load_workbook = None
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo import Command, fields, _
from odoo.exceptions import UserError
from odoo.tools import frozendict, DEFAULT_SERVER_DATE_FORMAT
from odoo.tools.misc import formatLang, file_open
class TestAccountReportsCommon(AccountTestInvoicingCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.other_currency = cls.setup_other_currency('CAD')
cls.company_data_2 = cls.setup_other_company()
cls.company_data_2['company'].currency_id = cls.other_currency
cls.company_data_2['currency'] = cls.other_currency
cls.garbage_account = cls.env['account.account'].create({
'code': "turlututu",
'name': "turlututu",
'account_type': "asset_current",
})
cls.fake_country = cls.env['res.country'].create({
'name': "L'Île de la Mouche",
'code': 'YY',
})
cls.snapshot_creation_cron = cls.env.ref('account_reports.ir_cron_create_snapshots')
cls.snapshot_garbage_collection_cron = cls.env.ref('account_reports.ir_cron_garbage_collect_snapshots')
@classmethod
def _generate_options(cls, report, date_from, date_to, default_options=None):
''' Create new options at a certain date.
:param report: The report.
:param date_from: A datetime object, str representation of a date or False.
:param date_to: A datetime object or str representation of a date.
:return: The newly created options.
'''
if isinstance(date_from, datetime):
date_from_str = fields.Date.to_string(date_from)
else:
date_from_str = date_from
if isinstance(date_to, datetime):
date_to_str = fields.Date.to_string(date_to)
else:
date_to_str = date_to
if not default_options:
default_options = {}
return report.get_options({
'selected_variant_id': report.id,
'date': {
'date_from': date_from_str,
'date_to': date_to_str,
},
'show_account': True,
'show_currency': True,
'consolidation': False,
**default_options,
})
@classmethod
def _cleanup_snapshot_cron_triggers(cls):
cls.env['ir.cron.trigger'].search([('cron_id', 'in', (cls.snapshot_garbage_collection_cron + cls.snapshot_creation_cron).ids)]).unlink()
def _run_snapshot_crons(self):
self.env['account.report.snapshot'].sudo()._cron_garbage_collect_snapshots()
while creation_trigger := self.env['ir.cron.trigger'].search([('cron_id', '=', self.snapshot_creation_cron.id)], limit=1):
creation_trigger.unlink()
self.env['account.report.snapshot'].sudo()._cron_create_snapshots()
def _press_journal_filter(self, options, journals):
for option_journal in options['journals']:
if option_journal.get('id') in journals.ids:
option_journal['selected'] = not option_journal['selected']
def _update_comparison_filter(self, options, report, comparison_type, number_period, date_from=None, date_to=None, period_order=None):
''' Modify the existing options to set a new filter_comparison.
:param options: The report options.
:param report: The report.
:param comparison_type: One of the following values: ('no_comparison', 'custom', 'previous_period', 'previous_year').
:param number_period: The number of period to compare.
:param date_from: A datetime object for the 'custom' comparison_type.
:param date_to: A datetime object the 'custom' comparison_type.
:return: The newly created options.
'''
previous_options = {**options, 'comparison': {
**options['comparison'],
'date_from': date_from and date_from.strftime(DEFAULT_SERVER_DATE_FORMAT),
'date_to': date_to and date_to.strftime(DEFAULT_SERVER_DATE_FORMAT),
'filter': comparison_type,
'number_period': number_period,
'period_order': period_order or options['comparison']['period_order'],
}}
return report.get_options(previous_options)
def _update_multi_selector_filter(self, options, option_key, selected_ids):
''' Modify a selector in the options to select .
:param options: The report options.
:param option_key: The key to the option.
:param selected_ids: The ids to be selected.
:return: The newly created options.
'''
new_options = copy.deepcopy(options)
for c in new_options[option_key]:
c['selected'] = c['id'] in selected_ids
return new_options
def assertColumnPercentComparisonValues(self, lines, expected_values):
filtered_lines = self._filter_folded_lines(lines)
# Check number of lines.
self.assertEqual(len(filtered_lines), len(expected_values))
for value, expected_value in zip(filtered_lines, expected_values):
# Check number of columns.
self.assertEqual(3, len(expected_value))
# Check name, value and class.
self.assertEqual((value.name, value.column_percent_comparison_data.name, value.column_percent_comparison_data.comparison_mode), expected_value)
def assertColumnAmountComparisonValues(self, lines, expected_values):
""" Like assertColumnPercentComparisonValues but asserts the underlying numeric delta
(column_percent_comparison_data.no_format) instead of the rendered string, so tests don't
depend on locale/currency formatting. """
filtered_lines = self._filter_folded_lines(lines)
self.assertEqual(len(filtered_lines), len(expected_values))
for value, expected_value in zip(filtered_lines, expected_values):
self.assertEqual(3, len(expected_value))
self.assertEqual((value.name, value.column_percent_comparison_data.no_format, value.column_percent_comparison_data.comparison_mode), expected_value)
def assertHorizontalGroupTotal(self, lines, expected_values):
filtered_lines = self._filter_folded_lines(lines)
# Check number of lines.
self.assertEqual(len(filtered_lines), len(expected_values))
for line_dict_list, (_title, *expected_columns) in zip(filtered_lines, expected_values):
column_values = [column.no_format for column in line_dict_list.columns]
# Compare the Total column, Total column is there only under certain condition
if line_dict_list.horizontal_group_total_data:
*expected_columns, total = expected_columns
self.assertEqual(line_dict_list.horizontal_group_total_data.no_format, total)
self.assertEqual(column_values, expected_columns)
def assertHeadersValues(self, headers, expected_headers):
''' Helper to compare the headers returned by the _get_table method
with some expected results.
An header is a row of columns. Then, headers is a list of list of dictionary.
:param headers: The headers to compare.
:param expected_headers: The expected headers.
:return:
'''
# Check number of header lines.
self.assertEqual(len(headers), len(expected_headers))
for header, expected_header in zip(headers, expected_headers):
# Check number of columns.
self.assertEqual(len(header), len(expected_header))
for i, column in enumerate(header):
# Check name.
self.assertEqual(column['name'], self._convert_str_to_date(column['name'], expected_header[i]))
def assertIdenticalLines(self, reports):
"""Helper to compare report lines with the same `code` across multiple reports.
The helper checks the lines for similarity on:
- number of expressions
- expression label
- expression engine
- expression formula
- expression subformula
- expression date_scope
:param reports: (recordset of account.report) The reports to check
"""
def expression_to_comparable_values(expr):
return (
expr.label,
expr.engine,
expr.formula,
expr.subformula,
expr.date_scope
)
if not reports:
raise UserError(self.env._('There are no reports to compare.'))
visited_line_codes = set()
for line in reports.line_ids:
if not line.code or line.code in visited_line_codes:
continue
identical_lines = reports.line_ids.filtered(lambda l: l != line and l.code == line.code)
if not identical_lines:
continue
with self.subTest(line_code=line.code):
for tested_line in identical_lines:
self.assertCountEqual(
line.expression_ids.mapped(expression_to_comparable_values),
tested_line.expression_ids.mapped(expression_to_comparable_values),
(
f'The line with code {line.code} from reports "{line.report_id.name}" and '
f'"{tested_line.report_id.name}" has different expression values in both reports.'
)
)
visited_line_codes.add(line.code)
def assertLinesValues(self, lines, columns, expected_values, options, currency_map=None, ignore_folded=True):
''' Helper to compare the lines returned by the _get_lines method
with some expected results and ensuring the 'id' key of each line holds a unique value.
:param lines: See _get_lines.
:param columns: The columns index.
:param expected_values: A list of iterables.
:param options: The options from the current report.
:param currency_map: A map mapping each column_index to some extra options to test the lines:
- currency: The currency to be applied on the column.
- currency_code_index: The index of the column containing the currency code.
:param ignore_folded: Will not filter folded lines when True.
'''
if currency_map is None:
currency_map = {}
filtered_lines = self._filter_folded_lines(lines) if ignore_folded else lines
# Compare the table length to see if any line is missing
self.assertEqual(len(filtered_lines), len(expected_values))
# Compare cell by cell the current value with the expected one.
to_compare_list = []
for i, line in enumerate(filtered_lines):
compared_values = [[], []]
for j, index in enumerate(columns):
if index == 0:
current_value = line.name
else:
# Some lines may not have columns, like title lines. In such case, no values should be provided for these.
# Note that the function expect a tuple, so the line still need a comma after the name value.
if j > len(expected_values[i]) - 1:
break
current_value = line.columns[index - 1].name or ''
current_figure_type = line.columns[index - 1].figure_type or ''
expected_value = expected_values[i][j]
currency_data = currency_map.get(index, {})
used_currency = None
if 'currency' in currency_data:
used_currency = currency_data['currency']
elif 'currency_code_index' in currency_data:
currency_code = line.columns[currency_data['currency_code_index'] - 1].name
if currency_code:
used_currency = self.env['res.currency'].search([('name', '=', currency_code)], limit=1)
assert used_currency, "Currency having name=%s not found." % currency_code
if not used_currency:
used_currency = self.env.company.currency_id
if type(expected_value) in (int, float) and type(current_value) == str:
if current_figure_type and current_figure_type != 'monetary':
expected_value = str(expected_value)
elif options.get('multi_currency'):
expected_value = formatLang(self.env, expected_value, currency_obj=used_currency)
else:
expected_value = formatLang(self.env, expected_value, digits=used_currency.decimal_places)
compared_values[0].append(current_value)
compared_values[1].append(expected_value)
to_compare_list.append(compared_values)
errors = []
for i, to_compare in enumerate(to_compare_list):
if to_compare[0] != to_compare[1]:
errors += [
"\n==== Differences at index %s ====" % str(i),
"Current Values: %s" % str(to_compare[0]),
"Expected Values: %s" % str(to_compare[1]),
]
id_counts = Counter(line.id for line in lines)
duplicate_ids = {k: v for k, v in id_counts.items() if v > 1}
if duplicate_ids:
index_to_id = [
f"index={index:<6} name={line.name} \tline_id={line.id}"
for index, line in enumerate(lines)
if line.id in duplicate_ids
]
errors += [
"\n==== There are lines sharing the same id ====",
"\n".join(index_to_id)
]
if errors:
self.fail('\n'.join(errors))
def _filter_folded_lines(self, lines):
""" Children lines returned for folded lines (for example, totals below sections) should be ignored when comparing the results
in assertLinesValues (their parents are folded, so they are not shown anyway). This function returns a filtered version of lines
list, without the chilren of folded lines.
"""
filtered_lines = []
folded_lines = set()
for line in lines:
if line.parent_id in folded_lines:
folded_lines.add(line.id)
else:
if line.unfoldable and not line.unfolded:
folded_lines.add(line.id)
filtered_lines.append(line)
return filtered_lines
def _convert_str_to_date(self, ref, val):
if isinstance(ref, date) and isinstance(val, str):
return datetime.strptime(val, '%Y-%m-%d').date()
return val
@classmethod
def _create_tax_report_line(cls, name, report, tag_name=None, parent_line=None, sequence=None, code=None, formula=None):
""" Creates a tax report line
"""
create_vals = {
'name': name,
'code': code,
'report_id': report.id,
'sequence': sequence,
'expression_ids': [],
}
if tag_name and formula:
raise UserError(_("Can't use this helper to create a line with both tags and formula"))
if tag_name:
create_vals['expression_ids'].append(Command.create({
"label": "balance",
"engine": "tax_tags",
"formula": tag_name,
}))
if parent_line:
create_vals['parent_id'] = parent_line.id
if formula:
create_vals['expression_ids'].append(Command.create({
"label": "balance",
"engine": "aggregation",
"formula": formula,
}))
return cls.env['account.report.line'].create(create_vals)
@classmethod
def _get_tag_ids(cls, expressions, company=False):
""" Helper function to define tag ids for taxes """
return [(6, 0, cls.env['account.account.tag'].search([
('applicability', '=', 'taxes'),
('country_id.code', '=', (company or cls.env.company).account_fiscal_country_id.code),
('name', 'in', [formula.lstrip('-') for formula in expressions.mapped('formula')]),
]).ids)]
@classmethod
def _get_basic_line_dict_id_from_report_line(cls, report_line):
""" Computes a full generic id for the provided report line (hence including the one of its parent as prefix), using no markup.
"""
report = report_line.report_id
if report_line.parent_id:
parent_line_id = cls._get_basic_line_dict_id_from_report_line(report_line.parent_id)
return report._get_generic_line_id(report_line._name, report_line.id, parent_line_id=parent_line_id)
return report._get_generic_line_id(report_line._name, report_line.id)
@classmethod
def _get_basic_line_dict_id_from_report_line_ref(cls, report_line_xmlid):
""" Same as _get_basic_line_dict_id_from_report_line, but from the line's xmlid, for convenience in the tests.
"""
return cls._get_basic_line_dict_id_from_report_line(cls.env.ref(report_line_xmlid))
@classmethod
def _get_audit_params_from_report_line(cls, options, report_line, report_line_data, **kwargs):
return {
'report_line_id': report_line.id,
'calling_line_dict_id': report_line_data.id,
'expression_label': 'balance',
'column_group_index': 0,
**kwargs,
}
def _report_compare_with_test_file(self, report, xml_file=None, test_xml=None):
report_xml = self.get_xml_tree_from_string(report['file_content'])
if xml_file and not test_xml:
with file_open(f"{self.test_module}/tests/expected_xmls/{xml_file}", 'rb') as fp:
test_xml = fp.read()
test_xml_tree = self.get_xml_tree_from_string(test_xml)
self.assertXmlTreeEqual(report_xml, test_xml_tree)
@classmethod
def _fill_tax_report_line_external_value(cls, target, amount, date):
cls.env['account.report.external.value'].create({
'company_id': cls.company_data['company'].id,
'target_report_expression_id': cls.env.ref(target).id,
'name': 'Manual value',
'date': fields.Date.from_string(date),
'value': amount,
})
# -------------------------------------------------------------------------
# REPORT CREATION AND POPULATION HELPERS
# -------------------------------------------------------------------------
def _prepare_test_external_values(self, value, date, figure_type=False):
field_name = 'text_value' if figure_type == 'string' else 'value'
return {
'name': date,
field_name: value,
'date': date,
}
def _prepare_test_expression(self, formula, label='balance', **kwargs):
return {
'expression_values': {
'label': label,
'formula': formula,
**kwargs,
},
}
def _prepare_test_expression_tax_tags(self, formula, **kwargs):
return self._prepare_test_expression(engine='tax_tags', formula=formula, **kwargs)
def _prepare_test_expression_domain(self, formula, subformula, **kwargs):
return self._prepare_test_expression(engine='domain', formula=formula, subformula=subformula, **kwargs)
def _prepare_test_expression_account_codes(self, formula, **kwargs):
return self._prepare_test_expression(engine='account_codes', formula=formula, **kwargs)
def _prepare_test_expression_external(self, formula, external_value_generators, **kwargs):
return {
**self._prepare_test_expression(engine='external', formula=formula, **kwargs),
'external_value_generators': external_value_generators,
}
def _prepare_test_expression_reference(self, formula, external_value_generators, **kwargs):
return {
**self._prepare_test_expression(engine='reference', formula=formula, **kwargs),
'external_value_generators': external_value_generators,
}
def _prepare_test_expression_custom(self, formula, **kwargs):
return self._prepare_test_expression(engine='custom', formula=formula, **kwargs)
def _prepare_test_expression_aggregation(self, formula, subformula=None, column='balance', date_scope=None):
expression_values = {
'label': column,
'engine': 'aggregation',
'formula': formula,
'subformula': subformula,
}
if date_scope:
expression_values['date_scope'] = date_scope
return {
'expression_values': expression_values,
}
def _prepare_test_report_line(self, *expression_generators, **kwargs):
return {
'report_line_values': {
**kwargs,
'expression_ids': [
Command.create({
'date_scope': 'strict_range',
**expression_values['expression_values'],
})
for expression_values in expression_generators
],
},
'expression_generators': expression_generators,
}
def _create_report(self, test_report_line_values_list, columns=None, **kwargs):
if not columns:
columns = ['balance']
# Create a new report
report = self.env['account.report'].create({
'name': "_run_report",
'filter_date_range': True,
'filter_unfold_all': True,
**kwargs,
'column_ids': [
Command.create({
'name': column,
'expression_label': column,
'sequence': i,
})
for i, column in enumerate(columns)
],
'line_ids': [
Command.create({
'name': f"test_line_{i}",
**test_report_line_values['report_line_values'],
'sequence': i,
})
for i, test_report_line_values in enumerate(test_report_line_values_list, start=1)
],
})
# Create the external values
external_values_create_list = []
for report_line, test_report_line_values in zip(report.line_ids, test_report_line_values_list):
for expression, expression_values in zip(report_line.expression_ids, test_report_line_values['expression_generators']):
for external_values in expression_values.get('external_value_generators', []):
external_values_create_list.append({
**external_values,
'target_report_expression_id': expression.id,
})
self.env['account.report.external.value'].create(external_values_create_list)
return report
def _prepare_test_account_move_line(self, balance, account_code=None, tax_tags=None, date='2020-01-01', **kwargs):
if tax_tags:
tags = self.env['account.account.tag'].search([
('applicability', '=', 'taxes'),
('country_id', '=', self.fake_country.id),
('name', 'in', tax_tags),
])
else:
tags = self.env['account.account.tag']
return {
'account_move_line_values': {
'name': "turlututu",
'account_id': self.garbage_account.id,
**kwargs,
'debit': balance if balance > 0.0 else 0.0,
'credit': -balance if balance < 0.0 else 0.0,
'tax_tag_ids': [Command.set(tags.ids)],
},
'account_move_values': {'date': date, 'company_id': kwargs.get('company_id', self.env.company.id)},
'account_code': account_code,
}
def _create_test_account_moves(self, test_account_move_line_values_list):
# Create the missing account on-the-fly.
accounts_to_create_by_code = set()
all_company_ids = set()
for test_account_move_line_values in test_account_move_line_values_list:
if test_account_move_line_values.get('account_code'):
accounts_to_create_by_code.add(test_account_move_line_values['account_code'])
all_company_ids.add(test_account_move_line_values['account_move_values']['company_id'])
if accounts_to_create_by_code:
accounts = self.env['account.account']
accounts += self.env['account.account'].create([
{
'code_mapping_ids': [
Command.create({'company_id': company_id, 'code': account_code})
for company_id in all_company_ids
],
'name': account_code,
'company_ids': [Command.link(comp_id) for comp_id in all_company_ids],
'account_type': "asset_current",
}
for account_code in accounts_to_create_by_code
])
account_by_code = {x.code: x for x in accounts}
for test_account_move_line_values in test_account_move_line_values_list:
account = account_by_code.get(test_account_move_line_values.get('account_code'))
if account:
test_account_move_line_values['account_move_line_values']['account_id'] = account.id
# Create the journal entries.
to_create = {}
for test_account_move_line_values in test_account_move_line_values_list:
account_move_key = frozendict(test_account_move_line_values['account_move_values'])
account_move_line_values = test_account_move_line_values['account_move_line_values']
account_move_to_create = to_create.setdefault(account_move_key, {
'account_move_values': {'line_ids': []},
'balance': 0.0,
})
account_move_to_create['account_move_values']['line_ids'].append(Command.create(account_move_line_values))
account_move_to_create['balance'] += account_move_line_values['debit'] - account_move_line_values['credit']
account_move_create_list = []
for account_move_dict, account_move_to_create in to_create.items():
open_balance = account_move_to_create['balance']
account_move_values = account_move_to_create['account_move_values']
if not self.env.company.currency_id.is_zero(open_balance):
account_move_values['line_ids'].append(Command.create({
'name': 'open balance',
'account_id': self.garbage_account.id,
'debit': -open_balance if open_balance < 0.0 else 0.0,
'credit': open_balance if open_balance > 0.0 else 0.0,
}))
account_move_create_list.append({
**account_move_dict,
**account_move_values,
})
moves = self.env['account.move'].create(account_move_create_list)
moves.action_post()
return moves
# -------------------------------------------------------------------------
def _test_xlsx_file(self, file_content, expected_values):
""" Takes in the binary content of a xlsx file and a dict of expected values.
It will then parse the file in order to compare the values with the expected ones.
The expected values dict format is:
'row_number': ['cell_1_val', 'cell_2_val', ...]
:param file_content: The binary content of the xlsx file
:param expected_values: The dict of expected values
"""
if load_workbook is None:
raise unittest.SkipTest("openpyxl not available")
report_file = io.BytesIO(file_content)
xlsx = load_workbook(filename=report_file, data_only=True)
sheet = xlsx.worksheets[0]
sheet_values = list(sheet.values)
for row, values in expected_values.items():
row_values = [v if v is not None else '' for v in sheet_values[row]]
for row_value, expected_value in zip(row_values, values):
self.assertEqual(row_value, expected_value)

View File

@@ -0,0 +1,273 @@
import datetime
import io
import unittest
import markupsafe
from odoo.tests import freeze_time, tagged
from odoo.tools import html2plaintext
from odoo.addons.account_reports.tests.common import TestAccountReportsCommon
try:
from openpyxl import load_workbook
except ImportError:
load_workbook = None
@tagged('post_install', '-at_install')
class TestAccountReportAnnotationsExport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
if load_workbook is None:
raise unittest.SkipTest("openpyxl not available")
super().setUpClass()
cls.report = cls.env.ref('account_reports.balance_sheet')
cls.report.column_ids.sortable = True
# Get accounts
bank_default_account = cls.company_data["default_journal_bank"].default_account_id
tax_sale_default_account = cls.company_data["default_account_tax_sale"]
# Create move
move = cls.env['account.move'].create({
'move_type': 'entry',
'date': '2024-06-10',
'journal_id': cls.company_data['default_journal_cash'].id,
'line_ids': [
(0, 0, {'debit': 250.0, 'credit': 0.0, 'account_id': bank_default_account.id}),
(0, 0, {'debit': 0.0, 'credit': 250.0, 'account_id': tax_sale_default_account.id}),
],
})
move.action_post()
# Create annotation
with freeze_time('2024-06-20'):
cls.env.cr._now = datetime.datetime.now() # used to force create_date, as sql is not wrapped by freeze gun
date = datetime.datetime.strptime('2024-06-20', '%Y-%m-%d').date()
message = cls.env['mail.message'].create({
'model': bank_default_account._name,
'res_id': bank_default_account.id,
'body': 'Papa a vu le fifi de lolo',
'date': date,
'author_id': cls.env.user.partner_id.id,
'message_type': 'comment',
'subtype_id': cls.env.ref('mail.mt_note').id,
})
cls.env['account.report.annotation'].create({
'date': date,
'message_id': message.id,
})
def read_xlsx_data(self, report_data):
report_file = io.BytesIO(report_data)
xlsx = load_workbook(filename=report_file, data_only=True)
sheet = xlsx.worksheets[0]
return list(sheet.values)
def test_annotations_export_no_comparison(self):
options = self._generate_options(self.report, '2024-06-01', '2024-06-30', default_options={'unfold_all': True})
report_data = self.report.export_to_xlsx(options)
export_content = self.read_xlsx_data(report_data['file_content'])
# When there is no comparison, there are two columns for the accounts (number, name), one column for the data and
# finally one column for the annotations. Hence the index 3 for the annotation column.
self.assertEqual(export_content[0][3], "Annotations")
self.assertEqual(export_content[7][3], "1 - Papa a vu le fifi de lolo")
def test_annotations_export_pdf(self):
options = self._generate_options(self.report, '2024-06-01', '2024-06-30', default_options={'unfold_all': True, 'export_mode': 'print'})
report_info = self.report.get_report_information(options)
render_annotations = self.report._build_annotations_list_for_pdf_export(report_info['lines'], report_info['annotations'])
self.assertEqual(render_annotations, [{'body': markupsafe.Markup('Papa a vu le fifi de lolo'), 'date': '06/20/2024', 'number': '1'}])
def test_annotations_export_same_period_last_year_comparison(self):
default_comparison = {
'filter': 'same_last_year',
'number_period': 1,
'date_from': '2023-06-01',
'date_to': '2023-06-30',
'periods': [{
'string': 'As of 06/30/2023',
'period_type': 'month', 'mode':
'single', 'date_from': '2023-06-01',
'date_to': '2023-06-30'
}],
'period_order':
'descending',
'string': 'As of 06/30/2023',
'period_type': 'month',
'mode': 'single'
}
options = self._generate_options(self.report, '2024-06-01', '2024-06-30', default_options={'unfold_all': True, 'comparison': default_comparison})
report_data = self.report.export_to_xlsx(options)
export_content = self.read_xlsx_data(report_data['file_content'])
# When comparing with the same period last year, there are two columns for the accounts (number, name), two columns for the
# date (one per period), one column for the growth comparison percentage and finally one column for the annotations.
# Hence the index 5 for the annotation column.
self.assertEqual(export_content[0][5], "Annotations")
self.assertEqual(export_content[7][5], "1 - Papa a vu le fifi de lolo")
def test_annotations_export_two_last_periods_comparison(self):
default_comparison = {
'filter': 'previous_period',
'number_period': 2,
'date_from': '2024-05-01',
'date_to': '2024-05-31',
'periods': [
{
'string': 'As of 05/31/2024',
'period_type': 'month',
'mode': 'single',
'date_from': '2024-05-01',
'date_to': '2024-05-31'
},
{
'string': 'As of 04/30/2024',
'period_type': 'month',
'mode': 'single',
'date_from': '2024-04-01',
'date_to': '2024-04-30'
}
],
'period_order': 'descending',
'string': 'As of 05/31/2024',
'period_type': 'month',
'mode': 'single'
}
options = self._generate_options(self.report, '2024-06-01', '2024-06-30', default_options={'unfold_all': True, 'comparison': default_comparison})
report_data = self.report.export_to_xlsx(options)
export_content = self.read_xlsx_data(report_data['file_content'])
# When comparing with the two last periods, there are two columns for the accounts (number, name), three columns for the
# data (one per period) and finally one column for the annotations. Hence the index 5 for the annotation column.
self.assertEqual(export_content[0][5], "Annotations")
self.assertEqual(export_content[7][5], "1 - Papa a vu le fifi de lolo")
def test_annotations_ordering(self):
bank_default_account = self.company_data["default_journal_bank"].default_account_id
model = bank_default_account._name
res_id = bank_default_account.id
with freeze_time('2024-06-21'):
self.env.cr._now = datetime.datetime.now() # used to force create_date, as sql is not wrapped by freeze gun
date = datetime.datetime.strptime('2024-06-21', '%Y-%m-%d').date()
message = self.env['mail.message'].create({
'model': model,
'res_id': res_id,
'body': 'lolo a vu le fifi de papa',
'date': date,
'author_id': self.env.user.partner_id.id,
'message_type': 'comment',
'subtype_id': self.env.ref('mail.mt_note').id,
})
self.env['account.report.annotation'].create({
'date': date,
'message_id': message.id,
})
options = self._generate_options(self.report, '2024-06-01', '2024-06-30', default_options={'unfold_all': True, 'export_mode': True})
report_data = self.report.get_report_information(options)
annotations = report_data['annotations']
report_line_ids = [f'~account.report.line~{self.report.line_ids[i].id}' for i in range(0, 3)]
expected = {
f'~account.report~{self.report.id}|{"|".join(report_line_ids)}|{{"groupby": "account_id"}}~{model}~{res_id}': [
{
'model': model,
'res_id': res_id,
'date': datetime.date(2024, 6, 20),
'body': 'Papa a vu le fifi de lolo',
},
{
'id': message.id,
'model': model,
'res_id': res_id,
'date': datetime.date(2024, 6, 21),
'body': 'lolo a vu le fifi de papa',
}
]
}
self.assertTrue(len(annotations.keys()) == len(expected.keys()), "More/Less lines are annotated than expected.")
self.assertTrue(all(key in annotations for key in expected), "The same lines are not annotated as expected.")
for line_id, line_annotations in expected.items():
self.assertEqual(len(annotations[line_id]), len(line_annotations), f"Line {line_id} has more/less annotations than expected.")
for i in range(len(line_annotations)):
for field in line_annotations[i]:
field_data = annotations[line_id][i][field]
if field == 'body':
field_data = html2plaintext(markupsafe.escape(field_data))
self.assertEqual(field_data, line_annotations[i][field], f"Line {line_id} annotation {i} has a different {field} than expected.")
def test_annotations_outside_custom_fiscal_years_are_ignored(self):
vals_list = [
{
'name': row[2],
'date_from': row[0],
'date_to': row[1],
'company_id': self.env.company.id,
}
for row in [('2025-01-01', '2025-04-30', 'FY 2025_1'), ('2025-05-01', '2025-12-31', 'FY 2025_2')]
]
self.env['account.fiscal.year'].create(vals_list)
options = self._generate_options(
self.report,
"2024-06-01",
"2024-06-30",
default_options={
"date": {"period_type": "year"},
"comparison": {"filter": "previous_period", "number_period": 2},
},
)
report_info = self.report.get_report_information(options)
self.assertEqual(report_info['annotations'], {})
def test_annotations_export_deferred_revenue_report(self):
"""
Regression test: exporting the Deferred Revenue Report to XLSX must not crash with
UnboundLocalError when annotations exist on a deferred revenue record.
"""
deferred_revenue_report = self.env.ref('account_reports.deferred_revenue_report')
revenue_account = self.company_data['default_account_revenue']
self._create_invoice(
move_type='out_invoice',
invoice_date='2024-01-01',
post=True,
invoice_line_ids=[
self._prepare_invoice_line(
price_unit=1200.0,
account_id=revenue_account,
deferred_start_date='2024-01-01',
deferred_end_date='2024-04-30',
)
],
)
# Generate the report lines to get a valid line_id to annotate
options = self._generate_options(deferred_revenue_report, '2024-01-01', '2024-01-31')
# Add an annotation on the first report line — this triggers the bug on XLSX export
date = datetime.datetime.strptime('2024-01-15', '%Y-%m-%d').date()
message = self.env['mail.message'].create({
'model': revenue_account._name,
'res_id': revenue_account.id,
'body': 'Annotation on deferred revenue record',
'date': date,
'author_id': self.env.user.partner_id.id,
'message_type': 'comment',
'subtype_id': self.env.ref('mail.mt_note').id,
})
self.env['account.report.annotation'].create({
'date': date,
'message_id': message.id,
})
# This must not raise UnboundLocalError
report_data = deferred_revenue_report.export_to_xlsx(options)
self.assertIn('file_content', report_data)
self.assertEqual(report_data['file_type'], 'xlsx')

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,775 @@
# -*- coding: utf-8 -*-
from odoo import Command
from odoo.tests import tagged
from odoo.addons.account_reports.tests.common import TestAccountReportsCommon
@tagged('post_install', '-at_install')
class TestAccountReportsJournalFilter(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.vanilla_company1 = cls.env['res.company'].create({'name': "Vanilla1"})
cls.vanilla_company2 = cls.env['res.company'].create({'name': "Vanilla2"})
# Force the test user to only access the vanilla companies
cls.env.user.write({
'company_ids': [Command.set((cls.vanilla_company1 + cls.vanilla_company2).ids)],
'company_id': cls.vanilla_company1.id,
})
cls.report = cls.env.ref('account_reports.balance_sheet')
cls.report.filter_journals = True
groups = cls.env['account.journal.group'].search([])
groups.unlink()
def _assert_filter_journal(self, options, display_name, expected_values_list):
self.env['account.journal.group'].browse(['local_gaap']).invalidate_recordset(['included_journal_ids'])
journal_options = options['journal_groups'] + options['journals']
self.assertEqual(options['name_journal_group'], display_name)
self.assertEqual(len(journal_options), len(expected_values_list))
for journal_option, expected_values in zip(journal_options, expected_values_list):
record, selected = expected_values
self.assertDictEqual(
{
'id': journal_option.get('id'),
'selected': journal_option.get('selected'),
},
{
'id': record.id,
'selected': selected,
},
)
def _assert_filter_journal_visible_unfolded(self, options, expected_values):
self.assertEqual(len(options['journals']), len(expected_values))
for journal, results in zip(options['journals'], expected_values):
self.assertTupleEqual((journal.get('visible', None), journal.get('unfolded', None)), results)
def _quick_create_journal(self, name, company, journal_type='sale'):
return self.env['account.journal'].create([{
'name': name,
'code': name,
'type': journal_type,
'company_id': company.id,
}])
def _quick_create_journal_group(self, name, included_journals):
return self.env['account.journal.group'].create([{
'name': name,
'included_journal_ids': [Command.set(included_journals.ids)],
}])
def _press_journal_filter(self, options, journals):
for option_journal in options['journals']:
if option_journal.get('id') in journals.ids:
option_journal['selected'] = not option_journal['selected']
def test_journal_filter_single_company(self):
j1 = self._quick_create_journal("j1", self.vanilla_company1)
j2 = self._quick_create_journal("j2", self.vanilla_company1)
j3 = self._quick_create_journal("j3", self.vanilla_company1)
j4 = self._quick_create_journal("j4", self.vanilla_company1)
j5 = self._quick_create_journal("j5", self.vanilla_company1)
j6 = self._quick_create_journal("j6", self.vanilla_company1)
j7 = self._quick_create_journal("j7", self.vanilla_company1)
j8 = self._quick_create_journal("j8", self.vanilla_company1)
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "All Journals", [
(j1, False),
(j2, False),
(j3, False),
(j4, False),
(j5, False),
(j6, False),
(j7, False),
(j8, False),
])
self._press_journal_filter(options, (j1 + j2 + j3))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "j1, j2, j3", [
(j1, True),
(j2, True),
(j3, True),
(j4, False),
(j5, False),
(j6, False),
(j7, False),
(j8, False),
])
self._press_journal_filter(options, (j4 + j5 + j6))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "j1, j2, j3, j4, j5 and one other", [
(j1, True),
(j2, True),
(j3, True),
(j4, True),
(j5, True),
(j6, True),
(j7, False),
(j8, False),
])
self._press_journal_filter(options, j7)
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "j1, j2, j3, j4, j5 and 2 others", [
(j1, True),
(j2, True),
(j3, True),
(j4, True),
(j5, True),
(j6, True),
(j7, True),
(j8, False),
])
self._press_journal_filter(options, j8)
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "All Journals", [
(j1, False),
(j2, False),
(j3, False),
(j4, False),
(j5, False),
(j6, False),
(j7, False),
(j8, False),
])
def test_journal_filter_multi_company(self):
j1 = self._quick_create_journal("j1", self.vanilla_company1)
j2 = self._quick_create_journal("j2", self.vanilla_company1)
j3 = self._quick_create_journal("j3", self.vanilla_company2)
j4 = self._quick_create_journal("j4", self.vanilla_company2)
j5 = self._quick_create_journal("j5", self.vanilla_company1)
j6 = self._quick_create_journal("j6", self.vanilla_company1)
j7 = self._quick_create_journal("j7", self.vanilla_company2)
j8 = self._quick_create_journal("j8", self.vanilla_company2)
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "All Journals", [
(j1, False),
(j2, False),
(j5, False),
(j6, False),
(j3, False),
(j4, False),
(j7, False),
(j8, False),
])
self._press_journal_filter(options, (j1 + j5))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "j1, j5", [
(j1, True),
(j2, False),
(j5, True),
(j6, False),
(j3, False),
(j4, False),
(j7, False),
(j8, False),
])
self._press_journal_filter(options, (j2 + j6))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, f"{self.vanilla_company1.display_name}", [
(j1, True),
(j2, True),
(j5, True),
(j6, True),
(j3, False),
(j4, False),
(j7, False),
(j8, False),
])
self._press_journal_filter(options, (j3 + j7))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, f"{self.vanilla_company1.display_name}, j3, j7", [
(j1, True),
(j2, True),
(j5, True),
(j6, True),
(j3, True),
(j4, False),
(j7, True),
(j8, False),
])
def test_journal_filter_with_groups_single_company(self):
j1 = self._quick_create_journal("j1", self.vanilla_company1)
j2 = self._quick_create_journal("j2", self.vanilla_company1)
j3 = self._quick_create_journal("j3", self.vanilla_company1)
j4 = self._quick_create_journal("j4", self.vanilla_company1)
j5 = self._quick_create_journal("j5", self.vanilla_company1)
j6 = self._quick_create_journal("j6", self.vanilla_company1)
g1 = self._quick_create_journal_group("g1", j2 + j4)
g2 = self._quick_create_journal_group("g2", j2 + j5)
gaap_group = self.env['account.journal.group'].browse(['local_gaap'])
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(g2, False),
(j1, True),
(j2, False),
(j3, True),
(j4, False),
(j5, False),
(j6, True),
])
# Check g2.
options['__journal_group_action'] = {'action': 'add', 'id': g2.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap, g2", [
(gaap_group, True),
(g1, False),
(g2, True),
(j1, True),
(j2, True),
(j3, True),
(j4, False),
(j5, True),
(j6, True),
])
# Uncheck g2.
options['__journal_group_action'] = {'action': 'remove', 'id': g2.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(g2, False),
(j1, True),
(j2, False),
(j3, True),
(j4, False),
(j5, False),
(j6, True),
])
# Check j2 and j5.
self._press_journal_filter(options, (j2 + j5))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap, g2", [
(gaap_group, True),
(g1, False),
(g2, True),
(j1, True),
(j2, True),
(j3, True),
(j4, False),
(j5, True),
(j6, True),
])
# Uncheck j2 and j5.
self._press_journal_filter(options, (j2 + j5))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(g2, False),
(j1, True),
(j2, False),
(j3, True),
(j4, False),
(j5, False),
(j6, True),
])
def test_journal_filter_with_groups_multi_company(self):
j1 = self._quick_create_journal("j1", self.vanilla_company1)
j2 = self._quick_create_journal("j2", self.vanilla_company1)
j3 = self._quick_create_journal("j3", self.vanilla_company1)
j4 = self._quick_create_journal("j4", self.vanilla_company1)
j5 = self._quick_create_journal("j5", self.vanilla_company2)
j6 = self._quick_create_journal("j6", self.vanilla_company2)
g1 = self._quick_create_journal_group("g1", j2 + j3)
g2 = self._quick_create_journal_group("g2", j6)
gaap_group = self.env['account.journal.group'].browse(['local_gaap'])
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(g2, False),
(j1, True),
(j2, False),
(j3, False),
(j4, True),
(j5, True),
(j6, False),
])
# Check g2.
options['__journal_group_action'] = {'action': 'add', 'id': g2.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap, g2", [
(gaap_group, True),
(g1, False),
(g2, True),
(j1, True),
(j2, False),
(j3, False),
(j4, True),
(j5, True),
(j6, True),
])
# Uncheck all journals of Local Gaap
self._press_journal_filter(options, (j1 + j4 + j5))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "g2", [
(gaap_group, False),
(g1, False),
(g2, True),
(j1, False),
(j2, False),
(j3, False),
(j4, False),
(j5, False),
(j6, True),
])
# Check g1.
options['__journal_group_action'] = {'action': 'add', 'id': g1.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "g1, g2", [
(gaap_group, False),
(g1, True),
(g2, True),
(j1, False),
(j2, True),
(j3, True),
(j4, False),
(j5, False),
(j6, True),
])
# Uncheck g2.
options['__journal_group_action'] = {'action': 'remove', 'id': g2.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "g1", [
(gaap_group, False),
(g1, True),
(g2, False),
(j1, False),
(j2, True),
(j3, True),
(j4, False),
(j5, False),
(j6, False),
])
def test_journal_filter_with_single_group_multi_company(self):
j1 = self._quick_create_journal("j1", self.vanilla_company1)
j2 = self._quick_create_journal("j2", self.vanilla_company1)
j3 = self._quick_create_journal("j3", self.vanilla_company2)
j4 = self._quick_create_journal("j4", self.vanilla_company2)
g1 = self._quick_create_journal_group("g1", j2)
gaap_group = self.env['account.journal.group'].browse(['local_gaap'])
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(j1, True),
(j2, False),
(j3, True),
(j4, True),
])
# Add g1.
options['__journal_group_action'] = {'action': 'add', 'id': g1.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "All Journals", [
(gaap_group, True),
(g1, True),
(j1, True),
(j2, True),
(j3, True),
(j4, True),
])
self._press_journal_filter(options, j3) # uncheck j3
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, f"{self.vanilla_company1.display_name}, g1, j4", [
(gaap_group, False),
(g1, True),
(j1, True),
(j2, True),
(j3, False),
(j4, True),
])
# Remove g1.
options['__journal_group_action'] = {'action': 'remove', 'id': g1.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, f"{self.vanilla_company1.display_name}, j4", [
(gaap_group, False),
(g1, False),
(j1, True),
(j2, False),
(j3, False),
(j4, True),
])
self._press_journal_filter(options, j2) # Check j2
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, f"{self.vanilla_company1.display_name}, g1, j4", [
(gaap_group, False),
(g1, True),
(j1, True),
(j2, True),
(j3, False),
(j4, True),
])
self._press_journal_filter(options, j2) # Uncheck j2
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, f"{self.vanilla_company1.display_name}, j4", [
(gaap_group, False),
(g1, False),
(j1, True),
(j2, False),
(j3, False),
(j4, True),
])
def test_journal_filter_with_groups_cash_flow_statement(self):
"""
Test the behaviour of the journal filter with groups in a report
that does not allow all journals, cash flow statement is a perfect
fit for this use case
"""
bnk = self._quick_create_journal("BNK", self.vanilla_company1, 'bank')
csh = self._quick_create_journal("CSH", self.vanilla_company1, 'cash')
misc = self._quick_create_journal("MISC", self.vanilla_company1, 'general')
exch = self._quick_create_journal("EXCH", self.vanilla_company1, 'general')
ifrs = self._quick_create_journal("IFRS", self.vanilla_company1, 'general')
caba = self._quick_create_journal("CABA", self.vanilla_company1, 'general')
inv = self._quick_create_journal("INV", self.vanilla_company1, 'sale') # Not accepted by the report
bill = self._quick_create_journal("BILL", self.vanilla_company1, 'purchase') # Not accepted by the report
g1 = self._quick_create_journal_group("g1", inv + bill)
g2 = self._quick_create_journal_group("g2", misc + bill)
gaap_group = self.env['account.journal.group'].browse(['local_gaap'])
report = self.env.ref('account_reports.cash_flow_report')
report.filter_journals = True
options = report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(g2, False), # g2 should be displayed because it has journals that are allowed in the report
(bnk, True),
(caba, True),
(csh, True),
(exch, True),
(ifrs, True),
(misc, False),
])
# Check g2, all journals from g2 that are allowed in report should be selected
options['__journal_group_action'] = {'action': 'add', 'id': g2.id}
options = report.get_options(previous_options=options)
self._assert_filter_journal(options, "All Journals", [
(gaap_group, True),
(g1, False),
(g2, True), # g2 should be displayed because it has journals that are allowed in the report
(bnk, True),
(caba, True),
(csh, True),
(exch, True),
(ifrs, True),
(misc, True),
])
# Uncheck g2.
options['__journal_group_action'] = {'action': 'remove', 'id': g2.id}
options = report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(g2, False), # g2 should be displayed because it has journals that are allowed in the report
(bnk, True),
(caba, True),
(csh, True),
(exch, True),
(ifrs, True),
(misc, False),
])
def test_journal_filter_branch_company(self):
"""
The purpose of this test is to ensure that the journal filter is
well managed with sub companies.
Each journal should appear once, even when it is shared within
a company and its children.
Also, journal from parent company should be display in the filter
if only the child company is selected
"""
self.vanilla_company1.write({'child_ids': [Command.create({'name': 'Vanilla3'})]})
vanilla_company3 = self.vanilla_company1.child_ids[0]
self.env.user.write({
'company_ids': [Command.set((self.vanilla_company1 + self.vanilla_company2 + vanilla_company3).ids)],
'company_id': self.vanilla_company1.id,
})
j1 = self._quick_create_journal("j1", self.vanilla_company1)
j2 = self._quick_create_journal("j2", self.vanilla_company1)
j3 = self._quick_create_journal("j3", self.vanilla_company2)
j4 = self._quick_create_journal("j4", self.vanilla_company2)
j5 = self._quick_create_journal("j5", self.vanilla_company1)
j6 = self._quick_create_journal("j6", self.vanilla_company1)
j7 = self._quick_create_journal("j7", self.vanilla_company2)
j8 = self._quick_create_journal("j8", self.vanilla_company2)
j9 = self._quick_create_journal("j9", vanilla_company3)
j10 = self._quick_create_journal("j10", vanilla_company3)
# With all companies selected, all journals should be displayed
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "All Journals", [
(j1, False),
(j2, False),
(j5, False),
(j6, False),
(j3, False),
(j4, False),
(j7, False),
(j8, False),
(j10, False),
(j9, False),
])
self._press_journal_filter(options, (j1 + j5 + j3 + j7 + j9))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "j1, j5, j3, j7, j9", [
(j1, True),
(j2, False),
(j5, True),
(j6, False),
(j3, True),
(j4, False),
(j7, True),
(j8, False),
(j10, False),
(j9, True),
])
# Select only the child company
self.env.user.write({
'company_ids': [Command.set((vanilla_company3).ids)],
'company_id': vanilla_company3.id,
})
# Parent company journals should be displayed too
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "All Journals", [
(j1, False),
(j2, False),
(j5, False),
(j6, False),
(j10, False),
(j9, False),
])
self._press_journal_filter(options, (j1 + j5 + j10))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "j1, j5, j10", [
(j1, True),
(j2, False),
(j5, True),
(j6, False),
(j10, True),
(j9, False),
])
# Select only the parent company
self.env.user.write({
'company_ids': [Command.set((self.vanilla_company1).ids)],
'company_id': self.vanilla_company1.id,
})
# Only parent company journals should be displayed
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "All Journals", [
(j1, False),
(j2, False),
(j5, False),
(j6, False),
])
self._press_journal_filter(options, (j1 + j5))
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "j1, j5", [
(j1, True),
(j2, False),
(j5, True),
(j6, False),
])
def test_journal_filter_with_groups_no_company_multi_company(self):
"""Test the journals filter with a group where no company is set, therefore implying that all companies can
visualize the filter in their accounting reports"""
j1 = self._quick_create_journal("j1", self.vanilla_company1)
j2 = self._quick_create_journal("j2", self.vanilla_company1)
j3 = self._quick_create_journal("j3", self.vanilla_company1)
j4 = self._quick_create_journal("j4", self.vanilla_company2)
j5 = self._quick_create_journal("j5", self.vanilla_company2)
g1 = self._quick_create_journal_group("g1", j1)
g2 = self._quick_create_journal_group("g2", j2 + j5)
gaap_group = self.env['account.journal.group'].browse(['local_gaap'])
# only select company 2
self.env.user.write({
'company_ids': [Command.set(self.vanilla_company2.ids)],
'company_id': self.vanilla_company2.id,
})
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g2, False),
(j4, True),
(j5, False),
])
self.env.user.write({
'company_ids': [Command.set((self.vanilla_company1 + self.vanilla_company2).ids)],
'company_id': self.vanilla_company2.id,
})
# Open report
options['is_opening_report'] = True
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(g2, False),
(j1, False),
(j2, False),
(j3, True),
(j4, True),
(j5, False),
])
# Check g1
options['__journal_group_action'] = {'action': 'add', 'id': g1.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap, g1", [
(gaap_group, True),
(g1, True),
(g2, False),
(j1, True),
(j2, False),
(j3, True),
(j4, True),
(j5, False),
])
# Check g2
options['__journal_group_action'] = {'action': 'add', 'id': g2.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "All Journals", [
(gaap_group, True),
(g1, True),
(g2, True),
(j1, True),
(j2, True),
(j3, True),
(j4, True),
(j5, True),
])
# only select company 1
self.env.user.write({
'company_ids': [Command.set(self.vanilla_company1.ids)],
'company_id': self.vanilla_company1.id,
})
# The company is changed -> reset the journals filter and select the first available group
options = self.report.get_options({'is_opening_report': True})
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(g2, False),
(j1, False),
(j2, False),
(j3, True),
])
# Check g2
options['__journal_group_action'] = {'action': 'add', 'id': g2.id}
options = self.report.get_options(previous_options=options)
self._assert_filter_journal(options, "Local Gaap, g2", [
(gaap_group, True),
(g1, False),
(g2, True),
(j1, False),
(j2, True),
(j3, True),
])
def test_filter_journal_visible_items(self):
""" Test the unfolded and visible attributes of the dropdown items of the journals filter """
j1 = self._quick_create_journal("j1", self.vanilla_company1)
j2 = self._quick_create_journal("j2", self.vanilla_company2)
g1 = self._quick_create_journal_group("g1", j1)
options = self.report.get_options({'is_opening_report': True})
gaap_group = self.env['account.journal.group'].browse(['local_gaap'])
self._assert_filter_journal(options, "Local Gaap", [
(gaap_group, True),
(g1, False),
(j1, False),
(j2, True),
])
# visible, unfolded
expected_values_at_opening = [
(False, False),
(False, False)
]
# Ensure that when opening the report for the first time, all companies are folded
self._assert_filter_journal_visible_unfolded(options, expected_values_at_opening)
# simulate unfold of 1st company
options['journals'][0]['unfolded'] = True
options['journals'][0]['visible'] = True
options = self.report.get_options(previous_options=options)
expected_values_after_unfolding = [
(True, True),
(False, False)
]
self._assert_filter_journal_visible_unfolded(options, expected_values_after_unfolding)
# simulate the refresh of the page, should fold back the 1st company
options['is_opening_report'] = True
options = self.report.get_options(previous_options=options)
self._assert_filter_journal_visible_unfolded(options, expected_values_at_opening)

View File

@@ -0,0 +1,143 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# pylint: disable=C0326
from odoo import fields
from odoo.tests import tagged
from odoo.tools import html2plaintext
from odoo.addons.account.tests.common import AccountTestInvoicingHttpCommon
from freezegun import freeze_time
@tagged('post_install', '-at_install')
class TestAccountReportsTours(AccountTestInvoicingHttpCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.report = cls.env.ref('account_reports.balance_sheet')
cls.report.column_ids.sortable = True
# Test the root reports. We don't want to choose US variants if some are installed.
cls.env['account.report'].search([]).variant_report_ids.active = False
# Create moves
cls.account_101401 = cls.env['account.account'].search([
('company_ids', '=', cls.company_data['company'].id),
('code', '=', 101401)
])
cls.bank_suspense_account = cls.company_data['company'].account_journal_suspense_account_id
cls.account_101404 = cls.env['account.account'].search([
('company_ids', '=', cls.company_data['company'].id),
('code', '=', 101404)
])
if not cls.account_101404:
# additional outstanding accounts are created when accounting is not installed
cls.account_101404 = cls.env['account.account'].search([
('company_ids', '=', cls.company_data['company'].id),
('code', '=', 'OSTR00')
])
cls.account_101404.code = '101404'
cls.account_121000 = cls.env['account.account'].search([
('company_ids', '=', cls.company_data['company'].id),
('code', '=', 121000)
])
cls.account_251000 = cls.env['account.account'].search([
('company_ids', '=', cls.company_data['company'].id),
('code', '=', 251000)
])
move = cls.env['account.move'].create({
'move_type': 'entry',
'date': '2022-06-01',
'journal_id': cls.company_data['default_journal_cash'].id,
'line_ids': [
(0, 0, {'debit': 75.0, 'credit': 0.0, 'account_id': cls.account_101401.id}),
(0, 0, {'debit': 100.0, 'credit': 0.0, 'account_id': cls.bank_suspense_account.id}),
(0, 0, {'debit': 50.0, 'credit': 0.0, 'account_id': cls.account_101404.id}),
(0, 0, {'debit': 25.0, 'credit': 0.0, 'account_id': cls.account_121000.id}),
(0, 0, {'debit': 0.0, 'credit': 250.0, 'account_id': cls.account_251000.id}),
],
})
move.action_post()
def test_account_reports_tours(self):
self.start_tour("/odoo/action-account_reports.action_account_report_bs", 'account_reports_tour', login=self.env.user.login)
def test_account_reports_annotations_tours(self):
annotations = self.env['account.report.annotation'].search([])
date = fields.Date.today().strftime('%Y-%m-%d')
message_101401 = self.env['mail.message'].create({
'model': 'account.account',
'res_id': self.account_101401.id,
'body': 'Annotation 101401',
'date': date,
'author_id': self.env.user.partner_id.id,
'message_type': 'comment',
'subtype_id': self.env.ref('mail.mt_note').id,
})
annotation_101401 = self.env['account.report.annotation'].create({
'date': date,
'message_id': message_101401.id,
})
message_101404 = self.env['mail.message'].create({
'model': 'account.account',
'res_id': self.account_101404.id,
'body': 'Annotation 101404',
'date': date,
'author_id': self.env.user.partner_id.id,
'message_type': 'comment',
'subtype_id': self.env.ref('mail.mt_note').id,
})
annotation_101404 = self.env['account.report.annotation'].create({
'date': date,
'message_id': message_101404.id,
})
self.start_tour("/odoo/action-account_reports.action_account_report_bs", 'account_reports_annotations', login=self.env.user.login)
annotations = self.env['account.report.annotation'].search([]) - annotations # remove annotations already present before the tour
self.assertEqual(len(annotations), 2, "There should be two annotations")
self.assertTrue(annotation_101401 in annotations, "The annotation on account 101401 should still exist")
self.assertTrue(annotation_101404 not in annotations, "The annotation on account 101404 should have been deleted")
new_message = (annotations - annotation_101401).message_id
self.assertEqual(new_message.model, "account.account", "The new message should be linked to an account")
self.assertEqual(new_message.res_id, self.account_121000.id, "The new message should be linked to account 121000")
def test_account_reports_audit_tours(self):
self.start_tour("/odoo/action-account_reports.action_view_account_audit", 'account_reports_audit', login=self.env.user.login)
messages = self.env['mail.message'].search([
('model', '=', 'account.account')
])
annotations = self.env['account.report.annotation'].search([
('message_id', 'in', messages.ids)
])
self.assertEqual(len(messages), 1, "There should be one message created by the tour")
self.assertEqual(len(annotations), 1, "There should be one annotation created by the tour")
self.assertEqual(bool(annotations.date), True, "The message should be an annotation (pinned)")
self.assertEqual(html2plaintext(messages.body), "Annotation from the audit", "The message body should match the expected annotation text")
@freeze_time('2016-12-13')
def test_account_reports_load_more_tour(self):
self.env.ref('account_reports.aged_receivable_report').load_more_limit = 1
partner_c = self.env['res.partner'].create({'name': "partner_c"})
self.init_invoice('out_invoice', partner=self.partner_a, invoice_date='2016-01-01', amounts=[100], post=True)
self.init_invoice('out_invoice', partner=self.partner_a, invoice_date='2016-01-01', amounts=[200], post=True)
self.init_invoice('out_invoice', partner=self.partner_b, invoice_date='2016-01-01', amounts=[300], post=True)
self.init_invoice('out_invoice', partner=partner_c, invoice_date='2016-01-01', amounts=[400], post=True)
self.start_tour('/odoo/action-account_reports.action_account_report_ar', 'account_reports_load_more', login=self.env.user.login)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
from freezegun import freeze_time
from unittest.mock import patch
from odoo import Command
from odoo.tests import tagged
from odoo.addons.account.tests.common import AccountTestInvoicingHttpCommon
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestAccountReturnTours(AccountTestInvoicingHttpCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.startClassPatcher(freeze_time('2024-12-31'))
default_group_ids = cls.env.user.group_ids.ids
required_group_ids = [
*default_group_ids,
# Required to see the views
cls.env.ref('account.group_account_user').id
]
cls.account_return_user = cls.env['res.users'].create({
'name': 'Account Return Test User',
'login': 'account_return_test_user',
'group_ids': [
Command.link(id)
for id in required_group_ids
],
})
# Init tax closing journal so that it is set on the dashboard
# By default the journal only appears when `accountant` is installed.
journal = cls.env.company._get_tax_closing_journal()
journal.show_on_dashboard = True
def test_account_return_basic_tax_return(self):
# states_workflow is by default generic_state_tax_report when this is a return linked to a tax report
self.dummy_tax_return_type = self.env['account.return.type'].create([{
'name': "DUMMY_TAX",
'report_id': self.env.ref('account.generic_tax_report').id,
}])
self.dummy_tax_return_type._try_create_returns_for_fiscal_year(self.env.company, False)
with patch.object(self.env.registry['ir.actions.report'], '_run_pdf_engine_without_processing', return_value=b"0"):
self.start_tour("/odoo/accounting", 'account_return_flow_tax_return', login=self.account_return_user.login)

View File

@@ -0,0 +1,626 @@
from odoo import Command
from odoo.addons.account_reports.tests.account_sales_report_common import AccountSalesReportCommon
from odoo.tests import tagged
from freezegun import freeze_time
@tagged('post_install', '-at_install')
class AccountSalesReportTest(AccountSalesReportCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env.company.totals_below_sections = False
cls.report_generic = cls.env.ref('account_reports.generic_ec_sales_report')
cls.env.company.account_fiscal_country_id = cls.env.ref('base.pt').id
columns = ['country_code', 'vat_number', 'goods', 'services', 'triangular', 'balance']
cls.report_groupby_partner = cls._create_ec_sales_report(grouping_key='partner_id', columns=columns, name="Report using grouping per partner")
columns = ['country_code', 'vat_number', 'sale_type_shortcut', 'balance']
cls.report_groupby_partner_and_category = cls._create_ec_sales_report(grouping_key='partner_id_and_sale_type', columns=columns, name="Report using grouping per partner and category")
cls.goods_tag = cls.env['account.account.tag'].create([{
'name': "goods",
'applicability': 'taxes',
'country_id': cls.env.company.account_fiscal_country_id.id,
}])
cls.services_tag = cls.env['account.account.tag'].create([{
'name': "services",
'applicability': 'taxes',
'country_id': cls.env.company.account_fiscal_country_id.id,
}])
cls.triangular_tag = cls.env['account.account.tag'].create([{
'name': "triangular",
'applicability': 'taxes',
'country_id': cls.env.company.account_fiscal_country_id.id,
}])
tax_group = cls.env['account.tax.group'].create({
'name': 'Test tax group',
'country_id': cls.env.company.account_fiscal_country_id.id,
'company_id': cls.env.company.id,
})
cls.goods_tax = cls.env['account.tax'].create([{
'name': 'goods',
'amount_type': 'percent',
'amount': 0,
'type_tax_use': 'sale',
'price_include_override': 'tax_excluded',
'include_base_amount': False,
'country_id': cls.env.company.account_fiscal_country_id.id,
'tax_group_id': tax_group.id,
'invoice_repartition_line_ids': [
Command.create({
'repartition_type': 'base',
'tag_ids': [Command.set(cls.goods_tag.ids)],
}),
Command.create({'repartition_type': 'tax'}),
],
}])
cls.triangular_tax = cls.env['account.tax'].create([{
'name': 'triangular',
'amount_type': 'percent',
'amount': 0,
'type_tax_use': 'sale',
'price_include_override': 'tax_excluded',
'include_base_amount': False,
'country_id': cls.env.company.account_fiscal_country_id.id,
'tax_group_id': tax_group.id,
'invoice_repartition_line_ids': [
Command.create({
'repartition_type': 'base',
'tag_ids': [Command.set(cls.triangular_tag.ids)],
}),
Command.create({'repartition_type': 'tax'}),
],
}])
cls.services_tax = cls.env['account.tax'].create([{
'name': 'services',
'amount_type': 'percent',
'amount': 0,
'type_tax_use': 'sale',
'price_include_override': 'tax_excluded',
'include_base_amount': False,
'country_id': cls.env.company.account_fiscal_country_id.id,
'tax_group_id': tax_group.id,
'invoice_repartition_line_ids': [
Command.create({
'repartition_type': 'base',
'tag_ids': [Command.set(cls.services_tag.ids)],
}),
Command.create({'repartition_type': 'tax'}),
],
}])
cls.bad_tax_1 = cls.env['account.tax'].create([{
'name': 'bad_1',
'amount_type': 'fixed',
'amount': 0,
'type_tax_use': 'sale',
'price_include_override': 'tax_excluded',
'include_base_amount': False,
}])
cls.bad_tax_2 = cls.env['account.tax'].create([{
'name': 'bad_2',
'amount_type': 'percent',
'amount': 10,
'type_tax_use': 'sale',
'price_include_override': 'tax_excluded',
'include_base_amount': False,
}])
cls.bad_tax_3 = cls.env['account.tax'].create([{
'name': 'bad_2',
'amount_type': 'percent',
'amount': 0,
'type_tax_use': 'purchase',
'price_include_override': 'tax_excluded',
'include_base_amount': False,
}])
# -------------------------------------------------------------------------
# HELPER METHODS
# -------------------------------------------------------------------------
@classmethod
def _create_ec_sales_report(cls, grouping_key, columns, name):
return cls.env['account.report'].create([{
'name': name,
'root_report_id': cls.env.ref('account_reports.generic_ec_sales_report').id,
'custom_handler_model_id': cls.env.ref('account_reports.model_account_ec_sales_with_tags_report_handler').id,
'column_ids': [
Command.create({
'name': col,
'expression_label': col,
'figure_type': 'string',
'sortable': True
})
for col in columns
],
'line_ids': [
Command.create({
'name': 'EC Sales Report',
'code': 'ec',
'groupby': grouping_key,
'foldability': 'always_unfolded',
'expression_ids': [
Command.create({
'label': col,
'engine': 'custom',
'formula': '_report_engine_ec_sales_report',
'auditable': True,
'subformula': col
})
for col in columns
],
})
]
}])
def _generate_ec_sales_report_options(self, report, date_from, date_to, default_options=None):
""" Generates options and simulate what each custom options initializer is supposed to do in localizations.
The name key is only useful for report with a grouping 'partner_id_and_sale_type'
"""
default_options = {} if default_options is None else default_options
default_options['sales_report_operation_types'] = {
'goods': {
'tax_tag_ids': self.goods_tag.ids,
'name': 'Goods',
'shortcut': 'G',
},
'services': {
'tax_tag_ids': self.services_tag.ids,
'name': 'Services',
'shortcut': 'S',
},
'triangular': {
'tax_tag_ids': self.triangular_tag.ids,
'name': 'Triangular',
'shortcut': 'T',
},
}
options = self._generate_options(report, date_from, date_to, default_options)
return options
# -------------------------------------------------------------------------
# TESTS
# -------------------------------------------------------------------------
@freeze_time('2019-12-31')
def test_ec_sales_report(self):
self._create_invoices([
(self.partner_a, self.goods_tax[:1], 100),
(self.partner_a, self.goods_tax[:1], 200),
(self.partner_a, self.triangular_tax[:1], 300),
(self.partner_b, self.triangular_tax[:1], 100),
(self.partner_a, self.services_tax[:1], 400),
(self.partner_b, self.services_tax[:1], 500),
(self.partner_b, self.bad_tax_1[:1], 700), # Should be ignored from generic report due to fixed amount
(self.partner_b, self.bad_tax_2[:1], 700), # Should be ignored from generic report due to non-null amount
(self.partner_b, self.bad_tax_3[:1], 700), # Should be ignored from generic report due to purchase tax
])
# Generic Report
options = self._generate_options(self.report_generic, '2019-12-01', '2019-12-31')
self.assertLinesValues(
self.report_generic._get_lines(options),
# Partner country code VAT Number Amount
[0, 1, 2, 3],
[
('EC Sales Report', '', '', 1600.0),
(self.partner_a.name, self.partner_a.vat[:2], self.partner_a.vat[2:], 1000.0),
(self.partner_b.name, self.partner_b.vat[:2], self.partner_b.vat[2:], 600.0),
],
options,
)
# Report Groupby Partner
options = self._generate_ec_sales_report_options(self.report_groupby_partner, '2019-12-01', '2019-12-31')
self.assertLinesValues(
self.report_groupby_partner._get_lines(options),
# Partner country code VAT Number Goods Services Triangular Amount
[0, 1, 2, 3, 4, 5, 6],
[
('EC Sales Report', '', '', 300.0, 900.0, 400.0, 1600.0),
(self.partner_a.name, self.partner_a.vat[:2], self.partner_a.vat[2:], 300.0, 400.0, 300.0, 1000.0),
(self.partner_b.name, self.partner_b.vat[:2], self.partner_b.vat[2:], 0.0, 500.0, 100.0, 600.0),
],
options,
)
# Report Groupby Partner and Tax Code
options = self._generate_ec_sales_report_options(self.report_groupby_partner_and_category, '2019-12-01', '2019-12-31')
self.assertLinesValues(
self.report_groupby_partner_and_category._get_lines(options),
# Partner country code VAT Number Tax Code Amount
[0, 1, 2, 3, 4],
[
('EC Sales Report', '', '', '', 1600.0),
(self.partner_a.name, self.partner_a.vat[:2], self.partner_a.vat[2:], 'G', 300.0),
(self.partner_a.name, self.partner_a.vat[:2], self.partner_a.vat[2:], 'S', 400.0),
(self.partner_a.name, self.partner_a.vat[:2], self.partner_a.vat[2:], 'T', 300.0),
(self.partner_b.name, self.partner_b.vat[:2], self.partner_b.vat[2:], 'S', 500.0),
(self.partner_b.name, self.partner_b.vat[:2], self.partner_b.vat[2:], 'T', 100.0),
],
options,
)
@freeze_time('2019-12-31')
def test_ec_sales_report_with_northern_irish_customer(self):
"""
Ensure that Northern Irish companies are included in the EC sales report.
"""
northern_ireland = self.env.ref('base.xi')
self.partner_a.write({
'country_id': northern_ireland.id,
'vat': 'IE1234567FA',
})
self._create_invoices([(self.partner_a, self.goods_tax, 100)])
options = self._generate_options(self.report_generic, '2019-12-01', '2019-12-31')
self.assertLinesValues(
self.report_generic._get_lines(options),
# Partner, country code, VAT Number, Amount
[ 0, 1, 2, 3],
[
('EC Sales Report', '', '', 100.0),
(self.partner_a.name, self.partner_a.vat[:2], self.partner_a.vat[2:], 100.0),
],
options,
)
def test_ec_sales_set_as_main(self):
"""Test setting a partner as the main in EC Sales Report when two partners share the same VAT.
Scenario:
- Two partners have the same VAT.
- Set one partner as the main partner.
- Validate that the second partner is linked correctly as a child and that moves are updated.
"""
# Prepare partners
partner_main = self.partner_a
partner_duplicate = self.partner_b
partner_duplicate.vat = partner_main.vat
move_vals = {
'move_type': 'out_invoice',
'invoice_date': '2025-04-29',
'invoice_line_ids': [Command.create({
'quantity': 1,
'price_unit': 500.0,
'tax_ids': [],
})],
}
# Create and post invoice for the main partner
move_main = self.env['account.move'].create({**move_vals, 'partner_id': partner_main.id})
move_main.action_post()
# Create and post invoice for the duplicate partner
move_duplicate = self.env['account.move'].create({**move_vals, 'partner_id': partner_duplicate.id})
move_duplicate.action_post()
# Call with context
partner_main.with_context(duplicate_partners_vat=[partner_main.vat, partner_duplicate.vat]).set_commercial_partner_main()
# Assertions: partner relationships
self.assertEqual(
partner_duplicate.commercial_partner_id, partner_main,
"Duplicate partner's commercial partner should be the main partner."
)
self.assertEqual(
partner_duplicate.parent_id, partner_main,
"Duplicate partner's parent should be set to the main partner."
)
# Assertions: accounting move reassignment
self.assertEqual(
move_duplicate.commercial_partner_id, partner_main,
"The move's commercial partner should also be reassigned."
)
# Assertions: journal items (move lines)
self.assertEqual(
move_duplicate.line_ids.partner_id, partner_main,
"Each move line should now be assigned to the main partner."
)
def test_ec_sales_report_with_other_groupby_levels(self):
"""Ensure generic EC Sales report works with other groupings, either before or after the default 'partner_id' key"""
self._create_invoices([
(self.partner_a, self.goods_tax[:1], 100),
(self.partner_b, self.goods_tax[:1], 200),
(self.partner_a, self.services_tax[:1], 300),
(self.partner_b, self.services_tax[:1], 400),
])
# Generic Report
self.report_generic.line_ids[0].user_groupby = 'company_id,partner_id,id'
self.report_generic.filter_unfold_all = True
options = self._generate_options(self.report_generic, '2019-12-01', '2019-12-31', default_options={'unfold_all': True})
self.assertLinesValues(
self.report_generic._get_lines(options),
# Partner, country code VAT Number Amount
[0, 1, 2, 3],
[
('EC Sales Report', '', '', 1000.0),
('company_1_data', '', '', 1000.0),
('Partner A', 'FR', '23334175221', 400.0),
('INV/2019/00003 line_1', '', '', 300.0),
('INV/2019/00001 line_1', '', '', 100.0),
('Partner B', 'BE', '0477472701', 600.0),
('INV/2019/00004 line_1', '', '', 400.0),
('INV/2019/00002 line_1', '', '', 200.0),
],
options,
)
# Report Groupby Partner
self.report_groupby_partner.line_ids[0].user_groupby = 'company_id,partner_id,id'
self.report_groupby_partner.filter_unfold_all = True
options = self._generate_ec_sales_report_options(self.report_groupby_partner, '2019-12-01', '2019-12-31', default_options={'unfold_all': True})
self.assertLinesValues(
self.report_groupby_partner._get_lines(options),
# Partner country code VAT Number Goods Services Triangular Amount
[0, 1, 2, 3, 4, 5, 6],
[
('EC Sales Report', '', '', 300.0, 700.0, 0.0, 1000.0),
('company_1_data', '', '', 300.0, 700.0, 0.0, 1000.0),
('Partner A', 'FR', '23334175221', 100.0, 300.0, 0.0, 400.0),
('INV/2019/00003 line_1', '', '', 0.0, 300.0, 0.0, 300.0),
('INV/2019/00001 line_1', '', '', 100.0, 0.0, 0.0, 100.0),
('Partner B', 'BE', '0477472701', 200.0, 400.0, 0.0, 600.0),
('INV/2019/00004 line_1', '', '', 0.0, 400.0, 0.0, 400.0),
('INV/2019/00002 line_1', '', '', 200.0, 0.0, 0.0, 200.0),
],
options,
)
# Report Groupby Partner and Tax Code
self.report_groupby_partner_and_category.line_ids[0].user_groupby = 'company_id,partner_id,partner_id_and_sale_type,id'
self.report_groupby_partner_and_category.filter_unfold_all = True
options = self._generate_ec_sales_report_options(self.report_groupby_partner_and_category, '2019-12-01', '2019-12-31', default_options={'unfold_all': True})
self.assertLinesValues(
self.report_groupby_partner_and_category._get_lines(options),
# Partner country code VAT Number Tax Code Amount
[0, 1, 2, 3, 4],
[
('EC Sales Report', '', '', '', 1000.0),
( 'company_1_data', '', '', '', 1000.0),
( 'Partner A', 'FR', '23334175221', '', 400.0),
( 'Partner A', 'FR', '23334175221', 'G', 100.0),
( 'INV/2019/00001 line_1', '', '', '', 100.0),
( 'Partner A', 'FR', '23334175221', 'S', 300.0),
( 'INV/2019/00003 line_1', '', '', '', 300.0),
( 'Partner B', 'BE', '0477472701', '', 600.0),
( 'Partner B', 'BE', '0477472701', 'G', 200.0),
( 'INV/2019/00002 line_1', '', '', '', 200.0),
( 'Partner B', 'BE', '0477472701', 'S', 400.0),
( 'INV/2019/00004 line_1', '', '', '', 400.0),
],
options,
)
@freeze_time('2019-12-31')
def test_ec_sales_generic_report_double_taxes_applied(self):
""" A move with 2 valid taxes should not be counted twice in the report """
invoice = self.env['account.move'].create([{
'move_type': 'out_invoice',
'date': '2019-12-01',
'partner_id': self.partner_a.id,
'invoice_line_ids': [
Command.create({
'name': "line 1",
'price_unit': 100,
'tax_ids': [Command.set((self.goods_tax + self.services_tax).ids)],
})
]
}])
invoice.action_post()
options = self._generate_options(self.report_generic, '2019-12-01', '2019-12-31')
self.assertLinesValues(
self.report_generic._get_lines(options),
# Partner, country code VAT Number Amount
[0, 1, 2, 3],
[
('EC Sales Report', '', '', 100.0),
('Partner A', 'FR', '23334175221', 100.0),
],
options,
)
@freeze_time('2019-12-31')
def test_ec_sales_report_double_tags_applied(self):
""" Ensure that if 2 tags are used on the same account move line, then the aml is not
counted twice on the report (Austrian use case, reason of the CTE in the query) """
other_goods_tag = self.env['account.account.tag'].create([{
'name': "goods_2",
'applicability': 'taxes',
'country_id': self.env.company.country_id.id,
}])
goods_tax_double_tags = self.env['account.tax'].create([{
'name': 'goods with double tags',
'amount_type': 'percent',
'amount': 0,
'type_tax_use': 'sale',
'price_include_override': 'tax_excluded',
'include_base_amount': False,
'invoice_repartition_line_ids': [
Command.create({
'repartition_type': 'base',
'tag_ids': [Command.set((self.goods_tag | other_goods_tag).ids)],
}),
Command.create({'repartition_type': 'tax'}),
],
}])
invoice = self.env['account.move'].create([{
'move_type': 'out_invoice',
'date': '2019-12-01',
'partner_id': self.partner_a.id,
'invoice_line_ids': [
Command.create({
'name': "line 1",
'price_unit': 100,
'tax_ids': [Command.set(goods_tax_double_tags.ids)],
})
]
}])
invoice.action_post()
options = self._generate_ec_sales_report_options(self.report_groupby_partner, '2019-12-01', '2019-12-31')
options['sales_report_operation_types']['goods']['tax_tag_ids'] = (self.goods_tag | other_goods_tag).ids
self.assertLinesValues(
self.report_groupby_partner._get_lines(options),
# Partner country code VAT Number Goods Services Triangular Amount
[0, 1, 2, 3, 4, 5, 6],
[
('EC Sales Report', '', '', 100.0, 0.0, 0.0, 100.0),
('Partner A', 'FR', '23334175221', 100.0, 0.0, 0.0, 100.0),
],
options,
)
def test_ec_sales_report_filter_selection(self):
""" Ensure that the ec categories are filtered out if the corresponding filter is not selected """
self._create_invoices([
(self.partner_a, self.goods_tax[:1], 100),
(self.partner_a, self.services_tax[:1], 100), # Should be hidden since service filter is not selected
])
options = self._generate_ec_sales_report_options(self.report_groupby_partner_and_category, '2019-12-01', '2019-12-31')
options['filter_sale_type_selection'] = [
{'id': 'goods', 'name': 'goods', 'selected': True},
{'id': 'services', 'name': 'services', 'selected': False},
{'id': 'triangular', 'name': 'triangular', 'selected': True},
]
self.assertLinesValues(
self.report_groupby_partner_and_category._get_lines(options),
# Partner country code VAT Number Tax Code Amount
[0, 1, 2, 3, 4],
[
('EC Sales Report', '', '', '', 100.0),
(self.partner_a.name, self.partner_a.vat[:2], self.partner_a.vat[2:], 'G', 100.0),
],
options,
)
def test_ec_sales_report_warnings(self):
""" Ensure warnings are generated if their conditions are met """
partner_without_vat = self.env['res.partner'].create([{
'name': 'Partner Without VAT Number',
'country_id': self.env.ref('base.ee').id,
}])
partner_same_country = self.env['res.partner'].create([{
'name': 'Partner Same Country',
'vat': '12345678',
'country_id': self.company_data['company'].country_id.id,
}])
partner_no_ec_country = self.env['res.partner'].create([{
'name': 'Partner outside EC countries',
'vat': '11345678',
'country_id': self.env.ref('base.ma').id,
}])
self._create_invoices([
(partner_without_vat, self.goods_tax[:1], 100),
(partner_same_country, self.goods_tax[:1], 100),
(partner_no_ec_country, self.goods_tax[:1], 100),
])
options = self._generate_ec_sales_report_options(self.report_groupby_partner, '2019-12-01', '2019-12-31')
report_information = self.report_groupby_partner.get_report_information(options)
self.assertEqual(
report_information['warnings'],
{
'account_reports.sales_report_warning_missing_vat': {'alert_type': 'warning'},
'account_reports.sales_report_warning_non_ec_country': {'alert_type': 'warning'},
'account_reports.sales_report_warning_same_country': {'alert_type': 'warning'},
}
)
def test_ec_sales_report_warnings_children(self):
""" Ensure warnings are generated if their conditions are met """
partner_same_country = self.env['res.partner'].create([{
'name': 'Partner Same Country',
'vat': '12345678',
'country_id': self.company_data['company'].country_id.id,
'child_ids': [
Command.create({
'type': 'delivery',
'country_id': self.env.ref('base.fr').id,
})
]
}])
partner_no_ec_country = self.env['res.partner'].create([{
'name': 'Partner outside EC countries',
'vat': '11345678',
'country_id': self.env.ref('base.ma').id,
'child_ids': [
Command.create({
'type': 'delivery',
'country_id': self.env.ref('base.fr').id,
})
]
}])
self._create_invoices([
(partner_same_country.child_ids[0], self.goods_tax[:1], 100),
(partner_no_ec_country.child_ids[0], self.goods_tax[:1], 100),
])
options = self._generate_ec_sales_report_options(self.report_groupby_partner, '2019-12-01', '2019-12-31')
report_information = self.report_groupby_partner.get_report_information(options)
self.assertEqual(
report_information['warnings'],
{
'account_reports.sales_report_warning_non_ec_country': {'alert_type': 'warning'},
'account_reports.sales_report_warning_same_country': {'alert_type': 'warning'},
}
)
def test_ec_sales_report_warnings_delivery_address(self):
""" Ensure warnings are generated if their conditions are met on delivery address """
partner = self.env['res.partner'].create([{
'name': 'Partner',
'vat': '12345678',
'country_id': self.company_data['company'].country_id.id,
}])
delivery_address_no_ec_sales_list = self.env['res.partner'].create([{
'name': 'Delivery Address',
'country_id': self.env.ref('base.je').id,
'type': 'delivery',
'parent_id': partner.id,
}])
delivery_address_same_country = self.env['res.partner'].create([{
'name': 'Delivery Address',
'country_id': partner.country_id.id,
'type': 'delivery',
'parent_id': partner.id,
}])
self._create_invoices([
(partner, self.goods_tax[:1], 100, delivery_address_no_ec_sales_list),
(partner, self.goods_tax[:1], 100, delivery_address_same_country),
])
options = self._generate_ec_sales_report_options(self.report_groupby_partner, '2019-12-01', '2019-12-31')
report_information = self.report_groupby_partner.get_report_information(options)
self.assertEqual(
report_information['warnings'],
{
'account_reports.sales_report_warning_non_ec_country': {'alert_type': 'warning'},
'account_reports.sales_report_warning_same_country': {'alert_type': 'warning'},
}
)

View File

@@ -0,0 +1,741 @@
# -*- coding: utf-8 -*-
# pylint: disable=C0326
from .common import TestAccountReportsCommon
from odoo import fields, Command
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestAgedPayableReport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner_category_a = cls.env['res.partner.category'].create({'name': 'partner_categ_a'})
cls.partner_category_b = cls.env['res.partner.category'].create({'name': 'partner_categ_b'})
cls.partner_a.write({'category_id': [Command.set([cls.partner_category_a.id, cls.partner_category_b.id])]})
cls.partner_b.write({'category_id': [Command.set([cls.partner_category_a.id])]})
payable_1 = cls.company_data['default_account_payable']
payable_2 = cls.company_data['default_account_payable'].copy()
payable_3 = cls.company_data['default_account_payable'].copy()
payable_4 = cls.company_data_2['default_account_payable']
payable_5 = cls.company_data_2['default_account_payable'].copy()
payable_6 = cls.company_data_2['default_account_payable'].copy()
misc_1 = cls.company_data['default_account_expense']
misc_2 = cls.company_data_2['default_account_expense']
# Test will use the following dates:
# As of 2017-02-01
# 1 - 30: 2017-01-31 - 2017-01-02
# 31 - 60: 2017-01-01 - 2016-12-03
# 61 - 90: 2016-12-02 - 2016-11-03
# 91 - 120: 2016-11-02 - 2016-10-04
# Older: 2016-10-03
# ==== Journal entries in company_1 for partner_a ====
move_1 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-11-03'),
'journal_id': cls.company_data['default_journal_purchase'].id,
'line_ids': [
# 1000.0 in 61 - 90.
Command.create({'debit': 0.0, 'credit': 1000.0, 'date_maturity': False, 'account_id': payable_1.id, 'partner_id': cls.partner_a.id}),
# -800.0 in 31 - 60
Command.create({'debit': 800.0, 'credit': 0.0, 'date_maturity': '2017-01-01', 'account_id': payable_2.id, 'partner_id': cls.partner_a.id}),
# Ignored line.
Command.create({'debit': 200.0, 'credit': 0.0, 'date_maturity': False, 'account_id': misc_1.id, 'partner_id': cls.partner_a.id}),
],
})
move_2 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-10-05'),
'journal_id': cls.company_data['default_journal_purchase'].id,
'line_ids': [
# -200.0 in 61 - 90
Command.create({'debit': 200.0, 'credit': 0.0, 'date_maturity': '2016-12-02', 'account_id': payable_1.id, 'partner_id': cls.partner_a.id}),
# -300.0 in 31 - 60
Command.create({'debit': 300.0, 'credit': 0.0, 'date_maturity': '2016-12-03', 'account_id': payable_1.id, 'partner_id': cls.partner_a.id}),
# 1000.0 in 91 - 120
Command.create({'debit': 0.0, 'credit': 1000.0, 'date_maturity': False, 'account_id': payable_2.id, 'partner_id': cls.partner_a.id}),
# 100.0 in all dates
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2017-02-01', 'account_id': payable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2017-01-02', 'account_id': payable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2016-12-03', 'account_id': payable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2016-11-03', 'account_id': payable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2016-10-04', 'account_id': payable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2016-01-01', 'account_id': payable_3.id, 'partner_id': cls.partner_a.id}),
# Ignored line.
Command.create({'debit': 1100.0, 'credit': 0.0, 'date_maturity': '2016-10-05', 'account_id': misc_1.id, 'partner_id': cls.partner_a.id}),
],
})
(move_1 + move_2).action_post()
(move_1 + move_2).line_ids.filtered(lambda line: line.account_id == payable_1).reconcile()
(move_1 + move_2).line_ids.filtered(lambda line: line.account_id == payable_2).reconcile()
# ==== Journal entries in company_2 for partner_b ====
move_3 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-11-03'),
'journal_id': cls.company_data_2['default_journal_purchase'].id,
'line_ids': [
# 1000.0 in 61 - 90.
Command.create({'debit': 0.0, 'credit': 1000.0, 'date_maturity': False, 'account_id': payable_4.id, 'partner_id': cls.partner_b.id}),
# -800.0 in 31 - 60
Command.create({'debit': 800.0, 'credit': 0.0, 'date_maturity': '2017-01-01', 'account_id': payable_5.id, 'partner_id': cls.partner_b.id}),
# Ignored line.
Command.create({'debit': 200.0, 'credit': 0.0, 'date_maturity': False, 'account_id': misc_2.id, 'partner_id': cls.partner_b.id}),
],
})
move_4 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-10-05'),
'journal_id': cls.company_data_2['default_journal_purchase'].id,
'line_ids': [
# -200.0 in 61 - 90
Command.create({'debit': 200.0, 'credit': 0.0, 'date_maturity': '2016-12-02', 'account_id': payable_4.id, 'partner_id': cls.partner_b.id}),
# -300.0 in 31 - 60
Command.create({'debit': 300.0, 'credit': 0.0, 'date_maturity': '2016-12-03', 'account_id': payable_4.id, 'partner_id': cls.partner_b.id}),
# 1000.0 in 91 - 120
Command.create({'debit': 0.0, 'credit': 1000.0, 'date_maturity': False, 'account_id': payable_5.id, 'partner_id': cls.partner_b.id}),
# 100.0 in all dates
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2017-02-01', 'account_id': payable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2017-01-02', 'account_id': payable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2016-12-03', 'account_id': payable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2016-11-03', 'account_id': payable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2016-10-04', 'account_id': payable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'date_maturity': '2016-01-01', 'account_id': payable_6.id, 'partner_id': cls.partner_b.id}),
# Ignored line.
Command.create({'debit': 1100.0, 'credit': 0.0, 'date_maturity': '2016-10-05', 'account_id': misc_2.id, 'partner_id': cls.partner_b.id}),
],
})
(move_3 + move_4).action_post()
(move_3 + move_4).line_ids.filtered(lambda line: line.account_id == payable_4).reconcile()
(move_3 + move_4).line_ids.filtered(lambda line: line.account_id == payable_5).reconcile()
cls.env['res.currency'].search([('name', '!=', 'USD')]).with_context(force_deactivate=True).active = False
companies = cls.company_data['company'] + cls.company_data_2['company']
cls.env = cls.env(context=dict(cls.env.context, allowed_company_ids=companies.ids))
cls.report = cls.env.ref('account_reports.aged_payable_report')
cls.parent_line_id = cls._get_basic_line_dict_id_from_report_line_ref("account_reports.aged_payable_line")
def test_aged_payable_unfold_1_whole_report(self):
""" Test unfolding a line when rendering the whole report. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
partner_a_line_id = self.report._get_generic_line_id('res.partner', self.partner_a.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
options['unfolded_lines'] = [partner_a_line_id]
report_lines = self.report._get_lines(options)
# Sort by Invoice Date
options['order_column'] = {
'expression_label': 'invoice_date',
'direction': 'ASC',
}
sorted_report_lines = self.report._sort_lines(report_lines, options)
self.assertLinesValues(
# pylint: disable=C0326
sorted_report_lines,
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
# Sort 61 - 90 decreasing.
options['order_column'] = {
'expression_label': 'period3',
'direction': 'DESC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(sorted_report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
# Sort 61 - 90 increasing.
options['order_column'] = {
'expression_label': 'period3',
'direction': 'ASC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(sorted_report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
def test_aged_payable_unfold_all(self):
default_options = {
'unfold_all': True,
'order_column': {
'expression_label': 'invoice_date',
'direction': 'ASC',
}
}
options = self._generate_options(self.report, '2017-02-01', '2017-02-01', default_options=default_options)
report_lines = self.report._get_lines(options)
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options
)
def test_aged_payable_unfold_all_with_integer_rounding(self):
"""Test unfolding a line when rendering the whole report with integer rounding."""
self.report.integer_rounding = 'HALF-UP'
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
partner_a_line_id = self.report._get_generic_line_id('res.partner', self.partner_a.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
options['unfolded_lines'] = [partner_a_line_id]
report_lines = self.report._get_lines(options)
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options
)
def test_aged_payable_unknown_partner(self):
""" Test that journal items without a partner in the payable account appear as unknown partner. """
misc_move = self.env['account.move'].create({
'date': '2017-03-31',
'line_ids': [
Command.create({'debit': 0.0, 'credit': 1000.0, 'account_id': self.company_data['default_account_expense'].id}),
Command.create({'debit': 1000.0, 'credit': 0.0, 'account_id': self.company_data['default_account_payable'].id}),
],
})
misc_move.action_post()
options = self._generate_options(self.report, '2017-03-01', '2017-04-01')
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 0.0, -1000.0, 150.0, 150.0, 150.0, 1500.0, 950.0),
('partner_a', 0.0, 0.0, 100.0, 100.0, 100.0, 1000.0, 1300.0),
('partner_b', 0.0, 0.0, 50.0, 50.0, 50.0, 500.0, 650.0),
('Unknown', 0.0, -1000.0, 0.0, 0.0, 0.0, 0.0, -1000.0),
],
options,
)
def test_aged_payable_filter_partners(self):
""" Test the filter on top allowing to filter on res.partner. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
options['partner_ids'] = self.partner_a.ids
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Invoice Date Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 1, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', '', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_a', '', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
],
options,
)
def test_aged_payable_filter_partner_categories(self):
""" Test the filter on top allowing to filter on res.partner.category. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
options['partner_categories'] = self.partner_category_a.ids
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
],
options,
)
def test_aged_payable_reconciliation_date(self):
""" Check the values at a date before some reconciliations are done. """
options = self._generate_options(self.report, '2016-10-31', '2016-10-31')
options['recon_date'] = {'date_to': '2016-10-31'}
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', -133.33, 1466.67, 0.0, 0.0, 0.0, 133.33, 1466.67),
('partner_a', -100.00, 1100.00, 0.0, 0.0, 0.0, 100.00, 1100.00),
('partner_b', -33.33, 366.67, 0.0, 0.0, 0.0, 33.33, 366.67),
],
options,
)
def test_aged_payablesort_lines_by_date(self):
""" Test the _sort_lines function using date as sort key. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
partner_a_line_id = self.report._get_generic_line_id('res.partner', self.partner_a.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
partner_b_line_id = self.report._get_generic_line_id('res.partner', self.partner_b.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
options['unfolded_lines'] = [partner_a_line_id, partner_b_line_id]
# Sort by Invoice Date increasing
options['order_column'] = {
'expression_label': 'invoice_date',
'direction': 'ASC',
}
report_lines = self.report._get_lines(options)
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
# Sort by Invoice Date increasing
options['order_column'] = {
'expression_label': 'invoice_date',
'direction': 'DESC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
def test_aged_payablesort_lines_by_numeric_value(self):
""" Test the _sort_lines function using float as sort key. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
partner_a_line_id = self.report._get_generic_line_id('res.partner', self.partner_a.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
partner_b_line_id = self.report._get_generic_line_id('res.partner', self.partner_b.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
options['unfolded_lines'] = [partner_a_line_id, partner_b_line_id]
report_lines = self.report._get_lines(options)
# Sort by Not Due On increasing
options['order_column'] = {
'expression_label': 'period0',
'direction': 'ASC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('BILL/2016/10/0001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
# Sort by Not Due On decreasing
options['order_column'] = {
'expression_label': 'period0',
'direction': 'DESC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('BILL/2016/10/0001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('BILL/2016/10/0001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/11/0001', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('BILL/2016/10/0001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
def test_aged_payable_zero_balanced_without_reconciliation(self):
options = self._generate_options(self.report, '2010-01-01', '2010-01-01', default_options={'unfold_all': True})
options['recon_date'] = {'date_to': '2010-01-01'}
invoice = self.env['account.move'].create({
'move_type': 'in_invoice',
'partner_id': self.partner_a.id,
'invoice_date': '2010-01-01',
'date': '2010-01-01',
'invoice_date_due': '2010-01-01',
'payment_reference': 'I',
'invoice_line_ids': [Command.create({
'name': 'test invoice',
'price_unit': 100,
'tax_ids': [],
})]
})
invoice.action_post()
refund = self.env['account.move'].create({
'move_type': 'in_refund',
'partner_id': self.partner_a.id,
'invoice_date': '2010-01-01',
'date': '2010-01-01',
'invoice_date_due': '2010-01-01',
'payment_reference': 'R',
'invoice_line_ids': [Command.create({
'name': 'test refund',
'price_unit': 100,
'tax_ids': [],
})]
})
refund.action_post()
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(f"{refund.name} R", -100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
(f"{invoice.name} I", 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('Total Aged Payable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
],
options,
)
# It should still work if both invoice and refund are partially reconciled with the same amount
self.env['account.payment.register'].with_context(active_ids=invoice.ids, active_model='account.move').create({
'amount': 42,
'payment_date': '2010-01-01',
'payment_method_line_id': self.inbound_payment_method_line.id,
})._create_payments()
self.env['account.payment.register'].with_context(active_ids=refund.ids, active_model='account.move').create({
'amount': 42,
'payment_date': '2010-01-01',
'payment_method_line_id': self.inbound_payment_method_line.id,
})._create_payments()
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(f"{refund.name} R", -58.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
(f"{invoice.name} I", 58.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('Total Aged Payable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
],
options,
)
# It should still work if both invoice and refund are fully reconciled in the future
self.env['account.payment.register'].with_context(active_ids=invoice.ids, active_model='account.move').create({
'amount': 58,
'payment_date': '2020-01-01',
'payment_method_line_id': self.inbound_payment_method_line.id,
})._create_payments()
self.env['account.payment.register'].with_context(active_ids=refund.ids, active_model='account.move').create({
'amount': 58,
'payment_date': '2020-01-01',
'payment_method_line_id': self.inbound_payment_method_line.id,
})._create_payments()
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(f"{refund.name} R", -58.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
(f"{invoice.name} I", 58.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('Total Aged Payable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
],
options,
)
def test_aged_payable_aging_interval(self):
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
initial_report_lines = self.report._get_lines(options)
# With default interval of 30
self.assertLinesValues(
self.report._sort_lines(initial_report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options
)
options['aging_interval'] = 60
report_lines = self.report._get_lines(options)
# With interval of 60
self.assertLinesValues(
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 60 61 - 120 121 - 180 181 - 240 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', 150.0, 300.0, 1350.0, 0.0, 0.0, 150.0, 1950.0),
('partner_a', 100.0, 200.0, 900.0, 0.0, 0.0, 100.0, 1300.0),
('partner_b', 50.0, 100.0, 450.0, 0.0, 0.0, 50.0, 650.0),
('Total Aged Payable', 150.0, 300.0, 1350.0, 0.0, 0.0, 150.0, 1950.0),
],
options
)
def test_storno_refund_account_payable(self):
self.env.company.account_storno = True
great_partner = self.env['res.partner'].create({'name': 'Great Partner'})
refund = self.env['account.move'].create({
'move_type': 'in_refund',
'partner_id': great_partner.id,
'invoice_date': '2010-02-01',
'date': '2010-02-01',
'invoice_date_due': '2010-02-01',
'invoice_line_ids': [Command.create({
'name': 'Great Product',
'price_unit': 100,
'tax_ids': [],
})]
})
refund.action_post()
self.env['account.payment.register'].with_context(active_model='account.move', active_ids=refund.ids).create({
'payment_date': '2010-02-01',
'amount': 100.0,
})._create_payments()
options = self._generate_options(self.report, '2010-02-01', '2010-02-01')
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Due Date Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 1, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Payable', '', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
],
options,
)
def test_aged_partner_balance_audit_with_open_on_date(self):
"""Test auditing an aged partner balance cell with an Open On date."""
options = self._generate_options(self.report, '2026-01-01', '2026-12-31')
options['recon_date'] = {'date_to': '2026-07-31'}
line = self.report._get_lines(options)[0]
params = self._get_audit_params_from_report_line(options, self.report.line_ids[0], line)
action = self.report.dispatch_report_action(options, 'action_audit_cell', params)
self.assertEqual(action['context']['search_default_open_on'], '2026-07-31')

View File

@@ -0,0 +1,795 @@
# -*- coding: utf-8 -*-
# pylint: disable=C0326
from .common import TestAccountReportsCommon
from odoo import fields, Command
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestAgedReceivableReport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner_category_a = cls.env['res.partner.category'].create({'name': 'partner_categ_a'})
cls.partner_category_b = cls.env['res.partner.category'].create({'name': 'partner_categ_b'})
cls.partner_a.write({'category_id': [Command.set([cls.partner_category_a.id, cls.partner_category_b.id])]})
cls.partner_b.write({'category_id': [Command.set([cls.partner_category_a.id])]})
receivable_1 = cls.company_data['default_account_receivable']
receivable_2 = cls.copy_account(cls.company_data['default_account_receivable'])
receivable_3 = cls.copy_account(cls.company_data['default_account_receivable'])
receivable_4 = cls.company_data_2['default_account_receivable']
receivable_5 = cls.copy_account(cls.company_data_2['default_account_receivable'])
receivable_6 = cls.copy_account(cls.company_data_2['default_account_receivable'])
misc_1 = cls.company_data['default_account_revenue']
misc_2 = cls.company_data_2['default_account_revenue']
# Test will use the following dates:
# As of 2017-02-01
# 1 - 30: 2017-01-31 - 2017-01-02
# 31 - 60: 2017-01-01 - 2016-12-03
# 61 - 90: 2016-12-02 - 2016-11-03
# 91 - 120: 2016-11-02 - 2016-10-04
# Older: 2016-10-03
# ==== Journal entries in company_1 for partner_a ====
move_1 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-11-03'),
'invoice_date': fields.Date.from_string('2016-11-03'),
'journal_id': cls.company_data['default_journal_sale'].id,
'line_ids': [
# 1000.0 in 61 - 90.
Command.create({'debit': 1000.0, 'credit': 0.0, 'date_maturity': False, 'account_id': receivable_1.id, 'partner_id': cls.partner_a.id}),
# -800.0 in 31 - 60
Command.create({'debit': 0.0, 'credit': 800.0, 'date_maturity': '2017-01-01', 'account_id': receivable_2.id, 'partner_id': cls.partner_a.id}),
# Ignored line.
Command.create({'debit': 0.0, 'credit': 200.0, 'date_maturity': False, 'account_id': misc_1.id, 'partner_id': cls.partner_a.id}),
],
})
move_2 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-10-05'),
'invoice_date': fields.Date.from_string('2016-10-05'),
'journal_id': cls.company_data['default_journal_sale'].id,
'line_ids': [
# -200.0 in 61 - 90
Command.create({'debit': 0.0, 'credit': 200.0, 'date_maturity': '2016-12-02', 'account_id': receivable_1.id, 'partner_id': cls.partner_a.id}),
# -300.0 in 31 - 60
Command.create({'debit': 0.0, 'credit': 300.0, 'date_maturity': '2016-12-03', 'account_id': receivable_1.id, 'partner_id': cls.partner_a.id}),
# 1000.0 in 91 - 120
Command.create({'debit': 1000.0, 'credit': 0.0, 'date_maturity': False, 'account_id': receivable_2.id, 'partner_id': cls.partner_a.id}),
# 100.0 in all dates
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2017-02-01', 'account_id': receivable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2017-01-02', 'account_id': receivable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2016-12-03', 'account_id': receivable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2016-11-03', 'account_id': receivable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2016-10-04', 'account_id': receivable_3.id, 'partner_id': cls.partner_a.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2016-01-01', 'account_id': receivable_3.id, 'partner_id': cls.partner_a.id}),
# Ignored line.
Command.create({'debit': 0.0, 'credit': 1100.0, 'date_maturity': '2016-10-05', 'account_id': misc_1.id, 'partner_id': cls.partner_a.id}),
],
})
(move_1 + move_2).action_post()
(move_1 + move_2).line_ids.filtered(lambda line: line.account_id == receivable_1).reconcile()
(move_1 + move_2).line_ids.filtered(lambda line: line.account_id == receivable_2).reconcile()
# ==== Journal entries in company_2 for partner_b ====
move_3 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-11-03'),
'invoice_date': fields.Date.from_string('2016-11-03'),
'journal_id': cls.company_data_2['default_journal_sale'].id,
'line_ids': [
# 1000.0 in 61 - 90.
Command.create({'debit': 1000.0, 'credit': 0.0, 'date_maturity': False, 'account_id': receivable_4.id, 'partner_id': cls.partner_b.id}),
# -200.0 in 31 - 60
Command.create({'debit': 0.0, 'credit': 800.0, 'date_maturity': '2017-01-01', 'account_id': receivable_5.id, 'partner_id': cls.partner_b.id}),
# Ignored line.
Command.create({'debit': 0.0, 'credit': 200.0, 'date_maturity': False, 'account_id': misc_2.id, 'partner_id': cls.partner_b.id}),
],
})
move_4 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-10-05'),
'invoice_date': fields.Date.from_string('2016-10-05'),
'journal_id': cls.company_data_2['default_journal_sale'].id,
'line_ids': [
# -200.0 in 61 - 90
Command.create({'debit': 0.0, 'credit': 200.0, 'date_maturity': '2016-12-02', 'account_id': receivable_4.id, 'partner_id': cls.partner_b.id}),
# -300.0 in 31 - 60
Command.create({'debit': 0.0, 'credit': 300.0, 'date_maturity': '2016-12-03', 'account_id': receivable_4.id, 'partner_id': cls.partner_b.id}),
# 1000.0 in 91 - 120
Command.create({'debit': 1000.0, 'credit': 0.0, 'date_maturity': False, 'account_id': receivable_5.id, 'partner_id': cls.partner_b.id}),
# 100.0 in all dates
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2017-02-01', 'account_id': receivable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2017-01-02', 'account_id': receivable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2016-12-03', 'account_id': receivable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2016-11-03', 'account_id': receivable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2016-10-04', 'account_id': receivable_6.id, 'partner_id': cls.partner_b.id}),
Command.create({'debit': 100.0, 'credit': 0.0, 'date_maturity': '2016-01-01', 'account_id': receivable_6.id, 'partner_id': cls.partner_b.id}),
# Ignored line.
Command.create({'debit': 0.0, 'credit': 1100.0, 'date_maturity': False, 'account_id': misc_2.id, 'partner_id': cls.partner_b.id}),
],
})
(move_3 + move_4).action_post()
(move_3 + move_4).line_ids.filtered(lambda line: line.account_id == receivable_4).reconcile()
(move_3 + move_4).line_ids.filtered(lambda line: line.account_id == receivable_5).reconcile()
cls.env['res.currency'].search([('name', '!=', 'USD')]).with_context(force_deactivate=True).active = False
companies = cls.company_data['company'] + cls.company_data_2['company']
cls.env = cls.env(context=dict(cls.env.context, allowed_company_ids=companies.ids))
cls.report = cls.env.ref('account_reports.aged_receivable_report')
cls.parent_line_id = cls._get_basic_line_dict_id_from_report_line_ref("account_reports.aged_receivable_line")
def test_aged_receivable_unfold_1_whole_report(self):
""" Test unfolding a line when rendering the whole report. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
partner_a_line_id = self.report._get_generic_line_id('res.partner', self.partner_a.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
options['unfolded_lines'] = [partner_a_line_id]
# Sort by Invoice Date
options['order_column'] = {
'expression_label': 'invoice_date',
'direction': 'ASC',
}
report_lines = self.report._get_lines(options)
sorted_report_lines = self.report._sort_lines(report_lines, options)
self.assertLinesValues(
# pylint: disable=C0326
sorted_report_lines,
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('INV/2016/00002', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
# Sort 61 - 90 decreasing.
options['order_column'] = {
'expression_label': 'period3',
'direction': 'DESC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(sorted_report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00002', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
# Sort 61 - 90 increasing.
options['order_column'] = {
'expression_label': 'period3',
'direction': 'ASC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(sorted_report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00002', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
def test_aged_receivable_unfold_all(self):
default_options = {
'unfold_all': True,
'order_column': {
'expression_label': 'invoice_date',
'direction': 'ASC',
}
}
options = self._generate_options(self.report, '2017-02-01', '2017-02-01', default_options=default_options)
report_lines = self.report._get_lines(options)
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('INV/2016/00002', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('INV/2016/00002', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options
)
def test_aged_receivable_unfold_all_with_integer_rounding(self):
""" Test unfolding a line when rendering the whole report with integer rounding. """
self.report.integer_rounding = 'HALF-UP'
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
partner_a_line_id = self.report._get_generic_line_id('res.partner', self.partner_a.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
options['unfolded_lines'] = [partner_a_line_id]
report_lines = self.report._get_lines(options)
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('INV/2016/00002', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options
)
def test_aged_receivable_unknown_partner(self):
""" Test that journal items without a partner in the receivable account appear as unknown partner. """
misc_move = self.env['account.move'].create({
'date': '2017-03-31',
'line_ids': [
Command.create({'debit': 1000.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id}),
Command.create({'debit': 0.0, 'credit': 1000.0, 'account_id': self.company_data['default_account_receivable'].id}),
],
})
misc_move.action_post()
options = self._generate_options(self.report, '2017-03-01', '2017-04-01')
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 0.0, -1000.0, 150.0, 150.0, 150.0, 1500.0, 950.0),
('partner_a', 0.0, 0.0, 100.0, 100.0, 100.0, 1000.0, 1300.0),
('partner_b', 0.0, 0.0, 50.0, 50.0, 50.0, 500.0, 650.0),
('Unknown', 0.0, -1000.0, 0.0, 0.0, 0.0, 0.0, -1000.0),
],
options,
)
def test_aged_receivable_filter_partners(self):
""" Test the filter on top allowing to filter on res.partner. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
options['partner_ids'] = self.partner_a.ids
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
],
options,
)
def test_aged_receivable_filter_partner_categories(self):
""" Test the filter on top allowing to filter on res.partner.category. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
options['partner_categories'] = self.partner_category_a.ids
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
],
options,
)
def test_aged_receivable_reconciliation_date(self):
""" Check the values at a date before some reconciliations are done. """
options = self._generate_options(self.report, '2016-10-31', '2016-10-31')
options['recon_date'] = {'date_to': '2016-10-31'}
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', -133.33, 1466.67, 0.0, 0.0, 0.0, 133.33, 1466.67),
('partner_a', -100.00, 1100.00, 0.0, 0.0, 0.0, 100.00, 1100.00),
('partner_b', -33.33, 366.67, 0.0, 0.0, 0.0, 33.33, 366.67),
],
options,
)
# TODO: move these tests into a generic report test class
def test_aged_receivable_sort_lines_by_date(self):
""" Test the _sort_lines function using date as sort key. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
partner_a_line_id = self.report._get_generic_line_id('res.partner', self.partner_a.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
partner_b_line_id = self.report._get_generic_line_id('res.partner', self.partner_b.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
options['unfolded_lines'] = [partner_a_line_id, partner_b_line_id]
# Sort by Invoice Date increasing
options['order_column'] = {
'expression_label': 'invoice_date',
'direction': 'ASC',
}
report_lines = self.report._get_lines(options)
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Invoice Date Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 1, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', '', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', '', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('INV/2016/00002', '11/03/2016', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('Total partner_a', '', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', '', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('INV/2016/00001', '10/05/2016', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('INV/2016/00002', '11/03/2016', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('Total partner_b', '', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Receivable', '', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
# Sort by Invoice Date decreasing
options['order_column'] = {
'expression_label': 'invoice_date',
'direction': 'DESC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00002', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('INV/2016/00002', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
def test_aged_receivable_sort_lines_by_numeric_value(self):
""" Test the _sort_lines function using float as sort key. """
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
partner_a_line_id = self.report._get_generic_line_id('res.partner', self.partner_a.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
partner_b_line_id = self.report._get_generic_line_id('res.partner', self.partner_b.id, parent_line_id=self.parent_line_id, markup={'groupby': 'partner_id'})
options['unfolded_lines'] = [partner_a_line_id, partner_b_line_id]
# Sort by Not Due On increasing
options['order_column'] = {
'expression_label': 'period0',
'direction': 'ASC',
}
report_lines = self.report._get_lines(options)
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('INV/2016/00002', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('INV/2016/00001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00002', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('INV/2016/00001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
# Sort by Not Due On decreasing
options['order_column'] = {
'expression_label': 'period0',
'direction': 'DESC',
}
self.assertLinesValues(
# pylint: disable=C0326
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('INV/2016/00001', 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00002', 0.0, 0.0, 0.0, 500.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 200.0, 0.0, ''),
('INV/2016/00001', 0.0, 100.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, ''),
('Total partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('INV/2016/00001', 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00002', 0.0, 0.0, 0.0, 250.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 100.0, 0.0, ''),
('INV/2016/00001', 0.0, 50.0, 0.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 50.0, 0.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 50.0, 0.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 50.0, 0.0, ''),
('INV/2016/00001', 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, ''),
('Total partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options,
)
def test_aged_receivable_zero_balanced_without_reconciliation(self):
options = self._generate_options(self.report, '2010-01-01', '2010-01-01', default_options={'unfold_all': True})
options['recon_date'] = {'date_to': '2010-01-01'}
invoice = self.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'invoice_date': '2010-01-01',
'invoice_date_due': '2010-01-01',
'payment_reference': 'I',
'invoice_line_ids': [Command.create({
'name': 'test invoice',
'price_unit': 100,
'tax_ids': [],
})]
})
invoice.action_post()
refund = self.env['account.move'].create({
'move_type': 'out_refund',
'partner_id': self.partner_a.id,
'invoice_date': '2010-01-01',
'invoice_date_due': '2010-01-01',
'payment_reference': 'R',
'invoice_line_ids': [Command.create({
'name': 'test refund',
'price_unit': 100,
'tax_ids': [],
})]
})
refund.action_post()
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(f"{refund.name} R", -100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
(f"{invoice.name} I", 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('Total Aged Receivable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
],
options,
)
# It should still work if both invoice and refund are partially reconciled with the same amount
self.env['account.payment.register'].with_context(active_ids=invoice.ids, active_model='account.move').create({
'amount': 42,
'payment_date': '2010-01-01',
'payment_method_line_id': self.outbound_payment_method_line.id,
})._create_payments()
self.env['account.payment.register'].with_context(active_ids=refund.ids, active_model='account.move').create({
'amount': 42,
'payment_date': '2010-01-01',
'payment_method_line_id': self.outbound_payment_method_line.id,
})._create_payments()
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(f"{refund.name} R", -58.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
(f"{invoice.name} I", 58.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('Total Aged Receivable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
],
options,
)
# It should still work if both invoice and refund are fully reconciled in the future
self.env['account.payment.register'].with_context(active_ids=invoice.ids, active_model='account.move').create({
'amount': 58,
'payment_date': '2020-01-01',
'payment_method_line_id': self.outbound_payment_method_line.id,
})._create_payments()
self.env['account.payment.register'].with_context(active_ids=refund.ids, active_model='account.move').create({
'amount': 58,
'payment_date': '2020-01-01',
'payment_method_line_id': self.outbound_payment_method_line.id,
})._create_payments()
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name Not Due On 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(f"{refund.name} R", -58.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
(f"{invoice.name} I", 58.0, 0.0, 0.0, 0.0, 0.0, 0.0, ''),
('Total partner_a', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('Total Aged Receivable', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
],
options,
)
def test_aged_receivable_partial_reconcile_currency(self):
""" Check that 'Amount Currency' column values are displayed and computed correctly. """
foreign_partner = self.env['res.partner'].create({'name': 'foreign_partner'})
currency = self.other_currency
currency.active = True
self.env.company.totals_below_sections = False
invoice = self.env['account.move'].create({
'move_type': 'out_invoice',
'invoice_date': '2023-05-01',
'invoice_date_due': '2023-05-01',
'partner_id': foreign_partner.id,
'currency_id': currency.id,
'invoice_line_ids': [Command.create({
'name': 'test',
'quantity': 1,
'price_unit': 100.0,
'tax_ids': [],
})],
})
invoice.action_post()
self.env['account.payment.register'].with_context(
active_model='account.move',
active_ids=invoice.ids,
).create({
'amount': 10.0,
'currency_id': currency.id,
'payment_date': '2023-05-05',
'partner_id': foreign_partner.id,
})._create_payments()
line_id = self.report._get_generic_line_id('res.partner', foreign_partner.id, markup={'groupby': 'partner_id'}, parent_line_id=self.parent_line_id)
options = self._generate_options(self.report, '2023-01-01', '2023-05-01')
options['unfolded_lines'] = [line_id]
options['recon_date'] = {'date_to': '2023-05-01'}
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_unfolded_lines(self.report._get_lines(options), line_id),
# Name Due Date Amount Currency Currency As Of Total
[ 0, 1, 2, 3, 5, 11],
[
('foreign_partner', '', '', '', 50.0, 50.0),
('INV/2023/00001', '05/01/2023', 100.0, 'CAD', 50.0, ''),
],
options,
currency_map={
2: {'currency': currency},
},
)
new_options = self._generate_options(self.report, '2023-01-01', '2023-05-05')
new_options['unfolded_lines'] = [line_id]
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_unfolded_lines(self.report._get_lines(new_options), line_id),
# Name Due Date Amount Currency Currency As Of 1-30 Total
[ 0, 1, 2, 3, 5, 6, 11],
[
('foreign_partner', '', '', '', 0.0, 45.0, 45.0),
('INV/2023/00001', '05/01/2023', 90.0, 'CAD', 0.0, 45.0, ''),
],
options,
currency_map={
2: {'currency': currency},
},
)
def test_aged_receivable_aging_interval(self):
options = self._generate_options(self.report, '2017-02-01', '2017-02-01')
initial_report_lines = self.report._get_lines(options)
# With the default interval of 30
self.assertLinesValues(
self.report._sort_lines(initial_report_lines, options),
# Name Not Due On 1 - 30 31 - 60 62 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
('partner_a', 100.0, 100.0, 100.0, 600.0, 300.0, 100.0, 1300.0),
('partner_b', 50.0, 50.0, 50.0, 300.0, 150.0, 50.0, 650.0),
('Total Aged Receivable', 150.0, 150.0, 150.0, 900.0, 450.0, 150.0, 1950.0),
],
options
)
options['aging_interval'] = 60
report_lines = self.report._get_lines(options)
# With the interval of 60
self.assertLinesValues(
self.report._sort_lines(report_lines, options),
# Name Not Due On 1 - 60 61 - 120 121 - 180 181 - 240 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9],
[
('Aged Receivable', 150.0, 300.0, 1350.0, 0.0, 0.0, 150.0, 1950.0),
('partner_a', 100.0, 200.0, 900.0, 0.0, 0.0, 100.0, 1300.0),
('partner_b', 50.0, 100.0, 450.0, 0.0, 0.0, 50.0, 650.0),
('Total Aged Receivable', 150.0, 300.0, 1350.0, 0.0, 0.0, 150.0, 1950.0),
],
options
)
def test_aged_receivable_horizontal_groups(self):
horizontal_group = self.env['account.report.horizontal.group'].create({
'name': 'Horizontal Group total',
'rule_ids': [
Command.create({
'field_name': 'company_id',
'domain': f"[('id', 'in', {(self.company_data['company'] + self.company_data_2['company']).ids})]",
}),
],
'report_ids': self.report
})
options = self._generate_options(self.report, '2017-03-01', '2017-04-01', default_options={'selected_horizontal_group_id': horizontal_group.id})
self.env.company.totals_below_sections = False
self.assertLinesValues(
# pylint: disable=C0326
self.report._get_lines(options),
# Name At Date 1 - 30 31 - 60 61 - 90 91 - 120 Older Total At Date 1 - 30 31 - 60 61 - 90 91 - 120 Older Total
[ 0, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16, 17, 18],
[
('Aged Receivable', 0.0, 0.0, 100.0, 100.0, 100.0, 1000.0, 1300.0, 0.0, 0.0, 50.0, 50.0, 50.0, 500.0, 650.0),
('partner_a', 0.0, 0.0, 100.0, 100.0, 100.0, 1000.0, 1300.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
('partner_b', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 50.0, 50.0, 50.0, 500.0, 650.0),
],
options,
)

View File

@@ -0,0 +1,177 @@
# -*- coding: utf-8 -*-
import json
from collections import defaultdict
from unittest.mock import patch
from odoo.tests.common import tagged
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
@tagged('post_install_l10n', 'post_install', '-at_install')
class TestAllReportsGeneration(AccountTestInvoicingCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
# do not disable buttons because of multiple companies selected
cls.env = cls.env(context={'allowed_company_ids': cls.env.company.ids})
cls.setup_other_currency('EUR')
cls.reports = cls.env['account.report'].with_context(active_test=False).search([])
# Make the reports always available, so that they don't clash with the company's country
cls.reports.availability_condition = 'always'
# We keep the country set on each of these reports, so that we can load the proper test data when testing exports
def test_open_all_reports(self):
# 'unfold_all' is forced on all reports (even if they don't support it), so that we really open it entirely
self.reports.filter_unfold_all = True
for report in self.reports:
with self.subTest(report=report.name, country=report.country_id.name):
# 'report_id' key is forced so that we don't open a variant when calling a root report
options = report.get_options({'selected_variant_id': report.id, 'unfold_all': True})
if report.use_sections:
self.assertNotEqual(options['report_id'], report.id, "Composite reports should always reroute.")
self.env['account.report'].browse(options['report_id']).get_report_information(options)
else:
report.get_report_information(options)
def test_generate_all_export_files(self):
# Test values for the fields that become mandatory when doing exports on the reports, depending on the country
l10n_pl_reports_tax_office = self.env.ref('l10n_pl.pl_tax_office_0215', raise_if_not_found=False)
l10n_bd_corporate_tax_liability = self.env['account.account'].search([('account_type', '=', 'liability_current')], limit=1)
l10n_ae_liability_account = self.env['account.account'].search([('account_type', '=', 'liability_current')], limit=1)
l10n_cz_reports_tax_office = self.env.ref('l10n_cz.tax_office_1', raise_if_not_found=False)
l10n_ar_activity_default = self.env.ref('l10n_ar.activity_620100', raise_if_not_found=False)
company_test_values = {
'AE': {'l10n_ae_tax_report_liabilities_account': l10n_ae_liability_account, 'l10n_ae_tax_report_expenses_account': l10n_ae_liability_account, 'l10n_ae_tax_report_asset_account': l10n_ae_liability_account},
'AR': {'vat': '30714295698', 'l10n_ar_arca_activity_id': l10n_ar_activity_default and l10n_ar_activity_default.id},
'AU': {'vat': '11225459588', 'street': 'Arrow Street', 'zip': '1348', 'city': 'Starling City', 'state_id': self.env.ref('base.state_au_1').id},
'BD': {'l10n_bd_corporate_tax_liability': l10n_bd_corporate_tax_liability, 'l10n_bd_corporate_tax_expense': l10n_bd_corporate_tax_liability},
'BR': {'vat': '01234567891251'},
'CZ': {'l10n_cz_tax_office_id': l10n_cz_reports_tax_office and l10n_cz_reports_tax_office.id},
'DE': {'vat': 'DE123456788', 'l10n_de_stnr': '151/815/08156', 'state_id': self.env.ref('base.state_de_th').id},
'DK': {'additional_identifiers': {'DK_CVR': '58403288'}},
'EE': {'additional_identifiers': {'EE_EN': '12345678'}},
'FI': {'additional_identifiers': {'FI_EN': '8763054-9'}},
'FR': {'street': 'Arrow Street', 'zip': '1348', 'city': 'Starling City'},
'LU': {'vat': 'LU12345613'},
'NO': {'vat': 'NO123456785', 'l10n_no_bronnoysund_number': '987654325'},
'PL': {
'vat': 'PL1234567883',
'l10n_pl_reports_tax_office_id': l10n_pl_reports_tax_office and l10n_pl_reports_tax_office.id,
},
'SK': {'zip': '010 01', 'city': 'Žilina', 'income_tax_id': '9999999999', 'l10n_sk_nace_code': '01110'},
}
# ecdf_prefix and matr_number only exist in enterprise
if self.env['ir.module.module']._get('l10n_lu_reports').state == 'installed':
company_test_values['LU'].update({
'ecdf_prefix': '1234AB',
'matr_number': '1111111111111',
})
# Some root reports are made for just one country and require test fields to be set the right way to generate their exports properly.
# Since they are root reports and are always available, they normally have no country set; we assign one here (only for the ones requiring it)
reports_forced_countries = [
('AU', 'l10n_au_reports.tpar_report'),
('FR', 'l10n_fr_reports.fiscal_declaration'),
]
for country_code, report_ref in reports_forced_countries:
country = self.env['res.country'].search([('code', '=', country_code)], limit=1)
report = self.env.ref(report_ref, raise_if_not_found=False)
if report:
report.country_id = country
# Check buttons of every report
for report in self.reports:
with self.subTest(report=report.name, country=report.country_id.name):
# Setup some generic data on the company that could be needed for some file export
self.env.company.write({
'vat': "VAT123456789",
'email': "dummy@email.com",
'phone': "01234567890",
**company_test_values.get(report.country_id.code, {}),
})
options = report.get_options({'selected_variant_id': report.id, '_running_export_test': True})
if report.use_sections:
self.assertNotEqual(options['report_id'], report.id, "Composite reports should always reroute.")
for option_button in options['buttons']:
if option_button['name'] in ('Print', 'Download Excel'): # keep "Copy to Documents" and other actions
# TODO remove me
# This test seems to have some trouble on runbot. It is running for way longer than
# locally. Freeze is coming, explanation are missing... Sorry 😟
continue
if report.custom_handler_model_name == 'l10n_fr.report.handler' and option_button['name'] == 'EDI VAT':
# This button requires a tax closing entry to be called. It doesn't make sense to test this button
# without a tax closing entry, so we will exclude it from testing here.
continue
with self.subTest(button=option_button['name']):
with self.allow_pdf_render():
if not option_button.get('client_tag'):
action_dict = report.dispatch_report_action(
options,
option_button['action'],
action_param=option_button.get('action_param'),
on_sections_source=True,
)
if action_dict['type'] == 'ir_actions_account_report_download':
file_gen_res = report.dispatch_report_action(
json.loads(action_dict['data']['options']),
action_dict['data']['file_generator'],
on_sections_source=True,
)
self.assertEqual(
set(file_gen_res.keys()), {'file_name', 'file_content', 'file_type'},
"File generator's result should always contain the same 3 keys."
)
# Unset the test values, in case they are used in conditions to define custom behaviors
self.env.company.write({
field_name: None
for field_name in company_test_values.get(report.country_id.code, {}).keys()
})
def test_custom_engines_related_groupby(self):
blacklist_xmlids = [
'account_reports.account_financial_report_executivesummary_avdebt0_ndays',
'account_reports.account_financial_report_executivesummary_avgcre0_ndays',
'account_reports.last_statement_balance_amount',
'account_reports.last_statement_balance_forced_currency_amount',
]
custom_engine_expressions = self.env['account.report.expression'].search([
('engine', '=', 'custom'),
('id', 'not in', tuple(self.env['ir.model.data']._xmlid_to_res_id(xmlid) for xmlid in blacklist_xmlids)),
('report_line_id.children_ids', '=', False),
])
expressions_per_engine = defaultdict(lambda: self.env['account.report.expression'])
for expression in custom_engine_expressions:
expressions_per_engine[(expression.report_line_id.report_id, expression.formula)] += expression
for (report, _formula), expressions in expressions_per_engine.items():
with self.subTest(report=report.name):
options = report.get_options({'no_report_reroute': True})
# Remove aggregations and external value expressions from those report lines, so that we always can set a groupby on the line
(expressions.report_line_id.expression_ids.filtered(lambda x: x.engine in ('aggregation', 'external'))).unlink()
# Set foldability to always unfolded for the lines to be unfolded by default
expressions.report_line_id.foldability = 'always_unfolded'
expressions.report_line_id.user_groupby = 'account_code' # account_code is a non-stored related field on aml
self.env.flush_all()
report._compute_expression_totals_for_each_column_group(expressions, options, groupby_to_expand='account_code')
# This computation will fail if the custom engine forgot to handle such groupby, typically via a call to _field_to_sql

View File

@@ -0,0 +1,549 @@
from odoo import Command
from odoo.tests import tagged
from .common import TestAccountReportsCommon
@tagged('post_install', '-at_install')
class TestAnalyticReport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env.user.group_ids += cls.env.ref(
'analytic.group_analytic_accounting')
cls.report = cls.env.ref('account_reports.profit_and_loss')
cls.analytic_plan_parent = cls.env['account.analytic.plan'].create({
'name': 'Plan Parent',
})
cls.analytic_plan_child = cls.env['account.analytic.plan'].create({
'name': 'Plan Child',
'parent_id': cls.analytic_plan_parent.id,
})
cls.analytic_account_parent = cls.env['account.analytic.account'].create({
'name': 'Account 1',
'plan_id': cls.analytic_plan_parent.id
})
cls.analytic_account_parent_2 = cls.env['account.analytic.account'].create({
'name': 'Account 2',
'plan_id': cls.analytic_plan_parent.id
})
cls.analytic_account_child = cls.env['account.analytic.account'].create({
'name': 'Account 3',
'plan_id': cls.analytic_plan_child.id
})
cls.analytic_account_parent_3 = cls.env['account.analytic.account'].create({
'name': 'Account 4',
'plan_id': cls.analytic_plan_parent.id
})
def test_report_group_by_analytic_plan(self):
out_invoice = self.env['account.move'].create([{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '2019-05-01',
'invoice_date': '2019-05-01',
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'price_unit': 200.0,
'analytic_distribution': {
self.analytic_account_parent.id: 100,
},
}),
Command.create({
'product_id': self.product_b.id,
'price_unit': 200.0,
'analytic_distribution': {
self.analytic_account_child.id: 100,
},
}),
]
}])
out_invoice.action_post()
options = self._generate_options(
self.report,
'2019-01-01',
'2019-12-31',
default_options={
'analytic_plans_groupby': [self.analytic_plan_parent.id, self.analytic_plan_child.id],
}
)
lines = self.report._get_lines(options)
self.assertLinesValues(
# pylint: disable=bad-whitespace
lines,
[ 0, 1, 2],
[
['Revenue', 400.00, 200.00],
['Costs of Revenue', 0.00, 0.00],
['Gross Profit', 400.00, 200.00],
['Operating Expenses', 0.00, 0.00],
['Operating Income (or Loss)', 400.00, 200.00],
['Other Income', 0.00, 0.00],
['Other Expenses', 0.00, 0.00],
['Net Profit', 400.00, 200.00],
['Allocations and Withdrawals', 0.00, 0.00],
],
options,
currency_map={
1: {'currency': self.env.company.currency_id},
2: {'currency': self.env.company.currency_id},
},
)
def test_audit_cell_analytic_groupby(self):
"""
Test that the analytic filters are applied on the auditing of the cells
"""
def _get_action_dict(options, column_index):
lines = self.report._get_lines(options)
report_line = self.report.line_ids[0]
report_line_dict = next(x for x in lines if x.name == report_line.name)
audit_param = self._get_audit_params_from_report_line(options, report_line, report_line_dict, column_group_index=options['columns'][column_index]['column_group_index'])
return self.report.action_audit_cell(options, audit_param)
other_plan = self.env['account.analytic.plan'].create({'name': "Other Plan"})
other_account = self.env['account.analytic.account'].create({'name': "Other Account", 'plan_id': other_plan.id, 'active': True})
out_invoices = self.env['account.move'].create([
{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '2023-02-01',
'invoice_date': '2023-02-01',
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'price_unit': 1000.0,
'analytic_distribution': {
self.analytic_account_parent.id: 40,
self.analytic_account_child.id: 60,
}
}),
]
},
{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '2023-02-01',
'invoice_date': '2023-02-01',
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'price_unit': 2000.0,
'analytic_distribution': {
f'{self.analytic_account_parent.id},{other_account.id}': 100,
},
}),
]
}
])
out_invoices.action_post()
out_invoices = out_invoices.with_context(analytic_plan_id=self.analytic_plan_parent.id)
analytic_lines_parent = out_invoices.invoice_line_ids.analytic_line_ids.filtered(lambda line: line.auto_account_id == self.analytic_account_parent)
analytic_lines_other = out_invoices.with_context(analytic_plan_id=other_plan.id).invoice_line_ids.analytic_line_ids.filtered(lambda line: line.auto_account_id == other_account)
# Test with only groupby
options = self._generate_options(
self.report,
'2023-01-01',
'2023-12-31',
default_options={
'analytic_accounts_groupby': [self.analytic_account_parent.id, other_account.id],
}
)
action_dict = _get_action_dict(options, 0) # First Column => Parent
self.assertEqual(
self.env['account.analytic.line'].search(action_dict['domain']),
analytic_lines_parent,
"Only the Analytic Line related to the Parent should be shown",
)
action_dict = _get_action_dict(options, 1) # Second Column => Other
self.assertEqual(
self.env['account.analytic.line'].search(action_dict['domain']),
analytic_lines_other,
"Only the Analytic Line related to the Parent should be shown",
)
action_dict = _get_action_dict(options, 2) # Third Column => AMLs
self.assertEqual(
out_invoices.line_ids.filtered_domain(action_dict['domain']),
out_invoices.invoice_line_ids,
"Both amls should be shown",
)
def test_general_ledger_with_analytic_group_by(self):
analytic_plan = self.env["account.analytic.plan"].create({
"name": "Default Plan",
})
analytic_account = self.env["account.analytic.account"].create({
"name": "Test Account",
"plan_id": analytic_plan.id,
})
invoice = self.init_invoice(
"out_invoice",
amounts=[100, 200],
invoice_date="2023-01-01",
)
invoice.action_post()
invoice.invoice_line_ids[0].analytic_distribution = {analytic_account.id: 100}
general_ledger_report = self.env.ref("account_reports.general_ledger_report")
general_ledger_report.filter_analytic_groupby = True
options = self._generate_options(
general_ledger_report,
"2023-01-01",
"2023-01-01",
default_options={
'unfold_all': True,
'analytic_accounts_groupby': [analytic_account.id],
}
)
self.assertLinesValues(
general_ledger_report._get_lines(options),
# [ Analytic account ]|[ Total ]
# Name Debit Credit Balance | Debit Credit Balance
[ 0, 4, 5, 6, 10, 11, 12],
[
['121000 Accounts Receivable', 0.00, 0.00, 0.00, 300.00, 0.00, 300.00],
['INV/2023/00001', 0.00, 0.00, 0.00, 300.00, 0.00, 300.00],
['Total 121000 Accounts Receivable', 0.00, 0.00, 0.00, 300.00, 0.00, 300.00],
['400000 Product Sales', 0.00, 100.00, -100.00, 0.00, 300.00, -300.00],
['INV/2023/00001 test line', 0.00, 100.00, -100.00, 0.00, 100.00, -100.00],
['INV/2023/00001 test line', 0.00, 0.00, -100.00, 0.00, 200.00, -300.00],
['Total 400000 Product Sales', 0.00, 100.00, -100.00, 0.00, 300.00, -300.00],
['Total General Ledger', 0.00, 100.00, -100.00, 300.00, 300.00, 0.00],
],
options,
)
def test_analytic_groupby_with_horizontal_groupby(self):
out_invoice_1 = self.env['account.move'].create([{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '2024-07-01',
'invoice_date': '2024-07-01',
'invoice_line_ids': [
Command.create({
'product_id': self.product_b.id,
'price_unit': 500.0,
'analytic_distribution': {
self.analytic_account_parent_2.id: 80,
self.analytic_account_parent_3.id: -10,
},
}),
]
}])
out_invoice_1.action_post()
out_invoice_2 = self.env['account.move'].create([{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '2024-07-01',
'invoice_date': '2024-07-01',
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'price_unit': 100.0,
'analytic_distribution': {
self.analytic_account_parent.id: 100,
},
}),
]
}])
out_invoice_2.action_post()
horizontal_group = self.env['account.report.horizontal.group'].create({
'name': 'Horizontal Group Journal Entries',
'report_ids': [self.report.id],
'rule_ids': [
Command.create({
'field_name': 'move_id', # this field is specific to account.move.line and not in account.analytic.line
'domain': f"[('id', 'in', {(out_invoice_1 + out_invoice_2).ids})]",
}),
],
})
options = self._generate_options(
self.report,
'2024-01-01',
'2024-12-31',
default_options={
'analytic_accounts_groupby': [self.analytic_account_parent.id, self.analytic_account_parent_2.id, self.analytic_account_parent_3.id],
'selected_horizontal_group_id': horizontal_group.id,
}
)
self.assertLinesValues(
self.report._get_lines(options),
# Horizontal groupby [ Move 2 ] [ Move 1 ]
# Analytic groupby A1 A2 A3 Balance A1 A2 A3 Balance
[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[
['Revenue', 100.00, 0.00, 0.00, 100.00, 0.00, 400.00, -50.00, 500.00],
['Costs of Revenue', 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
['Gross Profit', 100.00, 0.00, 0.00, 100.00, 0.00, 400.00, -50.00, 500.00],
['Operating Expenses', 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
['Operating Income (or Loss)', 100.00, 0.00, 0.00, 100.00, 0.00, 400.00, -50.00, 500.00],
['Other Income', 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
['Other Expenses', 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
['Net Profit', 100.00, 0.00, 0.00, 100.00, 0.00, 400.00, -50.00, 500.00],
['Allocations and Withdrawals', 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00],
],
options,
)
def test_analytic_groupby_with_analytic_simulations(self):
"""
Create an analytic simulation (analytic line without a move line)
and check that it is taken into account in the report
"""
self.env['account.analytic.line'].create({
'name': 'Simulation',
'date': '2019-05-01',
'amount': 100.0,
'unit_amount': 1.0,
'company_id': self.env.company.id,
self.analytic_plan_parent._column_name(): self.analytic_account_parent.id,
'general_account_id': self.company_data['default_account_revenue'].id,
})
options = self._generate_options(
self.report,
'2019-01-01',
'2019-12-31',
default_options={
'analytic_plans_groupby': [self.analytic_plan_parent.id, self.analytic_plan_child.id],
'include_analytic_without_aml': True,
}
)
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1, 2],
[
('Revenue', 100.00, 0.00),
('Costs of Revenue', 0.00, 0.00),
('Gross Profit', 100.00, 0.00),
('Operating Expenses', 0.00, 0.00),
('Operating Income (or Loss)', 100.00, 0.00),
('Other Income', 0.00, 0.00),
('Other Expenses', 0.00, 0.00),
('Net Profit', 100.00, 0.00),
('Allocations and Withdrawals', 0.00, 0.00),
],
options,
)
def test_analytic_groupby_plans_without_analytic_accounts(self):
"""
Ensure that grouping on several analytic plans without any analytic accounts works as expected
"""
analytic_plans_without_accounts = self.env['account.analytic.plan'].create([
{'name': 'Plan 1'},
{'name': 'Plan 2'},
])
options = self._generate_options(
self.report, '2019-01-01', '2019-12-31',
default_options={'analytic_plans_groupby': analytic_plans_without_accounts.ids}
)
self.assertEqual(
len(options['column_groups']), 3,
"the number of column groups should be 3, despite the 2 analytic plans having the exact same analytic accounts list"
)
self.assertLinesValues(
self.report._get_lines(options),
# Plan 1 Plan 2 Total
[ 0, 1, 2, 3],
[
('Revenue', 0.00, 0.00, 0.00),
('Costs of Revenue', 0.00, 0.00, 0.00),
('Gross Profit', 0.00, 0.00, 0.00),
('Operating Expenses', 0.00, 0.00, 0.00),
('Operating Income (or Loss)', 0.00, 0.00, 0.00),
('Other Income', 0.00, 0.00, 0.00),
('Other Expenses', 0.00, 0.00, 0.00),
('Net Profit', 0.00, 0.00, 0.00),
('Allocations and Withdrawals', 0.00, 0.00, 0.00),
],
options,
)
def test_profit_and_loss_multicompany_access_rights(self):
branch = self.env['res.company'].create([{
'name': "My Test Branch",
'parent_id': self.env.company.id,
}])
other_currency = self.setup_other_currency('EUR', rounding=0.001)
test_journal = self.env['account.journal'].create({
'name': 'Test Journal',
'code': 'TEST',
'type': 'sale',
'company_id': self.env.company.id,
'currency_id': other_currency.id,
})
test_user = self.env['res.users'].create({
'login': 'test',
'name': 'The King',
'email': 'noop@example.com',
'group_ids': [Command.link(self.env.ref('account.group_account_manager').id)],
'company_ids': [Command.link(self.env.company.id), Command.link(branch.id)],
})
self.env.invalidate_all()
options = self._generate_options(
self.report.with_user(test_user).with_company(branch), '2019-01-01', '2019-12-31',
)
lines = self.report._get_lines(options)
self.assertTrue(lines)
self.assertEqual(test_journal.display_name, "Test Journal (EUR)")
def test_show_analytic_coverage_column(self):
"""
Ensures that the column of analytic coverage only appears when only one plan is shown
"""
options = self._generate_options(
self.report,
'2019-01-01',
'2019-12-31',
)
self.assertIsNone(options.get('column_percent_comparison'))
options = self._generate_options(
self.report,
'2019-01-01',
'2019-12-31',
default_options={
'analytic_plans_groupby': [self.analytic_plan_child.id],
}
)
self.assertEqual(options.get('column_percent_comparison'), 'analytic_coverage')
options = self._generate_options(
self.report,
'2019-01-01',
'2019-12-31',
default_options={
'analytic_plans_groupby': [self.analytic_plan_parent, self.analytic_plan_child.id],
}
)
self.assertIsNone(options.get('column_percent_comparison'))
options = self._generate_options(
self.report,
'2019-01-01',
'2019-12-31',
default_options={
'analytic_accounts_groupby': [self.analytic_account_parent.id],
}
)
self.assertIsNone(options.get('column_percent_comparison'))
options = self._generate_options(
self.report,
'2019-01-01',
'2019-12-31',
default_options={
'analytic_accounts_groupby': [self.analytic_account_parent.id],
'analytic_plans_groupby': [self.analytic_plan_child.id],
}
)
self.assertIsNone(options.get('column_percent_comparison'))
def test_audit_analytic_lines(self):
def _get_action_dict(options, column_index):
lines = self.report._get_lines(options)
report_line = self.report.line_ids[0]
report_line_dict = next(x for x in lines if x.name == report_line.name)
audit_param = self._get_audit_params_from_report_line(options, report_line, report_line_dict, column_group_index=options['columns'][column_index]['column_group_index'])
return self.report.action_audit_cell(options, audit_param)
other_plan = self.env['account.analytic.plan'].create({'name': "Other Plan"})
other_account = self.env['account.analytic.account'].create({'name': "Other Account", 'plan_id': other_plan.id, 'active': True})
parent_invoice = self.env['account.move'].create([{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '2019-05-01',
'invoice_date': '2019-05-01',
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'price_unit': 200.0,
'analytic_distribution': {
self.analytic_account_parent.id: 50,
self.analytic_account_parent_2.id: 40,
},
}),
Command.create({
'product_id': self.product_b.id,
'price_unit': 200.0,
'analytic_distribution': {
self.analytic_account_parent.id: 100,
},
}),
]
},
])
parent_invoice.action_post()
other_invoice = self.env['account.move'].create([{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '2019-05-01',
'invoice_date': '2019-05-01',
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'price_unit': 200.0,
'analytic_distribution': {
other_account.id: 100,
},
}),
]
}])
other_invoice.action_post()
options = self._generate_options(
self.report,
'2019-01-01',
'2019-12-31',
default_options={
'analytic_plans_groupby': [self.analytic_plan_parent.id],
}
)
analytic_lines = parent_invoice.invoice_line_ids.analytic_line_ids + other_invoice.invoice_line_ids.analytic_line_ids
action_dict = _get_action_dict(options, 0) # First column: analytic lines of parent plan
self.assertEqual(action_dict['context'].get('group_by'), 'move_line_id')
self.assertEqual(
self.env['account.analytic.line'].with_context(action_dict['context']).search(action_dict['domain']),
analytic_lines,
)
action_dict = _get_action_dict(options, 1) # Second column: account move lines
move_lines = self.env['account.move.line'].with_context(action_dict['context']).search(action_dict['domain'])
move_line_parent_product_a = move_lines.filtered(lambda line: line.move_id.id == parent_invoice.id and line.product_id == self.product_a)
move_line_parent_product_b = move_lines.filtered(lambda line: line.move_id.id == parent_invoice.id and line.product_id == self.product_b)
move_line_other = move_lines.filtered(lambda line: line.move_id.id == other_invoice.id)
self.assertEqual(move_line_parent_product_a.analytic_coverage, 0.9)
self.assertEqual(move_line_parent_product_b.analytic_coverage, 1.0)
self.assertEqual(move_line_other.analytic_coverage, 0.0)

View File

@@ -0,0 +1,855 @@
# pylint: disable=C0326
import logging
import itertools
import contextlib
from odoo import fields
from odoo.tests import TransactionCase
from odoo.addons.account.models.chart_template import SYSCOHADA_LIST
_logger = logging.getLogger(__name__)
syscohada_coas = [country_code.lower() for country_code in SYSCOHADA_LIST]
syscebnl_coas = [f'{country_code.lower}_syscebnl' for country_code in SYSCOHADA_LIST]
# === Set this variable to something truthy if you want the test to identify any incorrectly-referenced accounts for you. === #
IDENTIFY_INCORRECT_ACCOUNTS = False
# === Set this to True (if the above is set to True) if you want the test to show you journal entries for reproducing the imbalance === #
EXTRA_DETAIL = False
# === When creating a new Balance Sheet, please add its config here. === #
''' Example config:
REPORT_CONFIG = {
<Balance Sheet report xmlid> : {
'asset_line_ref': <Total Assets line xmlid>
'liability_line_ref': <Total Liabilities line xmlid>
'equity_line_ref': (optional) <Total Equity line xmlid> (if not included in Liabilities)
'balance_col_label': (optional) <expression_label of the report column containing the totals> (if different from 'balance')
'chart_template_refs': (optional) <list of CoAs for which the report should be tested (by default any CoA on which the report is available)>
},
} '''
REPORT_CONFIG = {
'account_reports.balance_sheet': {
'asset_line_ref': 'account_reports.account_financial_report_total_assets0',
'liability_line_ref': 'account_reports.account_financial_report_liabilities_and_equity_view0',
},
'l10n_at_reports.account_financial_report_l10n_at_paragraph_224_ugb': {
'asset_line_ref': 'l10n_at_reports.account_financial_report_l10n_at_paragraph_224_ugb_line_activa',
'liability_line_ref': 'l10n_at_reports.account_financial_report_l10n_at_paragraph_224_ugb_line_passiva',
},
'l10n_be_reports.account_financial_report_bs_asso_a': {
'asset_line_ref': 'l10n_be_reports.account_financial_report_bs_asso_a_a_tot',
'liability_line_ref': 'l10n_be_reports.account_financial_report_bs_asso_a_el_tot',
},
'l10n_be_reports.account_financial_report_bs_asso_f': {
'asset_line_ref': 'l10n_be_reports.account_financial_report_bs_asso_f_a_tot',
'liability_line_ref': 'l10n_be_reports.account_financial_report_bs_asso_f_el_tot',
},
'l10n_be_reports.account_financial_report_bs_comp_acap': {
'asset_line_ref': 'l10n_be_reports.account_financial_report_bs_comp_acap_a_tot',
'liability_line_ref': 'l10n_be_reports.account_financial_report_bs_comp_acap_el_tot',
},
'l10n_be_reports.account_financial_report_bs_comp_acon': {
'asset_line_ref': 'l10n_be_reports.account_financial_report_bs_comp_acon_a_tot',
'liability_line_ref': 'l10n_be_reports.account_financial_report_bs_comp_acon_el_tot',
},
'l10n_be_reports.account_financial_report_bs_comp_fcap': {
'asset_line_ref': 'l10n_be_reports.account_financial_report_bs_comp_fcap_a_tot',
'liability_line_ref': 'l10n_be_reports.account_financial_report_bs_comp_fcap_el_tot',
},
'l10n_be_reports.account_financial_report_bs_comp_fcon': {
'asset_line_ref': 'l10n_be_reports.account_financial_report_bs_comp_fcon_a_tot',
'liability_line_ref': 'l10n_be_reports.account_financial_report_bs_comp_fcon_el_tot',
},
'l10n_bg_reports.l10n_bg_bs': {
'asset_line_ref': 'l10n_bg_reports.l10n_bg_bs_assets',
'liability_line_ref': 'l10n_bg_reports.l10n_bg_bs_liabilities',
},
'l10n_bo_reports.l10n_bo_bs': {
'asset_line_ref': 'l10n_bo_reports.l10n_bo_bs_assets',
'liability_line_ref': 'l10n_bo_reports.l10n_bo_bs_liabilities_plus_equity',
},
'l10n_br_reports.account_financial_report_br_balancesheet0': {
'asset_line_ref': 'l10n_br_reports.account_financial_report_total_assets0',
'liability_line_ref': 'l10n_br_reports.account_financial_report_liabilities_view0',
},
'l10n_ca_reports.l10n_ca_balance_sheet': {
'asset_line_ref': 'l10n_ca_reports.assets',
'liability_line_ref': 'l10n_ca_reports.liabilities_equity',
},
'l10n_ch_reports.account_financial_report_l10n_ch_bilan': {
'asset_line_ref': 'l10n_ch_reports.account_financial_report_line_ch_1',
'liability_line_ref': 'l10n_ch_reports.account_financial_report_line_ch_2',
},
'l10n_cl_reports.cl_eightcolumns_report': {
'chart_template_refs': [],
},
'l10n_co_reports.l10n_co_bs_report': {
'asset_line_ref': 'l10n_co_reports.l10n_co_bs_report_assets',
'liability_line_ref': 'l10n_co_reports.l10n_co_bs_report_liabilities_equity',
},
'l10n_co_reports.l10n_co_reports_libro_inv_blc': {
'asset_line_ref': 'l10n_co_reports.l10n_co_inv_blc_assets_expenses',
'liability_line_ref': 'l10n_co_reports.l10n_co_inv_blc_equity_liability',
},
'l10n_cy_reports.l10n_cy_balance_sheet': {
'asset_line_ref': 'l10n_cy_reports.account_financial_report_cy_active_line',
'liability_line_ref': 'l10n_cy_reports.account_financial_report_cy_passive_line',
},
'l10n_cz_reports.balance_sheet_l10n_cz_reports': {
'asset_line_ref': 'l10n_cz_reports.l10n_cz_reports_bs_aktiva',
'liability_line_ref': 'l10n_cz_reports.l10n_cz_reports_bs_pasiva',
'balance_col_label': 'net',
},
'l10n_de_reports.balance_sheet_l10n_de': {
'asset_line_ref': 'l10n_de_reports.skr_asset_total',
'liability_line_ref': 'l10n_de_reports.skr_liabilities_total',
},
'l10n_dk_reports.account_report_bs': {
'asset_line_ref': 'l10n_dk_reports.account_report_bs_a',
'liability_line_ref': 'l10n_dk_reports.account_report_bs_el',
},
'l10n_do_reports.l10n_do_bs': {
'asset_line_ref': 'l10n_do_reports.l10n_do_bs_assets',
'liability_line_ref': 'l10n_do_reports.l10n_do_bs_liabilities_plus_equity',
},
'l10n_dz_reports.l10n_dz_bs': {
'asset_line_ref': 'l10n_dz_reports.l10n_dz_bs_assets',
'liability_line_ref': 'l10n_dz_reports.l10n_dz_bs_liabilities',
'balance_col_label': 'net',
},
'l10n_ec_reports.l10n_ec_balance_sheet': {
'asset_line_ref': 'l10n_ec_reports.l10n_ec_balance_sheet_assets',
'liability_line_ref': 'l10n_ec_reports.l10n_ec_balance_sheet_liabilities_and_equity',
},
'l10n_ee_reports.account_financial_report_bs': {
'asset_line_ref': 'l10n_ee_reports.account_financial_report_bs_assets',
'liability_line_ref': 'l10n_ee_reports.account_financial_report_bs_liabilities_equity',
},
'l10n_es_reports.financial_report_balance_sheet_assoc': {
'asset_line_ref': 'l10n_es_reports.balance_assoc_line_10000',
'liability_line_ref': 'l10n_es_reports.balance_assoc_line_30000',
},
'l10n_es_reports.financial_report_balance_sheet_full': {
'asset_line_ref': 'l10n_es_reports.balance_full_line_10000',
'liability_line_ref': 'l10n_es_reports.balance_full_line_30000',
},
'l10n_es_reports.financial_report_balance_sheet_pymes': {
'asset_line_ref': 'l10n_es_reports.balance_pymes_line_10000',
'liability_line_ref': 'l10n_es_reports.balance_pymes_line_30000',
},
'l10n_es_reports.financial_report_balance_sheet_abbreviated': {
'asset_line_ref': 'l10n_es_reports.balance_abbreviated_line_10000',
'liability_line_ref': 'l10n_es_reports.balance_abbreviated_line_30000',
},
'l10n_fi_reports.account_financial_report_l10n_fi_bs': {
'asset_line_ref': 'l10n_fi_reports.account_financial_report_l10n_fi_bs_line_1',
'liability_line_ref': 'l10n_fi_reports.account_financial_report_l10n_fi_bs_line_2',
},
'l10n_fr_reports.account_financial_report_l10n_fr_bilan': {
'asset_line_ref': 'l10n_fr_reports.account_financial_report_fr_bilan_actif_total',
'liability_line_ref': 'l10n_fr_reports.account_financial_report_fr_bilan_passif_total',
'balance_col_label': 'net',
},
'l10n_fr_reports.account_financial_report_l10n_fr_bilan_asso': {
'asset_line_ref': 'l10n_fr_reports.account_financial_report_fr_bilan_actif_total_asso',
'liability_line_ref': 'l10n_fr_reports.account_financial_report_fr_bilan_passif_total_asso',
'balance_col_label': 'net',
},
'l10n_fr_reports.account_financial_report_l10n_fr_bilan_2024': {
'asset_line_ref': 'l10n_fr_reports.account_financial_report_fr_bilan_actif_total_2024',
'liability_line_ref': 'l10n_fr_reports.account_financial_report_fr_bilan_passif_total_2024',
'balance_col_label': 'net',
},
'l10n_fr_reports.l10n_fr_2033_A': {
'asset_line_ref': 'l10n_fr_reports.l10n_fr_2033_A_actif_total',
'liability_line_ref': 'l10n_fr_reports.l10n_fr_2033_A_passif_total',
'balance_col_label': 'net_round',
},
'l10n_gr_reports.l10n_gr_bs_accounting_report': {
'asset_line_ref': 'l10n_gr_reports.l10n_gr_bs_assets',
'liability_line_ref': 'l10n_gr_reports.l10n_gr_bs_equity_provisions_liabilities',
},
'l10n_hk_reports.account_financial_report_hk_bs': {
'asset_line_ref': 'l10n_hk_reports.account_financial_report_hk_bs_assets',
'liability_line_ref': 'l10n_hk_reports.account_financial_report_hk_bs_liabilities',
'equity_line_ref': 'l10n_hk_reports.account_financial_report_hk_bs_equity_earnings',
},
'l10n_hr_reports.l10n_hr_balance_sheet': {
'asset_line_ref': 'l10n_hr_reports.account_financial_report_hr_active_title0',
'liability_line_ref': 'l10n_hr_reports.account_financial_report_hr_passif_title0',
'chart_template_refs': ['hr'], # don't test the hr_kuna CoA anymore (obsolete)
},
'l10n_hu_reports.l10n_hu_balance_sheet': {
'asset_line_ref': 'l10n_hu_reports.l10n_hu_balance_sheet_assets',
'liability_line_ref': 'l10n_hu_reports.l10n_hu_balance_sheet_liabilities',
},
'l10n_ie_reports.l10n_ie_bs': {
'asset_line_ref': 'l10n_ie_reports.l10n_ie_bs_assets_total',
'liability_line_ref': 'l10n_ie_reports.l10n_ie_bs_liabilities_total',
},
'l10n_ie_reports.l10n_ie_bs_tags': {
'asset_line_ref': 'l10n_ie_reports.l10n_ie_bs_tags_assets_total',
'liability_line_ref': 'l10n_ie_reports.l10n_ie_bs_tags_liabilities_total',
},
'l10n_it_reports.account_financial_report_it_sp': {
'asset_line_ref': 'l10n_it_reports.account_financial_report_line_it_sp_assets_total',
'liability_line_ref': 'l10n_it_reports.account_financial_report_line_it_sp_passif_total',
},
'l10n_it_reports.account_financial_report_it_sp_reduce': {
'asset_line_ref': 'l10n_it_reports.account_financial_report_line_it_sp_reduce_assets_total',
'liability_line_ref': 'l10n_it_reports.account_financial_report_line_it_sp_reduce_passif_total',
},
'l10n_jp_reports.account_financial_report_jp_bs': {
'asset_line_ref': 'l10n_jp_reports.account_financial_report_jp_bs_jp_assets',
'liability_line_ref': 'l10n_jp_reports.account_financial_report_jp_bs_jp_liabilities_and_equity',
},
'l10n_ke_reports.account_financial_report_ke_bs': {
'asset_line_ref': 'l10n_ke_reports.account_financial_report_ke_bs_A',
'liability_line_ref': 'l10n_ke_reports.account_financial_report_ke_bs_B',
},
'l10n_kh_reports.l10n_kh_balance_sheet': {
'asset_line_ref': 'l10n_kh_reports.l10n_kh_balance_sheet_kh_bs_a',
'liability_line_ref': 'l10n_kh_reports.l10n_kh_balance_sheet_kh_bs_el',
},
'l10n_kz_reports.l10n_kz_bl_report': {
'asset_line_ref': 'l10n_kz_reports.l10n_kz_bl_assets',
'liability_line_ref': 'l10n_kz_reports.l10n_kz_bl_equity_liabilities',
},
'l10n_lk_reports.l10n_lk_bs': {
'asset_line_ref': 'l10n_lk_reports.l10n_lk_bs_assets',
'liability_line_ref': 'l10n_lk_reports.l10n_lk_bs_liabilities',
'equity_line_ref': 'l10n_lk_reports.l10n_lk_bs_equity_earnings',
},
'l10n_lt_reports.account_financial_report_balancesheet_lt': {
'asset_line_ref': 'l10n_lt_reports.account_financial_html_report_line_bs_lt_debit',
'liability_line_ref': 'l10n_lt_reports.account_financial_html_report_line_bs_lt_credit',
},
'l10n_lu_reports.account_financial_report_l10n_lu_bs_abr': {
'asset_line_ref': 'l10n_lu_reports.account_financial_report_l10n_lu_bs_abr_line_1_6',
'liability_line_ref': 'l10n_lu_reports.account_financial_report_l10n_lu_bs_abr_line_2_5',
},
'l10n_lu_reports.account_financial_report_l10n_lu_bs': {
'asset_line_ref': 'l10n_lu_reports.account_financial_report_l10n_lu_bs_line_1_6',
'liability_line_ref': 'l10n_lu_reports.account_financial_report_l10n_lu_bs_line_2_5',
},
'l10n_lv_reports.l10n_lv_balance_sheet': {
'asset_line_ref': 'l10n_lv_reports.account_financial_report_lv_active_title',
'liability_line_ref': 'l10n_lv_reports.account_financial_report_lv_passif_title',
},
'l10n_ma_reports.account_financial_report_bs': {
'asset_line_ref': 'l10n_ma_reports.account_financial_report_bs_a_total',
'liability_line_ref': 'l10n_ma_reports.account_financial_report_bs_p_total',
'balance_col_label': 'net',
},
'l10n_mk_reports.balance_sheet_l10n_mk': {
'asset_line_ref': 'l10n_mk_reports.account_financial_report_l10n_mk_bs_assets',
'liability_line_ref': 'l10n_mk_reports.account_financial_report_l10n_mk_bs_liabilities',
},
'l10n_mn_reports.account_report_balancesheet': {
'asset_line_ref': 'l10n_mn_reports.report_line_balanceta',
'liability_line_ref': 'l10n_mn_reports.report_line_balancele',
},
'l10n_mr_reports.l10n_mr_balance_sheet': {
'asset_line_ref': 'l10n_mr_reports.account_financial_report_mr_active_title',
'liability_line_ref': 'l10n_mr_reports.account_financial_report_mr_passive_title',
},
'l10n_mt_reports.l10n_mt_balance_sheet': {
'asset_line_ref': 'l10n_mt_reports.account_financial_report_mt_active_title',
'liability_line_ref': 'l10n_mt_reports.account_financial_report_mt_passif_title',
},
'l10n_mx_reports.l10n_mx_bs_nif_b6': {
'asset_line_ref': 'l10n_mx_reports.l10n_mx_bs_nif_b6_assets',
'liability_line_ref': 'l10n_mx_reports.l10n_mx_bs_nif_b6_liabilities',
'equity_line_ref': 'l10n_mx_reports.l10n_mx_bs_nif_b6_equity',
},
'l10n_my_reports.account_financial_report_my_bs': {
'asset_line_ref': 'l10n_my_reports.account_financial_report_my_bs_assets',
'liability_line_ref': 'l10n_my_reports.account_financial_report_my_bs_liabilities',
'equity_line_ref': 'l10n_my_reports.account_financial_report_my_bs_equity_earnings',
},
'l10n_mz_reports.l10_mz_bs': {
'asset_line_ref': 'l10n_mz_reports.l10n_mz_bs_line_1',
'liability_line_ref': 'l10n_mz_reports.l10n_mz_bs_line_2',
},
'l10n_nl_reports.account_financial_report_bs': {
'asset_line_ref': 'l10n_nl_reports.account_financial_report_bs_assets',
'liability_line_ref': 'l10n_nl_reports.account_financial_report_bs_leq',
},
'l10n_nl_reports.account_financial_report_bs_tags': {
'asset_line_ref': 'l10n_nl_reports.account_financial_report_bs_tags_assets',
'liability_line_ref': 'l10n_nl_reports.account_financial_report_bs_tags_leq',
},
'l10n_no_reports.account_financial_report_NO_balancesheet': {
'asset_line_ref': 'l10n_no_reports.account_financial_report_NO_active',
'liability_line_ref': 'l10n_no_reports.account_financial_report_NO_passive',
},
'l10n_pe_reports.account_financial_report_bs': {
'asset_line_ref': 'l10n_pe_reports.account_financial_report_bs_A_TOTAL',
'liability_line_ref': 'l10n_pe_reports.account_financial_report_bs_EL',
},
'l10n_pl_reports.l10n_pl_micro_bs': {
'asset_line_ref': 'l10n_pl_reports.l10n_pl_micro_bs_assets',
'liability_line_ref': 'l10n_pl_reports.l10n_pl_micro_bs_passives',
},
'l10n_pl_reports.l10n_pl_small_bs': {
'asset_line_ref': 'l10n_pl_reports.l10n_pl_small_bs_assets',
'liability_line_ref': 'l10n_pl_reports.l10n_pl_small_bs_passives',
},
'l10n_pt_reports.account_financial_report_line_pt_balanco': {
'asset_line_ref': 'l10n_pt_reports.account_financial_report_line_pt_balanco_total_do_ativo',
'liability_line_ref': 'l10n_pt_reports.account_financial_report_line_pt_balanco_total_do_capital_proprio_e_do_passivo',
},
'l10n_ro_reports.account_financial_report_ro_bs_smle': {
'asset_line_ref': 'l10n_ro_reports.account_financial_report_ro_bs_smle_total_assets',
'liability_line_ref': 'l10n_ro_reports.account_financial_report_ro_bs_smle_total_liabilities',
},
'l10n_ro_reports.account_financial_report_ro_bs_large': {
'asset_line_ref': 'l10n_ro_reports.account_financial_report_ro_bs_large_total_assets',
'liability_line_ref': 'l10n_ro_reports.account_financial_report_ro_bs_large_total_liabilities',
},
'l10n_rs_reports.account_financial_report_rs_BS': {
'asset_line_ref': 'l10n_rs_reports.account_financial_report_rs_BS_assets',
'liability_line_ref': 'l10n_rs_reports.account_financial_report_rs_BS_equity_liabilities',
},
'l10n_rw_reports.l10n_rw_balance_sheet': {
'asset_line_ref': 'l10n_rw_reports.account_financial_report_rw_active',
'liability_line_ref': 'l10n_rw_reports.account_financial_report_rw_passive',
},
'l10n_se_reports.account_financial_report_bs': {
'asset_line_ref': 'l10n_se_reports.account_financial_report_bs_A_TOTAL',
'liability_line_ref': 'l10n_se_reports.account_financial_report_bs_EL_TOTAL',
},
'l10n_sg_reports.account_financial_report_sg_bs': {
'asset_line_ref': 'l10n_sg_reports.account_financial_report_sg_bs_assets',
'liability_line_ref': 'l10n_sg_reports.account_financial_report_sg_bs_liabilities',
'equity_line_ref': 'l10n_sg_reports.account_financial_report_sg_bs_equity',
},
'l10n_si_reports.l10n_si_balance_sheet': {
'asset_line_ref': 'l10n_si_reports.l10n_si_balance_sheet_resources',
'liability_line_ref': 'l10n_si_reports.l10n_si_balance_sheet_liabilities',
},
'l10n_sk_reports.l10n_sk_reports_balance_sheet': {
'asset_line_ref': 'l10n_sk_reports.l10n_sk_reports_bs_total_assets',
'liability_line_ref': 'l10n_sk_reports.l10n_sk_reports_bs_total_equity_liabilities',
'balance_col_label': 'net',
},
'l10n_syscohada_reports.account_financial_report_syscohada_bilan': {
'asset_line_ref': 'l10n_syscohada_reports.account_financial_report_line_03_3_11_syscohada_bilan_actif',
'liability_line_ref': 'l10n_syscohada_reports.account_financial_report_line_03_3_11_syscohada_bilan_passif',
'chart_template_refs': syscohada_coas,
},
'l10n_syscohada_reports.account_financial_report_syscebnl_bilan_assoc': {
'asset_line_ref': 'l10n_syscohada_reports.account_financial_report_syscohada_bilan_actif_total',
'liability_line_ref': 'l10n_syscohada_reports.account_financial_report_syscohada_bilan_passif_total',
'chart_template_refs': syscebnl_coas,
},
'l10n_tn_reports.l10n_tn_bs_account_report': {
'asset_line_ref': 'l10n_tn_reports.l10n_tn_bs_assets',
'liability_line_ref': 'l10n_tn_reports.l10n_tn_bs_liabilities_equity',
},
'l10n_tr_reports.account_report_l10n_tr_balance_sheet': {
'asset_line_ref': 'l10n_tr_reports.account_report_line_trbs_active',
'liability_line_ref': 'l10n_tr_reports.account_report_line_trbs_pasive',
},
'l10n_tw_reports.l10n_tw_balance_sheet': {
'asset_line_ref': 'l10n_tw_reports.l10n_tw_balance_sheet_tw_a',
'liability_line_ref': 'l10n_tw_reports.l10n_tw_balance_sheet_tw_lbeq',
},
'l10n_tz_reports.l10n_tz_balance_sheet': {
'asset_line_ref': 'l10n_tz_reports.account_financial_report_tz_active',
'liability_line_ref': 'l10n_tz_reports.account_financial_report_tz_passive',
},
'l10n_us_reports.balance_sheet': {
'asset_line_ref': 'l10n_us_reports.assets',
'liability_line_ref': 'l10n_us_reports.liabilities_equity',
},
'l10n_uz_reports.balance_sheet_l10n_uz': {
'asset_line_ref': 'l10n_uz_reports.account_financial_report_l10n_uz_bs_to_assets',
'liability_line_ref': 'l10n_uz_reports.account_financial_report_l10n_uz_bs_eq_and_obl',
},
'l10n_vn_reports.balance_sheet_l10n_vn': {
'asset_line_ref': 'l10n_vn_reports.account_financial_report_l10n_vn_bs_ta',
'liability_line_ref': 'l10n_vn_reports.account_financial_report_l10n_vn_bs_tos',
},
'l10n_zm_reports.balance_sheet_zm': {
'asset_line_ref': 'l10n_zm_reports.balance_sheet_zm_assets',
'liability_line_ref': 'l10n_zm_reports.balance_sheet_zm_liabilities_and_equities',
},
'l10n_kr_reports.l10_kr_bs': {
'asset_line_ref': 'l10n_kr_reports.l10n_kr_bs_assets',
'liability_line_ref': 'l10n_kr_reports.l10n_kr_bs_total_liabilities_and_equity',
},
'l10n_cn_reports.l10n_cn_asbe_bs': {
'asset_line_ref': 'l10n_cn_reports.l10n_cn_asbe_bs_cn_a',
'liability_line_ref': 'l10n_cn_reports.l10n_cn_asbe_bs_cn_tle',
},
'l10n_cn_reports.l10n_cn_assbe_bs': {
'asset_line_ref': 'l10n_cn_reports.l10n_cn_assbe_bs_cns_ta',
'liability_line_ref': 'l10n_cn_reports.l10n_cn_assbe_bs_cns_tle',
},
'l10n_in_reports.l10n_in_schedule3_balance_sheet': {
'asset_line_ref': 'l10n_in_reports.l10n_in_s3_bs_assets',
'liability_line_ref': 'l10n_in_reports.l10n_in_s3_bs_equity_and_liabilities',
}
}
# === If some accounts should be excluded from the testing, specify them here === #
# Accounts starting with 99 are excluded anyway: users should change their codes
# to something sensible in order for them to be taken into account in the Balance Sheet.
'''
NON_TESTED_ACCOUNTS = {
<chart template ref>: [account_code_1, account_code_2, ...]
}
'''
NON_TESTED_ACCOUNTS = {
'all': [
'99', # 99 account codes are placeholders and should normally be changed by the user.
'123456' # hr.payroll creates an account 123456 Account Payslip Houserental for demo companies; don't test it
],
**{coa: ['13'] for coa in syscohada_coas},
'at': ['98'],
'mn': ['9301'],
'it': ['412', '413', '9102'],
'pt': ['811'],
}
def log_incorrect_accounts_quiet(report_setup_data, amls, totals, is_first_call):
if is_first_call:
_logger.error("""
The Balance Sheet %s is not balanced.
These accounts are incorrectly used in the Balance Sheet
or in the Profit & Loss, if inserted into the Balance Sheet via cross-report).
To show the journal entries that cause the imbalance,
set the EXTRA_DETAIL global to True at the top of the test file.
""",
report_setup_data['report_ref'],
)
_logger.error('- %s %s', amls[0].account_id.code, amls[0].account_id.name)
def log_incorrect_accounts_detailed(report_setup_data, amls, totals, is_first_call):
if is_first_call:
_logger.error("""
The Balance Sheet %s is not balanced.
If you construct any of the following journal entries, Assets != Liabilities + Equity.
""",
report_setup_data['report_ref'],
)
format_params = []
currency = amls.currency_id
for aml in amls:
format_params += [
aml.date,
f'{aml.account_id.code} {aml.account_id.name}'[:50],
currency.format(aml.debit),
currency.format(aml.credit),
]
format_params += [
report_setup_data['report_date'],
currency.format(totals['total_asset']),
currency.format(totals['total_liability']),
]
error_msg = '''
+------------+----------------------------------------------------+------------------+------------------+
| Date | Account | Debit | Credit |
+------------+----------------------------------------------------+------------------+------------------+
| {} | {:<50} | {:<16} | {:<16} |
| {} | {:<50} | {:<16} | {:<16} |
+------------+----------------------------------------------------+------------------+------------------+
Balance Sheet on {}: Total Assets: {} ; Total Liabilities + Equity: {}
'''.format(*format_params)
_logger.error(error_msg)
class TestBalanceSheetBalanced(TransactionCase):
''' Diagnose unbalanced Balance Sheets.
We do this by creating a journal entry with two journal items in each account:
one debit and one credit. We then generate the Balance Sheet report, and check
whether the Assets line is equal to the sum of the Liabilities and Equity lines.
Some accounts are not checked:
- those starting with '99' (automatically created in order to enable some
functionalities to work, but the user is expected to change their code)
- those included in the NON_TESTED_ACCOUNTS dict.
The test can optionally identify guilty accounts using binary search; this can
be toggled on by setting IDENTIFY_INCORRECT_ACCOUNTS = True.
'''
def _test_report(self):
for company in self.companies:
self.env = self.env(context={'allowed_company_ids': company.ids})
with contextlib.closing(self.env.cr.savepoint(flush=False)), self.subTest(CoA=company.chart_template):
# === 1. Set-up localization === #
available_reports, aml_pairs, accounts_by_aml = self._set_up_localization(
company,
post_lines=not IDENTIFY_INCORRECT_ACCOUNTS
)
self.env.cr.execute("ANALYZE account_account, account_move, account_move_line")
# Test each of the Balance Sheet reports available for the CoA.
for report in available_reports:
report_ref = report.get_external_id()[report.id]
if report_ref == 'account_reports.balance_sheet':
continue # failing in too many cases for now
with self.subTest(Report=report_ref):
_logger.info('Testing report %s with CoA %s', report_ref, company.chart_template)
# === 2. Set-up report === #
report_setup_data = self._set_up_report(report)
# === 3. Test that the report is balanced with both the debits journal entry and the credits journal entry. === #
if not IDENTIFY_INCORRECT_ACCOUNTS:
self._check_balance_sheet_balanced(report_setup_data, aml_pairs)
else:
bad_account_ids = set()
logging_fn = log_incorrect_accounts_detailed if EXTRA_DETAIL else log_incorrect_accounts_quiet
self._identify_incorrect_accounts(
report_setup_data,
aml_pairs,
accounts_by_aml,
bad_account_ids,
logging_fn,
)
if bad_account_ids:
self.fail('Balance Sheet not balanced.')
def _set_up_localization(self, company, post_lines=False):
''' Set up a localization for testing.
This identifies the company to use (creating it if needed),
sets self.env.company to it, and generates AMLs for testing.
If a (demo) company already exists with the CoA, we'll just use it
rather than create a new company and load a new CoA for it.
:param account.chart.template coa: the Chart of Accounts to install
:param post_lines: whether to post the generated move lines
:return: (available_reports, aml_pairs, accounts_by_aml), where:
* available_reports are the reports that can be tested for this localization
* aml_pairs is a list of (aml_id, counterpart_aml_id) that were generated
* accounts_by_aml is a map {aml_id: account_id} for the generated AMLs
'''
coa = company.chart_template
coa_setup_data = {}
coa_setup_data['counterpart_account'] = self.env['account.account'].search([
('company_ids', '=', company.id),
('account_type', '=', 'asset_receivable'),
], limit=1)
coa_setup_data['income_account'] = self.env['account.account'].search([
('company_ids', '=', company.id),
('internal_group', '=', 'income'),
], limit=1)
coa_setup_data['journal'] = self.env['account.journal'].search([
('company_id', '=', company.id),
('type', '=', 'general')
], limit=1)
# Find the available Balance Sheets for the current company.
generic_balance_sheet = self.env.ref('account_reports.balance_sheet').with_company(company)
generic_balance_sheet.with_context(active_test=False).variant_report_ids.write({'active': True})
available_report_ids = [variant['id'] for variant in generic_balance_sheet.get_options({})['available_variants']]
available_reports = self.env['account.report'].browse(available_report_ids)
# Don't test Balance Sheets for which the REPORT_CONFIG specifies a chart_template_refs that differs from this CoA.
available_report_refs = available_reports.get_external_id()
report_ids_to_skip = [id_ for id_, report_ref in available_report_refs.items()
if coa not in REPORT_CONFIG.get(report_ref, {}).get('chart_template_refs', [coa])]
available_reports -= self.env['account.report'].browse(report_ids_to_skip)
available_reports = available_reports.with_company(company)
# Choose an account to be a counterpart account. Every AML we generate will have a counterpart in this account.
# We use the Accounts Receivable account (which in general should be well-configured.)
# However, if the Balance Sheet is incorrect for the counterpart account, the test will give weird results.
tested_accounts_domain = [
('company_ids', '=', company.id),
('internal_group', '!=', 'off_balance'),
]
for code in NON_TESTED_ACCOUNTS['all'] + NON_TESTED_ACCOUNTS.get(coa, []):
tested_accounts_domain += ['!', ('code', '=like', f'{code}%')]
tested_accounts = self.env['account.account'].search(tested_accounts_domain)
coa_setup_data['tested_accounts'] = tested_accounts - coa_setup_data['counterpart_account']
# Create two test journal entries: one with debits in each account (other than the counterpart account), the other with credits.
debit_move_aml_pairs, debit_accounts_by_aml = self._create_balance_sheet_test_move(coa_setup_data, post_lines=post_lines)
credit_move_aml_pairs, credit_accounts_by_aml = self._create_balance_sheet_test_move(coa_setup_data, create_credits=True, post_lines=post_lines)
aml_pairs = debit_move_aml_pairs + credit_move_aml_pairs
accounts_by_aml = {**debit_accounts_by_aml, **credit_accounts_by_aml}
return available_reports, aml_pairs, accounts_by_aml
def _set_up_report(self, report):
''' Set-up a Balance Sheet report for testing.
:param account.report report: the Balance Sheet report to set-up
The method sets the following keys of coa_setup_data:
report_ref: the XMLID of the report currently being tested
report: the report currently being tested
report_options: the report options for the test
report_column_balance_idx: the index of the column containing the balance
asset_line: the Total Assets report line
liability_line: the Total Liabilities report line
equity_line: the Total Equity report line (if separate from Liabilities)
'''
report_setup_data = {'report': report}
report_ref = report.get_external_id()[report.id]
if report_ref not in REPORT_CONFIG:
self.fail(f'''
The following Balance Sheet report is installed but is not configured to be tested:
{report_ref}
Please add it to the REPORT_CONFIG global at the beginning of this file.''')
report_config = REPORT_CONFIG[report_ref]
report_setup_data['report_ref'] = report_ref
report_setup_data['report_date'] = '2022-12-31'
report_setup_data['report_options'] = self._generate_options(report, fields.Date.to_date(report_setup_data['report_date']))
# Find the report column containing the total figures.
for idx, col in enumerate(report_setup_data['report_options']['columns']):
if col['expression_label'] in report_config.get('balance_col_label', 'balance'):
report_setup_data['report_column_balance_idx'] = idx
break
else:
self.fail(f'Could not identify totals column for report {report_ref} '
'- please add its expression_label in the REPORT_CONFIG global at the top of this file.')
report_setup_data['asset_line'] = self.env.ref(report_config['asset_line_ref'])
report_setup_data['liability_line'] = self.env.ref(report_config['liability_line_ref'])
report_setup_data['equity_line'] = self.env.ref(report_config['equity_line_ref']) if 'equity_line_ref' in report_config else None
return report_setup_data
def _create_balance_sheet_test_move(self, coa_setup_data, create_credits=False, post_lines=False):
''' Create a journal entry that will be the basis for testing the Balance Sheet.
The created journal entry will have one AML in each account in coa_setup_data['tested_accounts'],
and corresponding counterpart AMLs in coa_setup_data['counterpart_account'].
We create it in SQL to improve performance (since this gets run a lot on runbot).
:param bool create_credits: If true, the AMLs will be created with credits (instead of debits)
and the counterpart AMLs will be created with debits.
:param bool post_lines: If true, the created AMLs will be posted.
:return: (aml_pairs, accounts_by_aml), where:
- aml_pairs is a list of tuples (aml_id, counterpart_aml_id) containing the AMLs of the journal entry that was created.
- accounts_by_aml is a map of AML id to account id.
'''
def get_move_line_sql_create_vals(move, account, balance):
debit, credit = (balance, 0.0) if balance > 0.0 else (0.0, -balance)
return {
'account_id': account.id,
'balance': balance,
'debit': debit,
'credit': credit,
'company_id': move.company_id.id,
'currency_id': move.company_id.currency_id.id,
'date': move.date,
'display_type': 'product',
'journal_id': move.journal_id.id,
'move_id': move.id,
'parent_state': 'posted' if post_lines else None,
}
move = self.env['account.move'].create({
'name': False,
'date': '2022-06-01',
'move_type': 'entry',
'journal_id': coa_setup_data['journal'].id,
})
# For each account, we create 2 AMLs:
# - one AML in that account (either a debit or a credit, depending on the create_credits param)
# - one counterpart AML in the counterpart account
amls_vals = []
for i, account in enumerate(coa_setup_data['tested_accounts']):
balance = self.env.company.currency_id.round(i + 1)
if not create_credits:
balance = -balance
amls_vals += [
get_move_line_sql_create_vals(move, account, balance),
get_move_line_sql_create_vals(move, coa_setup_data['counterpart_account'], -balance),
]
move_previous_year = self.env['account.move'].create({
'name': False,
'date': '2021-12-31',
'move_type': 'entry',
'journal_id': coa_setup_data['journal'].id,
})
# Additionally, in one Income/Expense account, create an AML in the previous fiscal year
# in order to test the unaffected earnings
amls_vals += [
get_move_line_sql_create_vals(move_previous_year, coa_setup_data['income_account'], balance),
get_move_line_sql_create_vals(move_previous_year, coa_setup_data['counterpart_account'], -balance),
]
# Create the AMLs
query_columns = ', '.join(amls_vals[0].keys())
query_placeholder = ', '.join("%s" for d in amls_vals)
query_params = [tuple(d.values()) for d in amls_vals]
self.env['account.move.line'].invalidate_model()
self.env.cr.execute(
f'INSERT INTO "account_move_line" ({query_columns}) VALUES {query_placeholder} RETURNING "id"',
query_params,
)
aml_ids = [aml_id for aml_id, in self.env.cr.fetchall()]
# Create a map of AMLs to accounts, to avoid having to fetch this info from the DB
accounts_by_aml = {aml_ids[i]: aml_vals['account_id'] for i, aml_vals in enumerate(amls_vals)}
# Group AMLs in account/counterpart pairs
aml_pairs = []
for i, _account in enumerate(coa_setup_data['tested_accounts']):
aml_id = aml_ids[2 * i]
counterpart_aml_id = aml_ids[2 * i + 1]
aml_pairs.append((aml_id, counterpart_aml_id))
return aml_pairs, accounts_by_aml
def _check_balance_sheet_balanced(self, report_setup_data, aml_pairs):
''' Check whether the Balance Sheet is balanced. '''
# Set 'parent_state' to 'posted' on the AMLs of the debits journal entry, and to 'draft' on all other AMLs.
totals = self._get_report_totals(report_setup_data)
if not totals['is_balanced']:
self.fail(f'''
The balance sheet {report_setup_data['report_ref']} is not balanced.
Total Assets: {totals['total_asset']}; Total Liabilities + Equity: {totals['total_liability']}.
This test can also find out for you which accounts are incorrectly used in the Balance Sheet.
To do this, set the IDENTIFY_INCORRECT_ACCOUNTS variable at the top of this file to something truthy.
''')
@contextlib.contextmanager
def _activate_lines(self, aml_pairs):
''' On entry: set the 'parent_state' of the specified AMLs to 'posted'.
On exit: set the 'parent_state' of these AMLs to 'draft'.
:param aml_pairs: list of tuples (aml_id, counterpart_aml_id) whose parent_state should be set to 'posted'.
'''
aml_ids = tuple(itertools.chain(*aml_pairs))
self.env['account.move.line'].browse(aml_ids).invalidate_recordset()
self.env.cr.execute(
'''
UPDATE account_move_line
SET parent_state = 'posted'
WHERE id IN %s
''',
[aml_ids]
)
yield
self.env.cr.execute(
'''
UPDATE account_move_line
SET parent_state = 'draft'
WHERE id IN %s
''',
[aml_ids]
)
def _get_report_totals(self, report_setup_data):
''' Get the Assets, Liabilities and Equity totals of the Balance Sheet report. '''
def get_line_amount(lines, report_line, balance_column_idx):
line = next(filter(lambda line: self.env['account.report']._get_res_id_from_line_id(line.id, 'account.report.line') == report_line.id, lines))
balance = line.columns[balance_column_idx].no_format
self.assertIsNotNone(balance, f'Report line "{report_line.name}" does not set a value in the column which should contain the balance.')
return balance
lines = report_setup_data['report']._get_lines(report_setup_data['report_options'])
balance_column_idx = report_setup_data['report_column_balance_idx']
total_asset = get_line_amount(lines, report_setup_data['asset_line'], balance_column_idx)
total_liability = (
get_line_amount(lines, report_setup_data['liability_line'], balance_column_idx)
+ (get_line_amount(lines, report_setup_data['equity_line'], balance_column_idx) if report_setup_data['equity_line'] else 0.0)
)
return {
'total_asset': total_asset,
'total_liability': total_liability,
'is_balanced': self.env.company.currency_id.compare_amounts(total_asset, total_liability) == 0
}
def _identify_incorrect_accounts(self, report_setup_data, aml_pairs, accounts_by_aml, bad_account_ids, logging_fn):
''' Identify accounts that are incorrectly used in the Balance Sheet, using a binary search.
This is a recursive function.
:param report_setup_data: The report configuration to test
:param aml_pairs: a list of tuples (aml_id, counterpart_aml_id)
account.move.lines which cause the Balance Sheet to be unbalanced.
:param accounts_by_aml: a map {aml_id: account_id} of the AMLs to test
:param bad_account_ids: a set of account ids that are determined to be badly referenced,
can be used to avoid testing a bad account twice
:param logging_fn: a function to call when an account causing an unbalance is found. This should take
as first argument a pair (aml_id, counterpart_aml_id) and
as second argument a dict containing information about the report totals
'''
# No need to further test AMLs in accounts already determined to be badly referenced.
aml_pairs = [
(aml_id, counterpart_aml_id)
for aml_id, counterpart_aml_id in aml_pairs
if accounts_by_aml[aml_id] not in bad_account_ids
]
if not aml_pairs:
return
with self._activate_lines(aml_pairs):
totals = self._get_report_totals(report_setup_data)
if totals['is_balanced']:
# Valid subtree case. There are no badly-referenced accounts in the subtree, just return (no need to search deeper)
return
elif len(aml_pairs) == 1:
# Leaf case. This account is badly-referenced: log and return.
logging_fn(
report_setup_data,
amls=self.env['account.move.line'].browse(aml_pairs[0]),
totals=totals,
is_first_call=not bad_account_ids,
)
bad_account_ids.add(accounts_by_aml[aml_pairs[0][0]])
else:
# Non-leaf case. Some accounts in the subtree are badly-referenced: bisect it into two halves, and check each half.
middle_index = len(aml_pairs) // 2
aml_pairs_left = aml_pairs[:middle_index]
aml_pairs_right = aml_pairs[middle_index:]
self._identify_incorrect_accounts(report_setup_data, aml_pairs_left, accounts_by_aml, bad_account_ids, logging_fn)
self._identify_incorrect_accounts(report_setup_data, aml_pairs_right, accounts_by_aml, bad_account_ids, logging_fn)
@classmethod
def _generate_options(cls, report, date_to, default_options=None):
''' Create new options at a certain date.
:param report: The report.
:param date_to: A datetime object or str representation of a date.
:return: The newly created options.
'''
date_to_str = fields.Date.to_string(date_to)
if not default_options:
default_options = {}
return report.get_options({
'selected_variant_id': report.id,
'date': {
'date_to': date_to_str,
},
'show_account': True,
'show_currency': True,
**default_options,
})

View File

@@ -0,0 +1,272 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# pylint: disable=bad-whitespace
from .common import TestAccountReportsCommon
from odoo import fields, Command
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestBalanceSheetReport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.report = cls.env.ref('account_reports.balance_sheet')
def test_report_lines_ordering(self):
""" Check that the report lines are correctly ordered with nested account groups """
account_parent_1 = self.env['account.account'].create({
'code': '101',
'name': 'Parent 1',
'account_type': 'asset_cash',
'active': False,
})
account_parent_2 = self.env['account.account'].create({
'code': '1014',
'name': 'Parent 2',
'account_type': 'asset_cash',
'parent_id': account_parent_1.id,
'active': False,
})
account_bank = self.company_data['default_journal_bank'].default_account_id
account_cash = self.company_data['default_journal_cash'].default_account_id
account_a = self.env['account.account'].create([{'code': '1014010', 'name': 'A', 'account_type': 'asset_cash', 'parent_id': account_parent_2.id}])
account_c = self.env['account.account'].create([{'code': '101600', 'name': 'C', 'account_type': 'asset_cash', 'parent_id': account_parent_1.id}])
# Create a journal lines for each account
move = self.env['account.move'].create({
'date': '2020-02-02',
'line_ids': [
Command.create({
'account_id': account.id,
'name': 'name',
})
for account in [account_a, account_c, account_bank, account_cash]
],
})
move.action_post()
move.line_ids.flush_recordset()
# Create the report hierarchy with the Bank and Cash Accounts lines unfolded
line_id = self._get_basic_line_dict_id_from_report_line_ref('account_reports.account_financial_report_bank_view0')
options = self._generate_options(self.report, '2020-02-01', '2020-02-28')
options['unfolded_lines'] = [line_id]
options['hierarchy'] = True
self.env.company.totals_below_sections = False
lines = self.report._get_lines(options)
# The Bank and Cash Accounts section start at index 2
# Since we created 4 lines + 2 groups, we keep the 6 following lines
unfolded_lines = self.report._get_unfolded_lines(lines, line_id)
unfolded_lines = [{'name': line.name, 'level': line.level} for line in unfolded_lines]
self.assertEqual(
unfolded_lines,
[
{'level': 5, 'name': 'Bank and Cash Accounts'},
{'level': 6, 'name': '101 Parent 1'},
{'level': 7, 'name': '1014 Parent 2'},
{'level': 8, 'name': '1014010 A'},
{'level': 7, 'name': '101600 C'},
{'level': 6, 'name': '101401 Bank'},
{'level': 6, 'name': '101501 Cash'},
]
)
def test_balance_sheet_custom_date(self):
line_id = self.env.ref('account_reports.account_financial_report_bank_view0').id
options = self._generate_options(self.report, '2020-02-01', '2020-02-28')
options['date']['period_type'] = 'custom'
options['unfolded_lines'] = [line_id]
invoices = self.env['account.move'].create([{
'move_type': 'out_invoice',
'partner_id': self.partner_a.id,
'date': '2020-0%s-15' % i,
'invoice_date': '2020-0%s-15' % i,
'invoice_line_ids': [(0, 0, {
'product_id': self.product_a.id,
'price_unit': 1000.0,
'tax_ids': [(6, 0, self.tax_sale_a.ids)],
})],
} for i in range(1, 4)])
invoices.action_post()
lines = self.report._get_lines(options)
self.assertLinesValues(
lines,
# Name Balance
[ 0, 1],
[
('ASSETS', 2300.00),
('Current Assets', 2300.00),
('Bank and Cash Accounts', 0.00),
('Receivables', 2300.00),
('Current Assets', 0.00),
('Prepayments', 0.00),
('Total Current Assets', 2300.00),
('Fixed Assets', 0.00),
('Non-current Assets', 0.00),
('Total ASSETS', 2300.00),
('LIABILITIES', 300.00),
('Current Liabilities', 300.00),
('Current Liabilities', 300.00),
('Credit Card', 0.00),
('Payables', 0.00),
('Total Current Liabilities', 300.00),
('Non-current Liabilities', 0.00),
('Total LIABILITIES', 300.00),
('EQUITY (& EARNINGS)', 2000.00),
('Equity', 0.00),
('Earnings', 2000.00),
('Current Year Unallocated Earnings', 2000.00),
('Previous Years Earnings', 0.00),
('Total Earnings', 2000.00),
('Total EQUITY (& EARNINGS)', 2000.00),
('LIABILITIES + EQUITY', 2300.00),
],
options,
)
def test_unfold_all_and_total_lines(self):
""" Check that exactly the total lines we want exist when we use the 'unfold_all' option. I.e. empty sections should not have total lines (since there are not lines to total).
This test only tests the function '_get_lines'. It does not test that the total lines are always handled correctly for manual unfolds in the web UI. """
self.env.company.totals_below_sections = True
options = self._generate_options(self.report, '1990-01-01', '1990-01-01')
bank_journal = self.company_data['default_journal_bank']
account_bank = bank_journal.default_account_id
account_other = self.env['account.account'].create({
'account_type': 'asset_current',
'name': 'account_other',
'code': '121040',
})
self.env['account.move'].create({
'move_type': 'entry',
'date': '1990-01-01',
'journal_id': bank_journal.id,
'line_ids': [
(0, 0, {'debit': 200.0, 'credit': 0.0, 'account_id': account_bank.id}),
(0, 0, {'debit': 0.0, 'credit': 200.0, 'account_id': account_other.id}),
],
}).action_post()
# Note that assertLinesValues filters / ignores children lines of folded lines.
# The total lines for the 2 visible lines with groupbys already exist in 'folded_lines' but are filtered / ignored by assertLinesValues.
# (Thus they do not appear in the expected result below either.)
self.assertLinesValues(
self.report._get_lines(options),
# Name
[ 0],
[
('ASSETS',),
('Current Assets',),
('Bank and Cash Accounts',),
('Receivables',),
('Current Assets',),
('Prepayments',),
('Total Current Assets',),
('Fixed Assets',),
('Non-current Assets',),
('Total ASSETS',),
('LIABILITIES',),
('Current Liabilities',),
('Current Liabilities',),
('Credit Card',),
('Payables',),
('Total Current Liabilities',),
('Non-current Liabilities',),
('Total LIABILITIES',),
('EQUITY (& EARNINGS)',),
('Equity',),
('Earnings',),
('Current Year Unallocated Earnings',),
('Previous Years Earnings',),
('Total Earnings',),
('Total EQUITY (& EARNINGS)',),
('LIABILITIES + EQUITY',),
],
options,
)
options['unfold_all'] = True
self.assertLinesValues(
self.report._get_lines(options),
# Name
[ 0],
[
('ASSETS',),
('Current Assets',),
('Bank and Cash Accounts',),
(account_bank.display_name,),
('Total Bank and Cash Accounts',),
('Receivables',),
('Current Assets',),
(account_other.display_name,),
('Total Current Assets',),
('Prepayments',),
('Total Current Assets',),
('Fixed Assets',),
('Non-current Assets',),
('Total ASSETS',),
('LIABILITIES',),
('Current Liabilities',),
('Current Liabilities',),
('Credit Card',),
('Payables',),
('Total Current Liabilities',),
('Non-current Liabilities',),
('Total LIABILITIES',),
('EQUITY (& EARNINGS)',),
('Equity',),
('Earnings',),
('Current Year Unallocated Earnings',),
('Previous Years Earnings',),
('Total Earnings',),
('Total EQUITY (& EARNINGS)',),
('LIABILITIES + EQUITY',),
],
options,
)
def test_balance_sheet_groupby_analytic_account(self):
analytic_plan = self.env['account.analytic.plan'].create({
'name': 'Analytic Plan',
})
analytic_account = self.env['account.analytic.account'].create({
'name': 'analytic Account',
'plan_id': analytic_plan.id,
})
options = self._generate_options(
self.report,
'2023-01-01',
'2023-12-31',
default_options={
'analytic_accounts_groupby': [analytic_account.id],
},
)
report_line = self.report.line_ids[0]
lines = self.report._get_lines(options)
report_line_dict = next(l for l in lines if l.name == report_line.name)
audit_params = self._get_audit_params_from_report_line(
options,
report_line,
report_line_dict,
column_group_index=options['columns'][0]['column_group_index'],
)
action = self.report.dispatch_report_action(options, 'action_audit_cell', audit_params)
self.assertTrue(action)
self.assertIsInstance(action['context'], dict)

View File

@@ -0,0 +1,873 @@
from odoo import Command, fields
from odoo.tests import tagged
from odoo.tools import date_utils
from odoo.addons.account_reports.tests.common import TestAccountReportsCommon
@tagged('post_install', '-at_install')
class TestBudgetReport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.company_data['company'].totals_below_sections = False
cls.account_1 = cls.company_data['default_account_revenue']
cls.account_2 = cls.copy_account(cls.account_1)
cls.account_3 = cls.copy_account(cls.account_1)
cls.account_4 = cls.copy_account(cls.account_1)
# Create a test report
cls.report = cls.env['account.report'].create({
'name': "Budget Test",
'filter_date_range': True,
'filter_budgets': True,
'filter_period_comparison': True,
'column_ids': [
Command.create({
'name': "Balance",
'expression_label': 'balance',
}),
],
'line_ids': [
Command.create({
'name': 'line_domain',
'groupby': 'account_id',
'foldability': 'always_unfolded',
'expression_ids': [
Command.create({
'label': 'balance',
'formula': "[('account_id.account_type', '=', 'income')]",
'subformula': 'sum',
'engine': 'domain',
}),
],
}),
Command.create({
'name': 'line_account_codes',
'groupby': 'account_id',
'foldability': 'always_unfolded',
'expression_ids': [
Command.create({
'label': 'balance',
'formula': cls.account_1.code[:3],
'engine': 'account_codes',
}),
],
}),
],
})
# Create budgets
cls.budget_1 = cls._create_budget(
{
cls.account_1.id: 1000,
cls.account_3.id: 100,
cls.account_4.id: 10,
},
'2020-01-01',
'2020-01-01',
)
cls.budget_2 = cls._create_budget(
{
cls.account_2.id: 10,
},
'2020-01-01',
'2020-01-01',
)
@classmethod
def _create_budget(cls, amount_per_account_ids=None, date_from=None, date_to=None):
date_from, date_to = fields.Date.to_date(date_from), fields.Date.to_date(date_to)
items = []
for account_id, amount in amount_per_account_ids.items():
for item_date in date_utils.date_range(date_from, date_to):
items.append(Command.create({
'amount': amount,
'account_id': account_id,
'date': date_utils.start_of(item_date, 'month'),
}))
return cls.env['account.report.budget'].create({
'name': 'Budget',
'item_ids': items,
})
@classmethod
def _create_moves(cls, amount_per_account_ids=None, date_from=None, date_to=None, to_post=True):
date_from, date_to = fields.Date.to_date(date_from), fields.Date.to_date(date_to)
moves_to_create = []
for move_date in date_utils.date_range(date_from, date_to):
move_to_create = {
'date': move_date,
'journal_id': cls.company_data['default_journal_misc'].id,
'line_ids': [],
}
for account_id, amount in amount_per_account_ids.items():
move_to_create['line_ids'].extend([
Command.create({
'debit': amount,
'account_id': account_id,
}),
Command.create({
'credit': amount,
'account_id': cls.company_data['default_account_assets'].id,
})
])
moves_to_create.append(move_to_create)
moves = cls.env['account.move'].create(moves_to_create)
if to_post:
moves.action_post()
return moves
def test_reports_single_budget(self):
self._create_moves(
{
self.account_1.id: 100,
self.account_2.id: 200,
self.account_3.id: 300,
},
'2020-01-01',
'2020-01-01',
)
options = self._generate_options(
self.report,
'2020-01-01',
'2020-12-31',
default_options={'budgets': [{'id': self.budget_1.id, 'selected': True}]},
)
lines = self.report._get_lines(options)
self.assertLinesValues(
lines,
[ 0, 1, 2, 3],
[
('line_domain', 600, 1110, '54.1%'),
(self.account_1.display_name, 100, 1000, '10.0%'),
(self.account_2.display_name, 200, 0, 'n/a'),
(self.account_3.display_name, 300, 100, '300.0%'),
(self.account_4.display_name, 0, 10, '0.0%'),
('line_account_codes', 600, 1110, '54.1%'),
(self.account_1.display_name, 100, 1000, '10.0%'),
(self.account_2.display_name, 200, 0, 'n/a'),
(self.account_3.display_name, 300, 100, '300.0%'),
(self.account_4.display_name, 0, 10, '0.0%'),
],
options,
)
def test_reports_multiple_budgets(self):
""" This test verifies the report when we have several budgets selected.
The report should have 2 columns per budget, the budget itself and
the comparison column.
"""
self._create_moves(
{
self.account_1.id: 100,
self.account_2.id: 200,
self.account_3.id: 300,
},
'2020-01-01',
'2020-01-01',
)
options = self._generate_options(
self.report,
'2020-01-01',
'2020-12-31',
default_options={'budgets': [{'id': self.budget_1.id, 'selected': True}, {'id': self.budget_2.id, 'selected': True}]},
)
lines = self.report._get_lines(options)
self.assertLinesValues(
lines,
[ 0, 1, 2, 3, 4, 5],
[
('line_domain', 600, 1110, '54.1%', 10, '6000.0%'),
(self.account_1.display_name, 100, 1000, '10.0%', 0, 'n/a'),
(self.account_2.display_name, 200, 0, 'n/a', 10, '2000.0%'),
(self.account_3.display_name, 300, 100, '300.0%', 0, 'n/a'),
(self.account_4.display_name, 0, 10, '0.0%', 0, 'n/a'),
('line_account_codes', 600, 1110, '54.1%', 10, '6000.0%'),
(self.account_1.display_name, 100, 1000, '10.0%', 0, 'n/a'),
(self.account_2.display_name, 200, 0, 'n/a', 10, '2000.0%'),
(self.account_3.display_name, 300, 100, '300.0%', 0, 'n/a'),
(self.account_4.display_name, 0, 10, '0.0%', 0, 'n/a'),
],
options,
)
def test_reports_budget_with_comparison_period(self):
budget_2024 = self._create_budget({self.account_1.id: 200}, '2024-01-01', '2024-12-31')
moves = self._create_moves({self.account_1.id: 200}, '2024-01-01', '2024-12-31', to_post=False)
moves += self._create_moves({self.account_1.id: 600}, '2024-06-22', '2024-06-22', to_post=False)
moves.action_post()
options = self._generate_options(
self.report,
'2024-06-01',
'2024-06-30',
default_options={
'budgets': [{'id': budget_2024.id, 'selected': True}],
'comparison': {'filter': 'previous_period', 'number_period': 1},
},
)
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1, 2, 3, 4, 5, 6],
[
('line_domain', 800, 200, '400.0%', 200, 200, '100.0%'),
(self.account_1.display_name, 800, 200, '400.0%', 200, 200, '100.0%'),
('line_account_codes', 800, 200, '400.0%', 200, 200, '100.0%'),
(self.account_1.display_name, 800, 200, '400.0%', 200, 200, '100.0%'),
],
options,
)
def test_reports_budget_with_comparison_period_and_multiple_budgets(self):
budget_2024 = self._create_budget({self.account_1.id: 200}, '2024-01-01', '2024-12-31')
budget_2023 = self._create_budget({self.account_1.id: 400}, '2023-01-01', '2023-12-31')
moves = self._create_moves({self.account_1.id: 200}, '2024-01-01', '2024-12-31', to_post=False)
moves += self._create_moves({self.account_1.id: 400}, '2023-01-01', '2023-12-31', to_post=False)
moves.action_post()
options = self._generate_options(
self.report,
'2024-01-01',
'2024-12-31',
default_options={
'budgets': [{'id': budget_2024.id, 'selected': True}, {'id': budget_2023.id, 'selected': True}],
'comparison': {'filter': 'previous_period', 'number_period': 1},
},
)
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
# [ Period 2024 + Budget 2024 + % + Budget 2023 + %] [ Period 2023 + Budget 2024 + % + Budget 2023 + %]
[
('line_domain', 2400, 2400, '100.0%', 0, 'n/a', 4800, 0, 'n/a', 4800, '100.0%'),
(self.account_1.display_name, 2400, 2400, '100.0%', 0, 'n/a', 4800, 0, 'n/a', 4800, '100.0%'),
('line_account_codes', 2400, 2400, '100.0%', 0, 'n/a', 4800, 0, 'n/a', 4800, '100.0%'),
(self.account_1.display_name, 2400, 2400, '100.0%', 0, 'n/a', 4800, 0, 'n/a', 4800, '100.0%'),
],
options,
)
def test_report_budget_items_with_different_date_filters(self):
""" The aim of this test is checking that we get the correct budget items
according to the selected dates.
"""
budget_2024 = self._create_budget({self.account_1.id: 300}, '2024-01-01', '2024-12-31')
self._create_moves({self.account_1.id: 200}, '2024-01-01', '2024-12-31')
# Case when we display a whole year in the report
options = self._generate_options(
self.report,
'2024-01-01',
'2024-12-31',
default_options={'budgets': [{'id': budget_2024.id, 'selected': True}]},
)
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1, 2],
[
('line_domain', 2400, 3600),
(self.account_1.display_name, 2400, 3600),
('line_account_codes', 2400, 3600),
(self.account_1.display_name, 2400, 3600),
],
options,
)
# Case when we display a whole quarter
options = self._generate_options(
self.report,
'2024-01-01',
'2024-03-31',
default_options={'budgets': [{'id': budget_2024.id, 'selected': True}]},
)
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1, 2],
[
('line_domain', 600, 900),
(self.account_1.display_name, 600, 900),
('line_account_codes', 600, 900),
(self.account_1.display_name, 600, 900),
],
options,
)
# Case when we display a whole month
options = self._generate_options(
self.report,
'2024-03-01',
'2024-03-31',
default_options={'budgets': [{'id': budget_2024.id, 'selected': True}]},
)
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1, 2],
[
('line_domain', 200, 300),
(self.account_1.display_name, 200, 300),
('line_account_codes', 200, 300),
(self.account_1.display_name, 200, 300),
],
options,
)
def test_report_budget_edit_items(self):
""" This test verifies the way we're modifying budget items.
The system calculates the difference between the old and new values
and distributes this difference proportionally over the number of
months in the selected period.
The test checks the following scenarios:
1. Adding a rounded value (1200) for an entire year (12 months).
2. Setting the value to 300 for 3 months (no change expected).
3. Setting the value to 900 for 3 months, resulting in three new values of 200 each.
4. Reducing the value for a whole year to a non-rounded value and checking if the
remainder is correctly applied to the last period.
"""
def set_budget_item(value, account_id):
budget_2024._create_or_update_budget_items(
value_to_set=value,
account_id=account_id,
rounding=self.env.company.currency_id.decimal_places,
date_from=options['date']['date_from'],
date_to=options['date']['date_to'],
)
budget_2024 = self.env['account.report.budget'].create({'name': "Budget 2024"})
self._create_moves({self.account_1.id: 200}, '2024-01-01', '2024-12-31')
options = self._generate_options(
self.report,
'2024-01-01',
'2024-12-31',
default_options={'budgets': [{'id': budget_2024.id, 'selected': True}]},
)
set_budget_item(1200, self.account_1.id)
expected_items = [
{'amount': 100.0, 'date': fields.Date.to_date('2024-01-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-02-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-03-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-04-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-05-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-06-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-07-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-08-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-09-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-10-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-11-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-12-01')},
]
self.assertRecordValues(
budget_2024.item_ids,
expected_items,
)
options = self._generate_options(
self.report,
'2024-01-01',
'2024-03-31',
default_options={'budgets': [{'id': budget_2024.id, 'selected': True}]},
)
set_budget_item(300, self.account_1.id)
# Nothing should be added as we don't change anything
self.assertRecordValues(
budget_2024.item_ids,
expected_items,
)
set_budget_item(900, self.account_1.id)
expected_items = [
{'amount': 300.0, 'date': fields.Date.to_date('2024-01-01')},
{'amount': 300.0, 'date': fields.Date.to_date('2024-02-01')},
{'amount': 300.0, 'date': fields.Date.to_date('2024-03-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-04-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-05-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-06-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-07-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-08-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-09-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-10-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-11-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2024-12-01')},
]
self.assertRecordValues(
budget_2024.item_ids,
expected_items,
)
options = self._generate_options(
self.report,
'2024-01-01',
'2024-12-31',
default_options={'budgets': [{'id': budget_2024.id, 'selected': True}]},
)
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1, 2],
[
('line_domain', 2400, 1800),
(self.account_1.display_name, 2400, 1800),
('line_account_codes', 2400, 1800),
(self.account_1.display_name, 2400, 1800),
],
options,
)
# Test the case with a remainder
set_budget_item(1000, self.account_1.id)
expected_items = [
{'amount': 300.0 - 66.66, 'date': fields.Date.to_date('2024-01-01')},
{'amount': 300.0 - 66.66, 'date': fields.Date.to_date('2024-02-01')},
{'amount': 300.0 - 66.66, 'date': fields.Date.to_date('2024-03-01')},
{'amount': 100.0 - 66.66, 'date': fields.Date.to_date('2024-04-01')},
{'amount': 100.0 - 66.66, 'date': fields.Date.to_date('2024-05-01')},
{'amount': 100.0 - 66.66, 'date': fields.Date.to_date('2024-06-01')},
{'amount': 100.0 - 66.66, 'date': fields.Date.to_date('2024-07-01')},
{'amount': 100.0 - 66.66, 'date': fields.Date.to_date('2024-08-01')},
{'amount': 100.0 - 66.66, 'date': fields.Date.to_date('2024-09-01')},
{'amount': 100.0 - 66.66, 'date': fields.Date.to_date('2024-10-01')},
{'amount': 100.0 - 66.66, 'date': fields.Date.to_date('2024-11-01')},
{'amount': 100.0 - 66.74, 'date': fields.Date.to_date('2024-12-01')},
]
self.assertRecordValues(
budget_2024.item_ids,
expected_items,
)
def test_report_budget_show_all_accounts_filter(self):
""" The aim of this test is checking that the show all accounts filter
is returning all the income accounts (as our test report is working with
income accounts only).
"""
self.env.companies = self.env.company
budget_2024 = self._create_budget({self.account_1.id: 300}, '2024-01-01', '2024-12-31')
options = self._generate_options(
self.report,
'2024-01-01',
'2024-12-31',
default_options={
'budgets': [{'id': budget_2024.id, 'selected': True}],
'show_all_accounts': True,
},
)
expected_lines = [
('line_domain', 0, 3600),
(self.account_1.display_name, 0, 3600),
]
expected_lines += [
(account['display_name'], 0, 0)
for account in self.env['account.account'].search_read([
('id', '!=', self.account_1.id),
('account_type', '=', 'income'),
('company_ids', 'in', self.report.get_report_company_ids(options)),
], ['display_name'], order='code')
]
expected_lines += [
('line_account_codes', 0, 3600),
(self.account_1.display_name, 0, 3600),
]
expected_lines += [
(account['display_name'], 0, 0)
for account in self.env['account.account'].search_read([
('id', '!=', self.account_1.id),
('code', '=like', f'{self.account_1.code[:3]}%'),
('company_ids', 'in', self.report.get_report_company_ids(options)),
], ['display_name'], order='code')
]
self.assertLinesValues(
self.report._get_lines(options),
[0, 1, 2],
expected_lines,
options,
)
def test_financial_budget_with_analytic_groupby(self):
""" Ensure that when budgets and analytics groupby filters are both active, then their headers are
displayed on the same level, and values in the report are properly computed"""
budget_a = self.env['account.report.budget'].create([{'name': "Budget A"}])
budget_b = self.env['account.report.budget'].create([{'name': "Budget B"}])
budget_a._create_or_update_budget_items(
value_to_set=2400, # 100 each month
account_id=self.account_1.id,
rounding=self.env.company.currency_id.decimal_places,
date_from='2024-01-01',
date_to='2025-12-31',
)
budget_b._create_or_update_budget_items(
value_to_set=3000, # 125 each month
account_id=self.account_1.id,
rounding=self.env.company.currency_id.decimal_places,
date_from='2024-01-01',
date_to='2025-12-31',
)
self.env.user.group_ids += self.env.ref('analytic.group_analytic_accounting')
self.report.write({'filter_analytic_groupby': True})
analytic_plan_a = self.env['account.analytic.plan'].create([{
'name': 'Plan A',
}])
analytic_account_1 = self.env['account.analytic.account'].create([{
'name': 'Account A1',
'plan_id': analytic_plan_a.id
}])
analytic_account_2 = self.env['account.analytic.account'].create([{
'name': 'Account A2',
'plan_id': analytic_plan_a.id
}])
moves_2024 = self._create_moves({self.account_1.id: 100}, '2024-01-01', '2024-12-31', to_post=False)
moves_2025 = self._create_moves({self.account_1.id: 150}, '2025-01-01', '2025-12-31', to_post=False)
for move_line in (moves_2024 + moves_2025).line_ids:
move_line.analytic_distribution = {str(analytic_account_1.id): 75.0, str(analytic_account_2.id): 25.0}
(moves_2024 + moves_2025).action_post()
options = self._generate_options(
self.report,
'2025-01-01',
'2025-12-31',
default_options={
'comparison': {'filter': 'previous_period', 'number_period': 1},
'analytic_accounts_groupby': [analytic_account_1.id, analytic_account_2.id],
'budgets': [{'id': budget_a.id, 'selected': True}, {'id': budget_b.id, 'selected': True}],
}
)
self.assertEqual(
[header['name'] for header in options['column_headers'][1]],
['Account A1', 'Account A2', 'Period Total', 'Budget A', '%', 'Budget B', '%']
)
self.assertLinesValues(
self.report._get_lines(options),
# [ 2025 ] [ 2024 ]
# [ A1 ] [ A2 ] [ Total ] [ Budget A ] [ % ] [ Budget B ] [ % ] [ A1 ] [ A2 ] [ Total ] [ Budget A ] [ % ] [ Budget B ] [ % ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[
('line_domain', 1350, 450, 1800, 1200, '150.0%', 1500, '120.0%', 900, 300, 1200, 1200, '100.0%', 1500, '80.0%'),
(self.account_1.display_name, 1350, 450, 1800, 1200, '150.0%', 1500, '120.0%', 900, 300, 1200, 1200, '100.0%', 1500, '80.0%'),
('line_account_codes', 1350, 450, 1800, 1200, '150.0%', 1500, '120.0%', 900, 300, 1200, 1200, '100.0%', 1500, '80.0%'),
(self.account_1.display_name, 1350, 450, 1800, 1200, '150.0%', 1500, '120.0%', 900, 300, 1200, 1200, '100.0%', 1500, '80.0%'),
],
options,
)
def test_financial_budget_with_several_columns(self):
""" Ensure that financial budget feature works properly on reports with several columns,
and that percentage column of budget is computed based on the 'balance' column, considered the main one,
if there is more than one moneraty column. """
self.report.write({
'column_ids': [
Command.create({
'name': "Column test",
'expression_label': 'column_test',
}),
],
})
self._create_moves(
{
self.account_1.id: 100,
self.account_2.id: 200,
self.account_3.id: 300,
},
'2020-01-01',
'2020-01-01',
)
options = self._generate_options(
self.report,
'2020-01-01',
'2020-12-31',
default_options={
'comparison': {'filter': 'previous_period', 'number_period': 1},
'budgets': [{'id': self.budget_1.id, 'selected': True}],
}
)
# Ensure level header colspan is 3 for top header, 2 for the columns + 1 selected budget
self.assertEqual(
self.report._get_column_headers_render_data(options),
{'level_colspan': [4, 2], 'level_repetitions': [1, 2], 'custom_subheaders': []}
)
self.assertLinesValues(
self.report._get_lines(options),
# [ 2020 ] [ 2019 ]
# [ col 1 ] [ col 2 ] [ budget 1 ] [ budget percentage ] [ col 1 ] [ col 2 ] [ budget 1 ] [ budget percentag ]
[0, 1, 2, 3, 4, 5, 6, 7, 8],
[
('line_domain', 600, '', 1110, '54.1%', 0, '', 0, 'n/a'),
(self.account_1.display_name, 100, '', 1000, '10.0%', 0, '', 0, 'n/a'),
(self.account_2.display_name, 200, '', 0, 'n/a', 0, '', 0, 'n/a'),
(self.account_3.display_name, 300, '', 100, '300.0%', 0, '', 0, 'n/a'),
(self.account_4.display_name, 0, '', 10, '0.0%', 0, '', 0, 'n/a'),
('line_account_codes', 600, '', 1110, '54.1%', 0, '', 0, 'n/a'),
(self.account_1.display_name, 100, '', 1000, '10.0%', 0, '', 0, 'n/a'),
(self.account_2.display_name, 200, '', 0, 'n/a', 0, '', 0, 'n/a'),
(self.account_3.display_name, 300, '', 100, '300.0%', 0, '', 0, 'n/a'),
(self.account_4.display_name, 0, '', 10, '0.0%', 0, '', 0, 'n/a'),
],
options,
)
def test_financial_budget_with_horizontal_and_analytic_groupbys(self):
""" Ensure that financial budgets are properly computed when combined with horizontal groupby filters and analytic filters """
budget = self.env['account.report.budget'].create([{'name': "Budget test"}])
budget._create_or_update_budget_items(
value_to_set=1200, # 100 each month
account_id=self.account_1.id,
rounding=self.env.company.currency_id.decimal_places,
date_from='2025-01-01',
date_to='2025-12-31',
)
self.env.user.group_ids += self.env.ref('analytic.group_analytic_accounting')
self.report.write({'filter_analytic_groupby': True})
analytic_plan = self.env['account.analytic.plan'].create([{
'name': 'Plan test',
}])
analytic_account_1 = self.env['account.analytic.account'].create([{
'name': 'Account A1',
'plan_id': analytic_plan.id
}])
analytic_account_2 = self.env['account.analytic.account'].create([{
'name': 'Account A2',
'plan_id': analytic_plan.id
}])
moves_2025 = self._create_moves({self.account_1.id: 150}, '2025-01-01', '2025-12-31', to_post=False)
for move_line in moves_2025.line_ids:
move_line.partner_id = self.partner_a
move_line.analytic_distribution = {str(analytic_account_1.id): 50.0, str(analytic_account_2.id): 25.0}
moves_2025.action_post()
move_partner_b = self._create_moves({self.account_1.id: 300}, '2025-01-01', '2025-01-31', to_post=False)
move_partner_b.line_ids.partner_id = self.partner_b
move_partner_b.action_post()
horizontal_group = self.env['account.report.horizontal.group'].create([{
'name': 'Horizontal Group',
'rule_ids': [
Command.create({
'field_name': 'partner_id',
'domain': f"[('id', 'in', {(self.partner_a + self.partner_b).ids})]",
}),
],
}])
self.report.horizontal_group_ids |= horizontal_group
options = self._generate_options(
self.report,
'2025-01-01',
'2025-12-31',
default_options={
'analytic_accounts_groupby': [analytic_account_1.id, analytic_account_2.id],
'selected_horizontal_group_id': horizontal_group.id,
'budgets': [{'id': budget.id, 'selected': True}],
}
)
self.assertEqual(
[
[header['name'] for header in header_level]
for header_level in options['column_headers']
],
[
['2025'],
['partner_a', 'partner_b', 'Period Total', 'Budget test', '%'],
['Account A1', 'Account A2', 'Total'],
]
)
self.assertEqual(
self.report._get_column_headers_render_data(options),
{'level_colspan': [9, 3, 1], 'level_repetitions': [1, 1, 2], 'custom_subheaders': []}
)
self.assertLinesValues(
self.report._get_lines(options),
# [ 2025 ]
# [ Partner A ] [ Partner B ] [ Period Total ] [ Budget ] [ % ]
# [ A1 ] [ A2 ] [ Total ] [ A1 ] [ A2 ] [ Total ] [ ] [ ] [ ]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[
('line_domain', 900, 450, 1800, 0, 0, 300, 2100, 1200, '175.0%'),
(self.account_1.display_name, 900, 450, 1800, 0, 0, 300, 2100, 1200, '175.0%'),
('line_account_codes', 900, 450, 1800, 0, 0, 300, 2100, 1200, '175.0%'),
(self.account_1.display_name, 900, 450, 1800, 0, 0, 300, 2100, 1200, '175.0%'),
],
options,
)
def test_hierarchy_with_budget(self):
""" Check that the report lines are correct with a budget and the option "Hierarchy and subtotals" is ticked"""
self.company_data['default_account_revenue'].parent_id = self.env['account.account'].create({
'code': '1.9',
'name': 'Sales',
'account_type': 'income',
'active': False,
})
move = self.env['account.move'].create({
'date': '2020-02-02',
'line_ids': [
Command.create({
'account_id': self.company_data['default_account_revenue'].id,
'name': 'name',
})
],
})
move.action_post()
move.line_ids.flush_recordset()
profit_and_loss_report = self.env.ref('account_reports.profit_and_loss')
line_id = self._get_basic_line_dict_id_from_report_line_ref('account_reports.account_financial_report_revenue0')
options = self._generate_options(profit_and_loss_report, '2020-02-01', '2024-12-28', default_options={'budgets': [{'id': self.budget_1.id, 'selected': True}]})
options['unfolded_lines'] = [line_id]
options['hierarchy'] = True
options['unfold_all'] = True
lines = profit_and_loss_report._get_lines(options)
unfolded_lines = profit_and_loss_report._get_unfolded_lines(lines, line_id)
unfolded_lines = [{'name': line.name, 'level': line.level} for line in unfolded_lines]
self.assertEqual(
unfolded_lines,
[
{'level': 1, 'name': 'Revenue'},
{'level': 2, 'name': '1.9 Sales'},
{'level': 3, 'name': '400000 Product Sales'},
]
)
def test_budget_report_edit_items_with_date(self):
"""
Ensure budget items are created or updated correctly
when editing across varying date ranges
"""
def set_budget_item(value, account_id, date_from, date_to):
budget._create_or_update_budget_items(
value_to_set=value,
account_id=account_id,
rounding=self.env.company.currency_id.decimal_places,
date_from=date_from,
date_to=date_to,
)
budget = self.env['account.report.budget'].create({'name': "Budget"})
set_budget_item(1200, self.account_1.id, '2025-01-01', '2025-12-01')
expected_items = [
{'amount': 100.0, 'date': fields.Date.to_date('2025-01-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-02-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-03-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-04-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-05-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-06-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-07-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-08-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-09-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-10-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-11-01')},
{'amount': 100.0, 'date': fields.Date.to_date('2025-12-01')},
]
self.assertRecordValues(budget.item_ids, expected_items)
# Update the second and third months to total of 900 (450 per month)
set_budget_item(900, self.account_1.id, '2025-01-10', '2025-3-10')
# Now the second and third months each have an amount of 450
set_budget_item(1000, self.account_1.id, '2025-01-01', '2025-12-01')
expected_items = [
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-01-01')},
{'amount': 450.0 - 75.00, 'date': fields.Date.to_date('2025-02-01')},
{'amount': 450.0 - 75.00, 'date': fields.Date.to_date('2025-03-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-04-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-05-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-06-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-07-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-08-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-09-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-10-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-11-01')},
{'amount': 100.0 - 75.00, 'date': fields.Date.to_date('2025-12-01')},
]
self.assertRecordValues(budget.item_ids, expected_items)
def test_budget_filter_with_percentage_figure_type(self):
"""
Test that budget filters don't crash when a report has lines with percentage
figure type that cannot be matched for budget comparison.
"""
report_with_percentage = self.env['account.report'].create({
'name': "Report with Percentage Line",
'filter_date_range': True,
'filter_budgets': True,
'root_report_id': self.env.ref('account_reports.profit_and_loss').id,
'column_ids': [
Command.create({
'name': "Balance",
'expression_label': 'balance',
}),
],
'line_ids': [
Command.create({
'name': 'percentage_line',
'expression_ids': [
Command.create({
'label': 'balance',
'formula': '100',
'engine': 'external',
'figure_type': 'percentage',
}),
],
}),
Command.create({
'name': 'monetary_line',
'groupby': 'account_id',
'foldability': 'always_unfolded',
'expression_ids': [
Command.create({
'label': 'balance',
'formula': "[('account_id.account_type', '=', 'income')]",
'subformula': 'sum',
'engine': 'domain',
}),
],
}),
],
})
self._create_moves(
{self.account_1.id: 100},
'2020-01-01',
'2020-01-01',
)
options = self._generate_options(
report_with_percentage,
'2020-01-01',
'2020-12-31',
default_options={'budgets': [{'id': self.budget_1.id, 'selected': True}]},
)
lines = report_with_percentage._get_lines(options)
self.assertTrue(lines)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,252 @@
from odoo import Command
from odoo.tests import tagged
from .common import TestAccountReportsCommon
@tagged('post_install', '-at_install')
class TestCTA(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.company_data['company'].write({'name': "USD Company", 'sequence': 1, 'totals_below_sections': False})
cls.company_data_2['company'].write({'name': 'CAD Company', 'sequence': 2, 'totals_below_sections': False})
cad = cls.env.ref('base.CAD')
cls.env['res.currency.rate'].search([]).unlink()
cls.env['res.currency.rate'].create([
{'name': '2025-01-01', 'rate': 1.1, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.9090909091
{'name': '2025-02-01', 'rate': 1.2, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.8333333333
{'name': '2025-03-01', 'rate': 1.3, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.7692307692
{'name': '2025-04-01', 'rate': 1.4, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.7142857143
{'name': '2025-05-01', 'rate': 1.5, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.6666666667
{'name': '2025-06-01', 'rate': 1.6, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.625
{'name': '2025-07-01', 'rate': 1.7, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.5882352941
{'name': '2025-08-01', 'rate': 1.8, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.5555555556
{'name': '2025-09-01', 'rate': 1.9, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.5263157895
{'name': '2025-10-01', 'rate': 2.0, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.5
{'name': '2025-11-01', 'rate': 2.1, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.4761904762
{'name': '2025-12-01', 'rate': 2.2, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.4545454545
{'name': '2026-01-01', 'rate': 2.3, 'currency_id': cad.id, 'company_id': cls.company_data['company'].id}, # inverse: 0.4347826087
])
current_year_earning_account = cls.company_data_2['company'].get_unaffected_earnings_account()
equity_account = cls.env['account.account'].search([
*cls.env['account.account']._check_company_domain(cls.company_data_2['company']),
('account_type', '=', 'equity'),
], limit=1)
cls.moves = cls.env['account.move'].with_company(cls.company_data_2['company']).create([{
'date': '2025-10-10',
'line_ids': [
Command.create({
'account_id': cls.company_data_2['default_account_expense'].id,
'balance': 3000.0, # average rate 0.633781251663689
}),
Command.create({
'account_id': cls.company_data_2['default_account_deferred_expense'].id,
'balance': 450.0, # closing rate 0.4545454545
}),
Command.create({
'account_id': cls.company_data_2['default_account_payable'].id,
'balance': -3450.0, # closing rate 0.4545454545
}),
],
}, {
'date': '2025-10-10',
'line_ids': [
Command.create({
'account_id': cls.company_data_2['default_account_revenue'].id,
'balance': -10000.0, # average rate 0.633781251663689
}),
Command.create({
'account_id': cls.company_data_2['default_account_deferred_revenue'].id,
'balance': -1500.0, # closing rate 0.4545454545
}),
Command.create({
'account_id': cls.company_data_2['default_account_receivable'].id,
'balance': 11500.0, # closing rate 0.4545454545
}),
],
}, {
'date': '2025-12-31',
'line_ids': [
Command.create({
'account_id': current_year_earning_account.id,
'balance': 6000.0, # average rate 0.633781251663689
}),
Command.create({
'account_id': equity_account.id,
'balance': -6000.0, # historic rate 0.4545454545
}),
],
}, {
'date': '2025-12-31',
'line_ids': [
Command.create({
'account_id': current_year_earning_account.id,
'balance': 1000.0, # average rate 0.633781251663689
}),
Command.create({
'account_id': equity_account.id,
'balance': -1000.0, # historic rate 0.4545454545
}),
],
}, {
'date': '2025-06-02',
'line_ids': [
Command.create({
'account_id': cls.company_data_2['default_journal_bank'].default_account_id.id,
'balance': 2000.0, # closing rate 0.4545454545
}),
Command.create({
'account_id': equity_account.id,
'balance': -2000.0, # historic rate 0.625
}),
],
}])
cls.moves.action_post()
def test_cta_value(self):
self.assertRecordValues(self.moves.line_ids.with_context(
date_from='2025-01-01',
date_to='2025-12-31',
allowed_company_ids=[self.company_data['company'].id, self.company_data_2['company'].id],
currency_translation='cta',
), [
{'consolidation_rate': 0.6337812516636894, 'consolidation_balance': 1901.34, 'cta_value': 537.70},
{'consolidation_rate': 0.45454545454545453, 'consolidation_balance': 204.55, 'cta_value': 0.00},
{'consolidation_rate': 0.45454545454545453, 'consolidation_balance': -1568.18, 'cta_value': 0.00},
{'consolidation_rate': 0.6337812516636894, 'consolidation_balance': -6337.81, 'cta_value': -1792.36},
{'consolidation_rate': 0.45454545454545453, 'consolidation_balance': -681.82, 'cta_value': 0.00},
{'consolidation_rate': 0.45454545454545453, 'consolidation_balance': 5227.27, 'cta_value': 0.00},
{'consolidation_rate': 0.6337812516636894, 'consolidation_balance': 3802.69, 'cta_value': 1075.42},
{'consolidation_rate': 0.45454545454545453, 'consolidation_balance': -2727.27, 'cta_value': 0.00},
{'consolidation_rate': 0.6337812516636894, 'consolidation_balance': 633.78, 'cta_value': 179.23},
{'consolidation_rate': 0.45454545454545453, 'consolidation_balance': -454.55, 'cta_value': 0.00},
{'consolidation_rate': 0.45454545454545453, 'consolidation_balance': 909.09, 'cta_value': 0.00},
{'consolidation_rate': 0.62500000000000000, 'consolidation_balance': -1250.00, 'cta_value': -340.91},
])
def test_cta_in_balance_sheet(self):
report = self.env.ref("account_reports.balance_sheet")
options = self._generate_options(report, '2025-01-01', '2025-12-31')
self.assertLinesValues(
report._get_lines(options),
# Name Balance RATE
[0, 1],
[
('ASSETS', 6340.91),
('Current Assets', 6340.91),
('Bank and Cash Accounts', 909.09), # closing: 2000 * 0.454545
('Receivables', 5227.27), # closing: 11500 * 0.454545
('Current Assets', 204.55), # closing: 450 * 0.454545
('Prepayments', 0.00),
('Fixed Assets', 0.00),
('Non-current Assets', 0.00),
('LIABILITIES', 2250.00),
('Current Liabilities', 2250.00),
('Current Liabilities', 681.82), # closing: 1500 * 0.454545
('Credit Card', 0.00),
('Payables', 1568.18), # closing: 3450 * 0.454545
('Non-current Liabilities', 0.00),
('EQUITY (& EARNINGS)', 4090.91),
('Equity', 4431.82), # historical: 6000 * 0.454545 + 1000 * 0.454545 + 2000 * 0.625000
('Earnings', 0.00),
('Current Year Unallocated Earnings', 0.00),
('Previous Years Earnings', 0.00),
('Other Comprehensive Income', -340.91),
('Cumulative Translation Adjustments', -340.91),
('LIABILITIES + EQUITY', 6340.91),
],
options,
)
options = self._generate_options(report, '2025-01-01', '2025-10-31')
# Average rate for period 1/1/25 --> 31/10/25 = 0.66766103075
self.assertLinesValues(
report._get_lines(options),
# Name Balance RATE
[0, 1],
[
('ASSETS', 6975.00),
('Current Assets', 6975.00),
('Bank and Cash Accounts', 1000.00), # closing: 2000 * 0.5
('Receivables', 5750.00), # closing: 11500 * 0.5
('Current Assets', 225.00), # closing: 450 * 0.5
('Prepayments', 0.00),
('Fixed Assets', 0.00),
('Non-current Assets', 0.00),
('LIABILITIES', 2475.00),
('Current Liabilities', 2475.00),
('Current Liabilities', 750.00), # closing: 1500 * 0.5
('Credit Card', 0.00),
('Payables', 1725.00), # closing: 3450 * 0.5
('Non-current Liabilities', 0.00),
('EQUITY (& EARNINGS)', 4500.00),
('Equity', 1250.00), # historical: 2000 * 0.625000
('Earnings', 4673.27),
('Current Year Unallocated Earnings', 4673.27),
('Previous Years Earnings', 0.00),
('Other Comprehensive Income', -1423.27),
('Cumulative Translation Adjustments', -1423.27),
('LIABILITIES + EQUITY', 6975.00),
],
options,
)
def test_cta_in_trial_balance(self):
report = self.env.ref("account_reports.trial_balance_report")
options = self._generate_options(report, '2025-01-01', '2025-12-31')
self.assertLinesValues(
report._get_lines(options),
# Name Initial Balance Debit Credit End Balance
[0, 1, 2, 3, 4],
[
('Bank', 0.0, 909.09, 0.0, 909.09),
('Current Assets', 0.0, 204.55, 0.0, 204.55),
('Accounts Receivable', 0.0, 5227.27, 0.0, 5227.27),
('Capital', 0.0, 0.0, 4431.82, -4431.82),
('Accumulated Retained Earnings', 0.0, 4436.47, 0.0, 4436.47),
('Expenses', 0.0, 1901.34, 0.0, 1901.34),
('Product Sales', 0.0, 0.0, 6337.81, -6337.81),
('Current Liabilities', 0.0, 0.0, 681.82, -681.82),
('Accounts Payable', 0.0, 0.0, 1568.18, -1568.18),
('Cumulative Translation Adjustments', 0.0, 340.91, 0.0, 340.91),
('Total', 0.0, 13019.63, 13019.63, 0.0),
],
options,
)
def test_cta_in_general_ledger(self):
report = self.env.ref("account_reports.general_ledger_report")
options = self._generate_options(report, '2025-01-01', '2025-12-31')
self.assertLinesValues(
report._get_lines(options),
# Name Debit Credit Balance
[0, 4, 5, 6],
[
('Bank', 909.09, 0.0, 909.09),
('Current Assets', 204.55, 0.0, 204.55),
('Accounts Receivable', 5227.27, 0.0, 5227.27),
('Capital', 0.0, 4431.82, -4431.82),
('Accumulated Retained Earnings', 4436.47, 0.0, 4436.47),
('Expenses', 1901.34, 0.0, 1901.34),
('Product Sales', 0.0, 6337.81, -6337.81),
('Current Liabilities', 0.0, 681.82, -681.82),
('Accounts Payable', 0.0, 1568.18, -1568.18),
('Cumulative Translation Adjustments', 340.91, 0.0, 340.91),
('Total General Ledger', 13019.63, 13019.63, 0.0),
],
options,
)

View File

@@ -0,0 +1,545 @@
from odoo import Command
from odoo.tests import tagged
from .common import TestAccountReportsCommon
@tagged('post_install', '-at_install')
class TestCurrencyTable(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.company_data['company'].write({'name': "USD Company 1", 'sequence': 1, 'totals_below_sections': False})
cls.company_usd_data = cls.company_data
# Create additional companies (also adding them to env.companies)
cls.company_usd_data_2 = cls.setup_other_company(name="USD Company 2", sequence=2, currency_id=cls.env.ref('base.USD').id)
cls.company_eur_data = cls.setup_other_company(name="EUR Company 1", sequence=3, currency_id=cls.env.ref('base.EUR').id)
cls.company_eur_data_2 = cls.setup_other_company(name="EUR Company 2", sequence=4, currency_id=cls.env.ref('base.EUR').id)
cls.company_chf_data = cls.setup_other_company(name="CHF Company", sequence=5, currency_id=cls.env.ref('base.CHF').id)
cls.company_mxn_data = cls.setup_other_company(name="MXN Company", sequence=5, currency_id=cls.env.ref('base.MXN').id)
# Add equity account to the company data
for company_data in (cls.company_usd_data, cls.company_usd_data_2, cls.company_eur_data, cls.company_eur_data_2, cls.company_chf_data, cls.company_mxn_data):
company_data['equity_account'] = cls.env['account.account'].search([
('company_ids', '=', company_data['company'].id),
('account_type', '=', 'equity'),
], limit=1)
cls.report = cls.env['account.report'].create({
'name': "Currency Table Test",
'filter_multi_company': 'selector',
'currency_translation': 'cta',
'groupby': 'company_id',
'column_ids': [Command.create({'name': "Balance", 'expression_label': 'balance'})],
'line_ids': [
Command.create({
'name': "Asset",
'foldability': 'always_unfolded',
'expression_ids': [
Command.create({
'label': 'balance',
'engine': 'domain',
'formula': "[('account_id.internal_group', '=', 'asset')]",
'subformula': "sum",
}),
],
}),
Command.create({
'name': "Income",
'foldability': 'always_unfolded',
'expression_ids': [
Command.create({
'label': 'balance',
'engine': 'domain',
'formula': "[('account_id.internal_group', '=', 'income')]",
'subformula': "sum",
}),
],
}),
Command.create({
'name': "Equity",
'foldability': 'always_unfolded',
'expression_ids': [
Command.create({
'label': 'balance',
'engine': 'domain',
'formula': "[('account_id.internal_group', '=', 'equity')]",
'subformula': "sum",
}),
],
}),
],
})
def _generate_equity_move(self, company_data, date, amount):
rslt = self.env['account.move'].create({
'company_id': company_data['company'].id,
'date': date,
'line_ids': [
Command.create({
'debit': 0,
'credit': amount,
'account_id': company_data['default_account_expense'].id,
}),
Command.create({
'debit': amount,
'credit': 0,
'account_id': company_data['equity_account'].id,
}),
],
})
rslt.action_post()
return rslt
def test_currency_table_multicurrency(self):
# USD OPERATIONS (domestic currency)
self.init_invoice('out_invoice', company=self.company_usd_data['company'], invoice_date='2020-05-12', amounts=[10], post=True)
self.init_invoice('out_invoice', company=self.company_usd_data_2['company'], invoice_date='2020-08-23', amounts=[25], post=True)
self._generate_equity_move(self.company_usd_data, '2020-11-11', 42)
self._generate_equity_move(self.company_usd_data, '2020-12-01', 88)
self._generate_equity_move(self.company_usd_data_2, '2020-02-01', 11)
# EUR OPERATIONS
self.setup_other_currency('EUR', rates=[('2018-10-10', 7), ('2019-12-22', 11), ('2020-01-01', 2), ('2020-03-12', 5), ('2020-03-30', 20), ('2020-04-01', 4)])
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-01-15', amounts=[23], post=True)
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-02-20', amounts=[64], post=True)
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-03-30', amounts=[100], post=True)
equity_unaffected_account = self.env['account.account'].search(
[
('account_type', '=', 'equity_unaffected'),
*self.env['account.account']._check_company_domain(self.company_eur_data['company']),
], limit=1,
)
self.env['account.move'].create(
{
'date': '2020-02-15',
'company_id': self.company_eur_data['company'].id,
'line_ids': [
Command.create({'account_id': equity_unaffected_account.id, 'debit': 100.0}),
Command.create({'account_id': self.company_eur_data['default_account_receivable'].id, 'credit': 100.0}),
],
},
).action_post()
self._generate_equity_move(self.company_eur_data, '2020-03-15', 20)
self._generate_equity_move(self.company_eur_data, '2020-03-31', 5)
self.init_invoice('out_invoice', company=self.company_eur_data_2['company'], invoice_date='2020-03-14', amounts=[54], post=True)
self.init_invoice('out_invoice', company=self.company_eur_data_2['company'], invoice_date='2020-04-10', amounts=[77], post=True)
self._generate_equity_move(self.company_eur_data_2, '2020-05-21', 40)
# CHF OPERATIONS
self.setup_other_currency('CHF', rates=[('2018-03-01', 10), ('2019-01-01', 3), ('2020-03-30', 7), ('2020-05-10', 8), ('2020-12-25', 2), ('2020-12-31', 4)])
self.init_invoice('out_invoice', company=self.company_chf_data['company'], invoice_date='2020-01-16', amounts=[58], post=True)
self.init_invoice('out_invoice', company=self.company_chf_data['company'], invoice_date='2020-05-01', amounts=[99], post=True)
self.init_invoice('out_invoice', company=self.company_chf_data['company'], invoice_date='2020-12-31', amounts=[22], post=True)
self._generate_equity_move(self.company_chf_data, '2020-03-15', 20)
# MXN OPERATIONS
self.setup_other_currency('MXN', rates=[('2020-05-09', 1), ('2020-05-10', 2)])
self.init_invoice('out_invoice', company=self.company_mxn_data['company'], invoice_date='2020-01-01', amounts=[10], post=True)
self.init_invoice('out_invoice', company=self.company_mxn_data['company'], invoice_date='2020-07-01', amounts=[21], post=True)
self._generate_equity_move(self.company_mxn_data, '2020-03-15', 2)
# Test conversion : date range cta
self.report.currency_translation = 'cta'
cta_options_range = self._generate_options(self.report, '2019-12-22', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(cta_options_range),
[ 0, 1],
[
("Asset", 149.75),
("USD Company 1", 10.00),
("USD Company 2", 25.00),
# EUR current rate = 1/4
("EUR Company 1", 21.75), # (23 + 64 + 100 - 100) / 4
("EUR Company 2", 32.75), # (54 + 77) / 4
# CHF current rate = 1/4
("CHF Company", 44.75), # (58 + 99 + 22) / 4
("MXN Company", 15.50), # (10 + 21) / 2
("Income", -182.01),
("USD Company 1", -10.00),
("USD Company 2", -25.00),
# EUR average rate = (1/11 * 10 + 1/2 * 71 + 1/5 * 18 + 1/20 * 2 + 1/4 * 275) / 376 = 0.289518859
("EUR Company 1", -54.14), # (-23 - 64 - 100) * 0.289518859
("EUR Company 2", -37.93), # (-54 - 77) * 0.289518859
# CHF average rate = (1/3 * 99 + 1/7 * 41 + 1/8 * 229 + 1/2 * 6 + 1/4) / 376 = 0.188117401
("CHF Company", -33.67), # (-58 - 99 -22) * 0.188117401
# MXN average rate = (1 * 140 + 1/2 * 236) / 376 = 0.686170213
("MXN Company", -21.27), # (-10 - 21) * 0.686170213
("Equity", 192.87),
("USD Company 1", 130.00),
("USD Company 2", 11.00),
("EUR Company 1", 33.20), # 20 / 5 + 5 / 20 + 100 * 0.289518859
("EUR Company 2", 10.00), # 40 / 4
("CHF Company", 6.67), # 20 / 3
("MXN Company", 2.00), # 2 / 1
],
cta_options_range,
)
# Test conversion : single cta
self.report.currency_translation = 'cta'
self.report.filter_date_range = False
cta_options_single = self._generate_options(self.report, '2020-12-31', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(cta_options_single),
[ 0, 1],
[
("Asset", 149.75),
("USD Company 1", 10.00),
("USD Company 2", 25.00),
# EUR current rate = 1/4
("EUR Company 1", 21.75), # (23 + 64 + 100 - 100) / 4
("EUR Company 2", 32.75), # (54 + 77) / 4
# CHF current rate = 1/4
("CHF Company", 44.75), # (58 + 99 + 22) / 4
# MXN current rate = 1/2
("MXN Company", 15.50), # (10 + 21) / 2
("Income", -182.76),
("USD Company 1", -10.00),
("USD Company 2", -25.00),
# EUR average rate = (1/2 * 71 + 1/5 * 18 + 1/20 * 2 + 1/4 * 275) / 366 = 0.294945355
("EUR Company 1", -55.15), # (-23 - 64 - 100) * 0.294945355
("EUR Company 2", -38.64), # (-54 - 77) * 0.294945355
# CHF average rate = (1/3 * 89 + 1/7 * 41 + 1/8 * 229 + 1/2 * 6 + 1/4) / 366 = 0.184149753
("CHF Company", -32.96), # (-58 - 99 -22) * 0.184149753
# MXN average rate = (1 * 130 + 1/2 * 236) / 366 = 0.677595628
("MXN Company", -21.01), # (-10 - 21) * 0.677595628
("Equity", 193.41),
("USD Company 1", 130.00),
("USD Company 2", 11.00),
("EUR Company 1", 33.74), # 20 / 5 + 5 / 20 + 100 * 0.294945355
("EUR Company 2", 10.00), # 40 / 4
("CHF Company", 6.67), # 20 / 3
("MXN Company", 2.00), # 2 / 1
],
cta_options_single,
)
# Test conversion : current : date range and single
current_expected_lines = [
# EUR current rate = 1/4
# CHF current rate = 1/4
("Asset", 149.75),
("USD Company 1", 10.00),
("USD Company 2", 25.00),
("EUR Company 1", 21.75), # (23 + 64 + 100 - 100) / 4
("EUR Company 2", 32.75), # (54 + 77) / 4
("CHF Company", 44.75), # (58 + 99 + 22) / 4
("MXN Company", 15.50), # (10 + 21) / 2
("Income", -174.75),
("USD Company 1", -10.00),
("USD Company 2", -25.00),
("EUR Company 1", -46.75), # (-23 - 64 - 100) / 4
("EUR Company 2", -32.75), # (-54 - 77) / 4
("CHF Company", -44.75), # (-58 - 99 -22) / 4
("MXN Company", -15.50), # (-10 - 21) / 2
("Equity", 188.25),
("USD Company 1", 130.00),
("USD Company 2", 11.00),
("EUR Company 1", 31.25), # (20 + 5 + 100) / 4
("EUR Company 2", 10.00), # 40 / 4
("CHF Company", 5.00), # 20 / 4
("MXN Company", 1.00), # 2 / 2
]
self.report.currency_translation = 'current'
current_options_range = self._generate_options(self.report, '2020-01-01', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(current_options_range),
[0, 1],
current_expected_lines,
current_options_range,
)
self.report.filter_date_range = False
current_options_single = self._generate_options(self.report, '2020-12-31', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(current_options_single),
[0, 1],
current_expected_lines,
current_options_single,
)
def test_currency_table_monocurrency(self):
self.init_invoice('out_invoice', company=self.company_usd_data['company'], invoice_date='2020-01-01', amounts=[63], post=True)
self.init_invoice('out_invoice', company=self.company_usd_data_2['company'], invoice_date='2020-01-01', amounts=[42], post=True)
self._generate_equity_move(self.company_usd_data, '2020-11-11', 88)
self._generate_equity_move(self.company_usd_data_2, '2020-11-11', 92)
companies = self.company_usd_data['company'] + self.company_usd_data_2['company']
self.env = self.env(context=dict(self.env.context, allowed_company_ids=companies.ids))
options = self._generate_options(self.report, '2020-01-01', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1],
[
("Asset", 105.00),
("USD Company 1", 63.00),
("USD Company 2", 42.00),
("Income", -105.00),
("USD Company 1", -63.00),
("USD Company 2", -42.00),
("Equity", 180.00),
("USD Company 1", 88.00),
("USD Company 2", 92.00),
],
options,
)
def test_currency_table_comparison(self):
# EUR operations
self.setup_other_currency('EUR', rates=[('2018-01-01', 7), ('2019-01-01', 2), ('2020-03-12', 5), ('2021-03-30', 20), ('2022-04-01', 4)])
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2019-01-01', amounts=[14], post=True)
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-01-01', amounts=[24], post=True)
self._generate_equity_move(self.company_eur_data, '2019-11-11', 55)
self._generate_equity_move(self.company_eur_data, '2020-11-11', 99)
# CHF operations
self.setup_other_currency('CHF', rates=[('2018-01-01', 10), ('2019-01-01', 4), ('2019-03-12', 5), ('2021-03-30', 20), ('2022-04-01', 4)])
self.init_invoice('out_invoice', company=self.company_chf_data['company'], invoice_date='2019-01-01', amounts=[20], post=True)
self.init_invoice('out_invoice', company=self.company_chf_data['company'], invoice_date='2020-01-01', amounts=[66], post=True)
self._generate_equity_move(self.company_chf_data, '2019-11-11', 12)
self._generate_equity_move(self.company_chf_data, '2020-11-11', 84)
options = self._generate_options(self.report, '2020-01-01', '2020-12-31')
options = self._update_comparison_filter(options, self.report, 'previous_period', 1)
self.assertLinesValues(
self.report._get_lines(options),
# 2020 2019
[ 0, 1, 2],
[
("Asset", 18.00, 11.00),
# EUR current rate: 2020 = 1/5 ; 2019 = 1/2
("EUR Company 1", 4.80, 7.00),
# CHF current rate: 2020 = 1/5 ; 2019 = 1/5
("CHF Company", 13.20, 4.00),
("Income", -19.40, -11.19),
# EUR average rate in 2020: (1/2 * 71 + 1/5 * 295) / 366 = 0.258196721
# EUR average rate in 2019: 1/2
("EUR Company 1", -6.20, -7.00),
# CHF average rate in 2020: 1/5
# CHF average rate in 2019: (1/4 * 70 + 1/5 * 295) / 365 = 0.209589041
("CHF Company", -13.20, -4.19),
("Equity", 36.60, 29.90),
("EUR Company 1", 19.80, 27.50),
("CHF Company", 16.80, 2.40),
],
options,
)
def test_currency_table_branches(self):
usd_branch_data = self.setup_other_company(
name='USD Branch',
parent_id=self.company_usd_data['company'].id,
sequence=self.company_usd_data['company'].sequence,
)
eur_branch_data = self.setup_other_company(
name='EUR Branch',
parent_id=self.company_eur_data['company'].id,
sequence=self.company_eur_data['company'].sequence,
)
usd_branch_data['company'].totals_below_sections = False
# Add equity accounts to branch data
usd_branch_data['equity_account'] = self.company_usd_data['equity_account']
eur_branch_data['equity_account'] = self.company_eur_data['equity_account']
# Create rates on the root USD company
self.setup_other_currency('EUR', rates=[('2020-01-01', 4), ('2020-03-01', 2), ('2020-12-01', 5)])
# Create some entries
self.init_invoice('out_invoice', company=self.company_usd_data['company'], invoice_date='2020-11-01', amounts=[10], post=True)
self.init_invoice('out_invoice', company=usd_branch_data['company'], invoice_date='2020-09-01', amounts=[20], post=True)
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-06-25', amounts=[30], post=True)
self.init_invoice('out_invoice', company=eur_branch_data['company'], invoice_date='2020-02-23', amounts=[40], post=True)
self._generate_equity_move(self.company_usd_data, '2020-11-12', 50)
self._generate_equity_move(usd_branch_data, '2020-01-21', 60)
self._generate_equity_move(self.company_eur_data, '2020-05-12', 70)
self._generate_equity_move(eur_branch_data, '2020-09-09', 80)
# env.company becomes the USD branch
companies = usd_branch_data['company'] + eur_branch_data['company'] + self.company_usd_data['company'] + self.company_eur_data['company']
self.env = self.env(context=dict(self.env.context, allowed_company_ids=companies.ids))
self.report = self.report.with_env(self.env)
options = self._generate_options(self.report, '2020-01-01', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1],
[
("Asset", 44.00),
("USD Branch", 20.00),
("USD Company 1", 10.00),
# EUR current rate = 1/5
("EUR Branch", 8.00),
("EUR Company 1", 6.00),
("Income", -60.35),
("USD Branch", -20.00),
("USD Company 1", -10.00),
# EUR average rate = (1/4 * 60 + 1/2 * 275 + 1/5 * 31) / 366 = 0.433606557
("EUR Branch", -17.34),
("EUR Company 1", -13.01),
("Equity", 185.00),
("USD Branch", 60.00),
("USD Company 1", 50.00),
("EUR Branch", 40.00),
("EUR Company 1", 35.00),
],
options,
)
def test_currency_table_no_rate(self):
self.init_invoice('out_invoice', company=self.company_usd_data['company'], invoice_date='2020-11-01', amounts=[10], post=True)
self._generate_equity_move(self.company_usd_data, '2020-11-12', 20)
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-02-23', amounts=[30], post=True)
self._generate_equity_move(self.company_eur_data, '2020-05-12', 40)
options = self._generate_options(self.report, '2020-01-01', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1],
[
("Asset", 40.00),
("USD Company 1", 10.00),
("EUR Company 1", 30.00),
("Income", -40.00),
("USD Company 1", -10.00),
("EUR Company 1", -30.00),
("Equity", 60.00),
("USD Company 1", 20.00),
("EUR Company 1", 40.00),
],
options,
)
def test_currency_table_non_1_domestic_rate(self):
self.setup_other_currency('USD', rates=[('2019-12-31', 0.5)])
self.setup_other_currency('EUR', rates=[('2019-12-31', 4), ('2020-02-29', 2), ('2020-11-30', 5)])
self.init_invoice('out_invoice', company=self.company_usd_data['company'], invoice_date='2020-11-01', amounts=[10], post=True)
self._generate_equity_move(self.company_usd_data, '2020-11-12', 20)
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-02-23', amounts=[30], post=True)
self._generate_equity_move(self.company_eur_data, '2020-05-12', 40)
options = self._generate_options(self.report, '2020-01-01', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1],
[
("Asset", 13.00),
("USD Company 1", 10.00),
# EUR current rate = 0.5/5
("EUR Company 1", 3.00),
("Income", -16.50),
("USD Company 1", -10.00),
# EUR average rate = (0.5/4 * 60 + 0.5/2 * 275 + 0.5/5 * 31) / 366 = 0.216803279
("EUR Company 1", -6.50),
("Equity", 30.00),
("USD Company 1", 20.00),
("EUR Company 1", 10.00), # rate = 0.5/2
],
options,
)
def test_currency_table_cta_account_types(self):
# Scenario 1: stable domestic (USD) rate (implicit factor = 1 throughout)
# EUR rate=2 from Jan 1 to Jun 30 → 182 days at factor 1/2
# EUR rate=4 from Jul 1 to Dec 31 → 184 days at factor 1/4
# Current rate at 2020-12-31: 1/4
# Average rate: (1/2 * 182 + 1/4 * 184) / 366 = 137/366 ≈ 0.37432
self.setup_other_currency('EUR', rates=[('2020-01-01', 2), ('2020-07-01', 4)])
# Invoices: debit receivable (asset) + credit revenue (income)
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-03-01', amounts=[120], post=True)
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-10-01', amounts=[80], post=True)
# Equity moves: translated at the historical rate (the rate in effect on the transaction date)
self._generate_equity_move(self.company_eur_data, '2020-03-01', 40) # EUR rate=2 → 40/2 = 20.00
self._generate_equity_move(self.company_eur_data, '2020-10-01', 60) # EUR rate=4 → 60/4 = 15.00
self.report.currency_translation = 'cta'
options = self._generate_options(self.report, '2020-01-01', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1],
[
# Asset: current rate = 1/4
("Asset", 50.00), # (120 + 80) / 4
("EUR Company 1", 50.00),
# Income: average rate = 137/366 ≈ 0.37432
("Income", -74.86), # -(120 + 80) * 137/366
("EUR Company 1", -74.86),
# Equity: historical rate at transaction date
("Equity", 35.00), # 40/2 + 60/4 = 20 + 15
("EUR Company 1", 35.00),
],
options,
)
# Scenario 2: fluctuating domestic (USD) rate
# USD rate=1 from Jan 1 to Jun 30, USD rate=3 from Jul 1 to Dec 31
# EUR rates unchanged: 2 from Jan 1, 4 from Jul 1
#
# Conversion factors (= USD_rate / EUR_rate):
# Jan 1 - Jun 30 (182 days): 1/2 = 0.50
# Jul 1 - Dec 31 (184 days): 3/4 = 0.75
#
# Current rate at 2020-12-31: 3/4 = 0.75
# Average rate: (0.50 * 182 + 0.75 * 184) / 366 = 229/366 ≈ 0.62568
#
# historical equity rates:
# mar 1 (usd=1, eur=2): historical = 1/2 = 0.50;
# oct 1 (usd=3, eur=4): historical = 3/4 = 0.75;
self.setup_other_currency('USD', rates=[('2020-01-01', 1), ('2020-07-01', 3)])
options = self._generate_options(self.report, '2020-01-01', '2020-12-31')
self.assertLinesValues(
self.report._get_lines(options),
[ 0, 1],
[
# Asset: current rate = 3/4 = 0.75
("Asset", 150.00), # (120 + 80) * 3/4
("EUR Company 1", 150.00),
# Income: correct average rate = 229/366 ≈ 0.62568
("Income", -125.14), # -(120 + 80) * 229/366
("EUR Company 1", -125.14),
# Equity: correct historical rates per transaction date
("Equity", 65.00), # 40 * (1/2) + 60 * (3/4) = 20 + 45
("EUR Company 1", 65.00),
],
options,
)
def test_currency_manual_line_expansion(self):
self.setup_other_currency('EUR', rates=[('2019-12-31', 2)])
self.init_invoice('out_invoice', company=self.company_eur_data['company'], invoice_date='2020-12-22', amounts=[42], post=True)
self.report.line_ids.foldability = 'foldable'
options = self._generate_options(self.report, '2020-01-01', '2020-12-31')
line_to_expand_id = self.report._get_generic_line_id('account.report.line', self.report.line_ids[0].id)
self.assertLinesValues(
self.report.get_expanded_lines(options, line_to_expand_id, 'company_id', '_report_expand_unfoldable_line_with_groupby', None, None),
[ 0, 1],
[
("EUR Company 1", 21.00),
],
options,
)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,228 @@
from .common import TestAccountReportsCommon
from odoo import Command, fields
from freezegun import freeze_time
from odoo.tools import format_date
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestFollowupReport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.report = cls.env.ref('account_reports.followup_report')
# Initiate Invoices
with freeze_time('2025-10-08'):
cls.today = fields.Date.today()
invoices_data = [
# Partner A invoices
{'partner': cls.partner_a, 'amount': 100.0, 'due_date': '2025-01-01'},
{'partner': cls.partner_a, 'amount': 100.0, 'due_date': cls.today},
{'partner': cls.partner_a, 'amount': 100.0, 'due_date': '2025-01-01', 'move_type': 'out_refund'},
{'partner': cls.partner_a, 'amount': 100.0, 'due_date': '2025-01-01', 'date': '2024-12-22'},
{'partner': cls.partner_a, 'amount': 100.0, 'due_date': False, 'date': '2024-12-22'},
# Partner B invoices
{'partner': cls.partner_b, 'amount': 100.0, 'due_date': '2025-01-01'},
{'partner': cls.partner_b, 'amount': 100.0, 'due_date': cls.today},
{'partner': cls.partner_b, 'amount': 400.0, 'due_date': '2025-01-01', 'move_type': 'out_refund'},
]
cls.invoices = cls.env['account.move'].union(
cls.init_invoice(
move_type=invoice_data.get('move_type', 'out_invoice'),
partner=invoice_data['partner'],
amounts=[invoice_data['amount']],
invoice_date_due=invoice_data['due_date'],
invoice_date=invoice_data.get('invoice_date', '2025-01-01'),
)
for invoice_data in invoices_data
)
cls.formatted_today = format_date(cls.env, cls.today, date_format='MM/dd/YYY')
@classmethod
def init_invoice(cls, move_type, partner=None, invoice_date=None, post=False, products=None, amounts=None, taxes=None, company=False, currency=None, journal=None, invoice_date_due=None):
move = super().init_invoice(move_type, partner, invoice_date, False, products, amounts, taxes, company, currency, journal)
if invoice_date_due is not None:
move.invoice_payment_term_id = False
move.invoice_date_due = invoice_date_due
move.action_post()
return move
@freeze_time('2025-10-08')
def test_followup_report_unfold(self):
''' Test unfolding a line when rendering the whole report, having overdue and due sections '''
options = self._generate_options(self.report, '2025-01-01', '2025-01-31')
lines = self.report._get_lines(options)
self.assertLinesValues(
lines,
# Name Amount Resdiual
[ 0, 4, 6],
[
('Open Items', 100.0, 100.0),
('partner_a', 300.0, 300.0),
('partner_b', -200.0, -200.0),
('Total Open Items', 100.0, 100.0),
],
options
)
parent_line_id = self.report._get_generic_line_id(model_name='account.report.line', value=self.env.ref("account_reports.followup_report_line").id)
partner_a_line_id = self.report._get_generic_line_id(model_name='res.partner', value=self.partner_a.id, markup={'groupby': 'partner_id'}, parent_line_id=parent_line_id)
options['unfolded_lines'] = [partner_a_line_id]
self.assertLinesValues(
self.report._get_lines(options),
# Name Due Date Amount Resdiual
[ 0, 3, 4, 6],
[
('Open Items', '', 100.0, 100.0),
('partner_a', '', 300.0, 300.0),
('INV/2025/00001', '01/01/2025', 100.0, 100.0),
('RINV/2025/00001', '01/01/2025', -100.0, -100.0),
('INV/2025/00003', '01/01/2025', 100.0, 100.0),
('INV/2025/00002', self.formatted_today, 100.0, 100.0),
('INV/2025/00004', '', 100.0, 100.0),
('Total partner_a', '', 300.0, 300.0),
('partner_b', '', -200.0, -200.0),
('Total Open Items', '', 100.0, 100.0),
],
options
)
@freeze_time('2025-10-08')
def test_followup_report_load_more(self):
''' Test loading more lines when reaching the limit '''
self.report.load_more_limit = 2
invoices_data = [
{'amount': 100.0, 'due_date': '2024-12-03'},
{'amount': 100.0, 'due_date': self.today},
]
for invoice_data in invoices_data:
self.init_invoice(
move_type='out_invoice',
partner=self.partner_a,
amounts=[invoice_data['amount']],
invoice_date_due=invoice_data['due_date'],
invoice_date='2025-01-01',
)
options = self._generate_options(self.report, '2025-01-01', '2025-01-31')
parent_line_id = self.report._get_generic_line_id(model_name='account.report.line', value=self.env.ref("account_reports.followup_report_line").id)
partner_a_line_id = self.report._get_generic_line_id(model_name='res.partner', value=self.partner_a.id, markup={'groupby': 'partner_id'}, parent_line_id=parent_line_id)
options['unfolded_lines'] = [partner_a_line_id]
report_lines = self.report._get_lines(options)
self.assertLinesValues(
report_lines,
# Name Due Date Amount Resdiual
[ 0, 3, 4, 6],
[
('Open Items', '', 300.0, 300.0),
('partner_a', '', 500.0, 500.0),
('INV/2025/00007', '12/03/2024', 100.0, 100.0),
('INV/2025/00001', '01/01/2025', 100.0, 100.0),
('5 more', '', 300.0, 300.0),
('Total partner_a', '', 500.0, 500.0),
('partner_b', '', -200.0, -200.0),
('Total Open Items', '', 300.0, 300.0),
],
options
)
options['unfolded_lines'] = [line.id for line in report_lines if line.unfolded]
load_more_lines = self.report.get_expanded_lines(
options,
report_lines[1].id,
report_lines[5].groupby,
'_report_expand_unfoldable_line_with_groupby',
None,
None,
ignore_load_more=True,
)
self.assertLinesValues(
load_more_lines,
# Name Due Date Amount Resdiual
[ 0, 3, 4, 6],
[
('INV/2025/00007', '12/03/2024', 100.0, 100.0),
('INV/2025/00001', '01/01/2025', 100.0, 100.0),
('RINV/2025/00001', '01/01/2025', -100.0, -100.0),
('INV/2025/00003', '01/01/2025', 100.0, 100.0),
('INV/2025/00002', self.formatted_today, 100.0, 100.0),
('INV/2025/00008', self.formatted_today, 100.0, 100.0),
('INV/2025/00004', '', 100.0, 100.0),
],
options,
)
@freeze_time('2025-10-08')
def test_followup_reconciled(self):
receivable = self.partner_a.property_account_receivable_id
payment = self.env['account.move'].create([{
'partner_id': self.partner_a.id,
'line_ids': [
Command.create({
'balance': 50,
'account_id': self.company_data['default_account_revenue'].id,
}),
Command.create({
'balance': -50,
'account_id': receivable.id,
}),
],
}])
options = self._generate_options(self.report, '2025-01-01', '2025-01-31')
parent_line_id = self.report._get_generic_line_id(model_name='account.report.line', value=self.env.ref("account_reports.followup_report_line").id)
partner_a_line_id = self.report._get_generic_line_id(model_name='res.partner', value=self.partner_a.id, markup={'groupby': 'partner_id'}, parent_line_id=parent_line_id)
options['unfolded_lines'] = [partner_a_line_id]
# We display the residual amount
(self.invoices[0] + payment).line_ids.filtered(lambda l: l.account_id == receivable).reconcile()
self.assertLinesValues(
self.report._get_lines(options),
# Name Due Date Amount Resdiual
[ 0, 3, 4, 6],
[
('Open Items', '', 100.0, 50.0),
('partner_a', '', 300.0, 250.0),
('INV/2025/00001', '01/01/2025', 100.0, 50.0),
('RINV/2025/00001', '01/01/2025', -100.0, -100.0),
('INV/2025/00003', '01/01/2025', 100.0, 100.0),
('INV/2025/00002', self.formatted_today, 100.0, 100.0),
('INV/2025/00004', '', 100.0, 100.0),
('Total partner_a', '', 300.0, 250.0),
('partner_b', '', -200.0, -200.0),
('Total Open Items', '', 100.0, 50.0),
],
options
)
# Fully reconciled lines are removed from the report
(self.invoices[0] + self.invoices[2]).line_ids.filtered(lambda l: l.account_id == receivable).reconcile()
self.assertLinesValues(
self.report._get_lines(options),
# Name Due Date Amount Resdiual
[ 0, 3, 4, 6],
[
('Open Items', '', '', 50.0),
('partner_a', '', 200.0, 250.0),
('RINV/2025/00001', '01/01/2025', -100.0, -50.0),
('INV/2025/00003', '01/01/2025', 100.0, 100.0),
('INV/2025/00002', self.formatted_today, 100.0, 100.0),
('INV/2025/00004', '', 100.0, 100.0),
('Total partner_a', '', 200.0, 250.0),
('partner_b', '', -200.0, -200.0),
('Total Open Items', '', '', 50.0),
],
options
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,228 @@
from datetime import date
from .common import TestAccountReportsCommon
from odoo import fields
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestGeneralLedgerSnapshots(TestAccountReportsCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
for company in cls.env.companies:
assert not company.hard_lock_date
company.fiscalyear_lock_date = None
company.tax_lock_date = None
cls.env = cls.env(context=dict(cls.env.context, allowed_company_ids=cls.company_data['company'].ids))
# Only the General Ledger should generate snapshots in these tests
cls.env['account.report'].search([]).enable_snapshots = False
cls.report = cls.env.ref('account_reports.general_ledger_report')
cls.report.enable_snapshots = True
cls.snapshot_creation_cron = cls.env.ref('account_reports.ir_cron_create_snapshots')
cls.snapshot_garbage_collection_cron = cls.env.ref('account_reports.ir_cron_garbage_collect_snapshots')
cls.account_bank = cls.company_data['default_account_assets']
cls.account_revenue = cls.company_data['default_account_revenue']
# Entries in 2016 (initial balance)
cls.move_2016 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-06-01'),
'journal_id': cls.company_data['default_journal_misc'].id,
'line_ids': [
(0, 0, {'debit': 100.0, 'credit': 0.0, 'name': '2016_bank', 'account_id': cls.account_bank.id}),
(0, 0, {'debit': 0.0, 'credit': 100.0, 'name': '2016_revenue', 'account_id': cls.account_revenue.id}),
],
})
# Entries in 2017 (period data)
cls.move_2017 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2017-06-01'),
'journal_id': cls.company_data['default_journal_misc'].id,
'line_ids': [
(0, 0, {'debit': 50.0, 'credit': 0.0, 'name': '2017_bank', 'account_id': cls.account_bank.id}),
(0, 0, {'debit': 0.0, 'credit': 50.0, 'name': '2017_revenue', 'account_id': cls.account_revenue.id}),
],
})
(cls.move_2016 + cls.move_2017).action_post()
cls._cleanup_cron_triggers()
@classmethod
def _cleanup_cron_triggers(cls):
cls.env['ir.cron.trigger'].search([('cron_id', 'in', (cls.snapshot_garbage_collection_cron + cls.snapshot_creation_cron).ids)]).unlink()
def _run_snapshot_crons(self):
self.env['account.report.snapshot'].sudo()._cron_garbage_collect_snapshots()
while creation_trigger := self.env['ir.cron.trigger'].search([('cron_id', '=', self.snapshot_creation_cron.id)], limit=1):
creation_trigger.unlink()
self.env['account.report.snapshot'].sudo()._cron_create_snapshots()
def _get_general_ledger_snapshots(self):
return self.env['account.report.snapshot'].sudo().search([('report_id', '=', self.report.id)]).sorted(lambda snapshot: snapshot.groupby or '')
def test_general_ledger_snapshot_lifecycle(self):
"""
The General Ledger's initial balances must be snapshotted when a lock date is set,
and give the exact same report content as a full computation.
"""
options = self._generate_options(self.report, '2017-01-01', '2017-12-31')
# Fetch without snapshots
self.assertFalse(self._get_general_ledger_snapshots())
lines_without_snapshot = self.report._get_lines(options)
values_without_snapshot = [(l.name, [c.no_format for c in l.columns]) for l in lines_without_snapshot]
# Set lock date & create snapshots
self.env.company.fiscalyear_lock_date = '2016-12-31'
self._run_snapshot_crons()
snapshots = self._get_general_ledger_snapshots()
self.assertTrue(snapshots)
self.assertEqual(
[(snapshot.groupby, snapshot.date, snapshot.engine_func) for snapshot in snapshots],
[
(False, date(2016, 12, 31), '_report_engine_gl_initial_balance'),
('account_id', date(2016, 12, 31), '_report_engine_gl_initial_balance'),
],
)
# Fetch with snapshots
lines_with_snapshot = self.report._get_lines(options)
values_with_snapshot = [(l.name, [c.no_format for c in l.columns]) for l in lines_with_snapshot]
self.assertEqual(values_without_snapshot, values_with_snapshot)
# Corrupt the snapshot to prove it skips recomputation
for snapshot in snapshots.filtered(lambda s: not s.groupby):
corrupted_result = {}
for expr_key, formula_result in snapshot.result.items():
if isinstance(formula_result, list):
corrupted_list = []
for grouping_key, row_dict in formula_result:
corrupted_row = dict(row_dict)
if 'balance' in corrupted_row:
corrupted_row['balance'] = corrupted_row.get('balance', 0) + 999.0
if 'init_balance' in corrupted_row:
corrupted_row['init_balance'] = corrupted_row.get('init_balance', 0) + 999.0
corrupted_list.append((grouping_key, corrupted_row))
corrupted_result[expr_key] = corrupted_list
else:
corrupted_row = dict(formula_result)
if 'balance' in corrupted_row:
corrupted_row['balance'] = corrupted_row.get('balance', 0) + 999.0
if 'init_balance' in corrupted_row:
corrupted_row['init_balance'] = corrupted_row.get('init_balance', 0) + 999.0
corrupted_result[expr_key] = corrupted_row
snapshot.result = corrupted_result
lines_corrupted = self.report._get_lines(options)
corrupted_values = [(l.name, [c.no_format for c in l.columns]) for l in lines_corrupted]
expected_corrupted_values = []
for name, cols in values_without_snapshot:
new_cols = list(cols)
if name == 'Total General Ledger':
new_cols[-1] = (new_cols[-1] or 0.0) + 999.0
expected_corrupted_values.append((name, new_cols))
self.assertEqual(
expected_corrupted_values,
corrupted_values,
)
# Garbage collection
self.env.company.fiscalyear_lock_date = '2015-12-31'
self._run_snapshot_crons()
snapshots_after_gc = self._get_general_ledger_snapshots()
self.assertEqual(
[(snapshot.groupby, snapshot.date, snapshot.engine_func) for snapshot in snapshots_after_gc],
[
(False, date(2015, 12, 31), '_report_engine_gl_initial_balance'),
('account_id', date(2015, 12, 31), '_report_engine_gl_initial_balance'),
],
)
lines_restored = self.report._get_lines(options)
values_restored = [(l.name, [c.no_format for c in l.columns]) for l in lines_restored]
self.assertEqual(values_without_snapshot, values_restored)
def test_general_ledger_snapshot_open_period_merge(self):
"""
When a fiscal year lock date is set, the snapshot generated must align with that
lock date. Subsequent reports covering open periods must inherit their historical
initial balances directly from this cached snapshot rather than recomputing.
"""
# Create a transaction in 2025 (Locked Year) and 2026 (Open Year)
move_2025 = self.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2025-06-01'),
'journal_id': self.company_data['default_journal_misc'].id,
'line_ids': [
(0, 0, {'debit': 500.0, 'credit': 0.0, 'name': '2025_bank', 'account_id': self.account_bank.id}),
(0, 0, {'debit': 0.0, 'credit': 500.0, 'name': '2025_revenue', 'account_id': self.account_revenue.id}),
],
})
move_2026 = self.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2026-06-01'),
'journal_id': self.company_data['default_journal_misc'].id,
'line_ids': [
(0, 0, {'debit': 100.0, 'credit': 0.0, 'name': '2026_bank', 'account_id': self.account_bank.id}),
(0, 0, {'debit': 0.0, 'credit': 100.0, 'name': '2026_revenue', 'account_id': self.account_revenue.id}),
],
})
(move_2025 + move_2026).action_post()
# Lock the end of 2025 and trigger the cron
self.env.company.fiscalyear_lock_date = '2025-12-31'
self._run_snapshot_crons()
snapshots = self._get_general_ledger_snapshots()
# The latest snapshot must be dated exactly at the lock date (2025-12-31).
self.assertTrue(snapshots)
latest_snapshot_date = max(snapshots.mapped('date'))
self.assertEqual(latest_snapshot_date, date(2025, 12, 31))
# Generate the report for mid-2026
options_2026 = self._generate_options(self.report, '2026-07-01', '2026-07-31')
lines_uncorrupted = self.report._get_lines(options_2026)
values_uncorrupted = [(l.name, [c.no_format for c in l.columns]) for l in lines_uncorrupted]
# Corrupt the 2025 snapshot to prove the locked values are pulled from cache, not recomputed
snapshot_2025 = snapshots.filtered(lambda s: s.date == date(2025, 12, 31))
for snapshot in snapshot_2025:
corrupted_result = {}
for expr_key, formula_result in snapshot.result.items():
if isinstance(formula_result, list):
corrupted_list = []
for grouping_key, row_dict in formula_result:
corrupted_row = dict(row_dict)
if 'balance' in corrupted_row:
corrupted_row['balance'] = corrupted_row.get('balance', 0) + 999.0
if 'init_balance' in corrupted_row:
corrupted_row['init_balance'] = corrupted_row.get('init_balance', 0) + 999.0
corrupted_list.append((grouping_key, corrupted_row))
corrupted_result[expr_key] = corrupted_list
else:
corrupted_row = dict(formula_result)
if 'balance' in corrupted_row:
corrupted_row['balance'] = corrupted_row.get('balance', 0) + 999.0
if 'init_balance' in corrupted_row:
corrupted_row['init_balance'] = corrupted_row.get('init_balance', 0) + 999.0
corrupted_result[expr_key] = corrupted_row
snapshot.result = corrupted_result
# Generating the mid-2026 report should inherit the corrupted 2025 data
lines_corrupted = self.report._get_lines(options_2026)
values_corrupted = [(l.name, [c.no_format for c in l.columns]) for l in lines_corrupted]
self.assertNotEqual(values_uncorrupted, values_corrupted)

View File

@@ -0,0 +1,28 @@
from odoo import fields
from odoo.addons.account_reports.tests.common import TestAccountReportsCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestIntercoComparisonReport(TestAccountReportsCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.report = cls.env.ref('account_reports.interco_comparison_report')
def test_tax_lines_hidden_by_default(self):
options = self._generate_options(self.report, fields.Date.from_string('2024-01-01'), fields.Date.from_string('2024-12-31'))
self.assertTrue(options['hide_tax_lines'])
self.assertIn(('tax_line_id', '=', False), options['forced_domain'])
def test_tax_lines_shown_when_the_filter_is_unset(self):
options = self._generate_options(
self.report,
fields.Date.from_string('2024-01-01'),
fields.Date.from_string('2024-12-31'),
default_options={'hide_tax_lines': False},
)
self.assertFalse(options['hide_tax_lines'])
self.assertNotIn(('tax_line_id', '=', False), options['forced_domain'])

View File

@@ -0,0 +1,554 @@
# pylint: disable=C0326
from .common import TestAccountReportsCommon
from odoo import Command, fields
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestJournalReport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.report = cls.env.ref('account_reports.journal_report')
##############
# Bank entries
##############
cls.default_bank_journal = cls.company_data['default_journal_bank']
cls.default_sale_journal = cls.company_data['default_journal_sale']
# Entries in 2016 for company_1 to test the starting balance of bank journals.
cls.liquidity_account = cls.default_bank_journal.default_account_id
cls.move_bank_0 = cls.env['account.move'].create({
'move_type': 'entry',
'date': '2016-01-01',
'journal_id': cls.company_data['default_journal_bank'].id,
'line_ids': [
Command.create({'debit': 100.0, 'credit': 0.0, 'name': '2016_1_1', 'account_id': cls.liquidity_account.id}),
Command.create({'debit': 0.0, 'credit': 100.0, 'name': '2016_1_2', 'account_id': cls.company_data['default_account_revenue'].id}),
],
})
cls.move_bank_0.action_post()
# Entries in 2017 for company_1 to test the bank journal at current date.
cls.move_bank_1 = cls.env['account.move'].create({
'move_type': 'entry',
'date': '2017-01-01',
'journal_id': cls.company_data['default_journal_bank'].id,
'line_ids': [
Command.create({'debit': 200.0, 'credit': 0.0, 'name': '2017_1_1', 'account_id': cls.liquidity_account.id}),
Command.create({'debit': 0.0, 'credit': 200.0, 'name': '2017_1_2', 'account_id': cls.company_data['default_account_revenue'].id}),
],
})
cls.move_bank_1.action_post()
##############
# Sales entries
##############
# Invoice in 2017 for company_1 to test a sale journal at current date.
cls.move_sales_0 = cls.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': cls.partner_a.id,
'invoice_date': '2017-01-01',
'journal_id': cls.company_data['default_journal_sale'].id,
'payment_reference': 'ref123',
'invoice_line_ids': [Command.create({
'quantity': 1,
'price_unit': 3000.0,
'account_id': cls.company_data['default_account_revenue'].id,
'tax_ids': [],
})],
})
cls.move_sales_0.action_post()
# Invoice in 2017 for company_1, with foreign currency to test a sale journal at current date.
cls.other_currency = cls.setup_other_currency('EUR', rounding=0.001, rates=[('2015-12-31', 2.0), ('2016-12-31', 2.0)])
cls.move_sales_1 = cls.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': cls.partner_a.id,
'invoice_date': '2017-01-01',
'journal_id': cls.company_data['default_journal_sale'].id,
'currency_id': cls.other_currency.id,
'payment_reference': 'ref234',
'invoice_line_ids': [Command.create({
'quantity': 1,
'price_unit': 3000.0,
'account_id': cls.company_data['default_account_revenue'].id,
'tax_ids': [],
})],
})
cls.move_sales_1.action_post()
# Invoice in 2017 for company_1, with foreign currency but no ref.
cls.move_sales_2 = cls.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': cls.partner_a.id,
'invoice_date': '2017-01-01',
'journal_id': cls.company_data['default_journal_sale'].id,
'currency_id': cls.other_currency.id,
'invoice_line_ids': [Command.create({
'quantity': 1,
'price_unit': 2000.0,
'account_id': cls.company_data['default_account_revenue'].id,
'tax_ids': [],
})],
})
cls.move_sales_2.action_post()
# Set up a tax report, tax report line, and all needed to get a tax with a grid.
cls.company_data['company'].country_id = cls.env.ref('base.us')
cls.tax_report = cls.env['account.report'].create({
'name': 'Tax report',
'root_report_id': cls.env.ref('account.generic_tax_report').id,
'country_id': cls.company_data['company'].country_id.id,
'allow_foreign_vat': True,
'availability_condition': 'country',
'column_ids': [Command.create({
'name': 'Balance',
'expression_label': 'balance',
'sequence': 1,
})],
'line_ids': [Command.create({
'name': '10%',
'code': 'c10',
'sequence': 1,
'expression_ids': [Command.create({
'label': 'balance',
'engine': 'tax_tags',
'formula': '-c10',
})]
})]
})
cls.test_tax = cls.env['account.tax'].create({
'name': 'Tax 10%',
'amount': 10.0,
'amount_type': 'percent',
'type_tax_use': 'sale',
'invoice_repartition_line_ids': [
Command.create({'repartition_type': 'base'}),
Command.create({
'repartition_type': 'tax',
'tag_ids': [Command.link(cls.tax_report.line_ids.expression_ids._get_matching_tags().id)],
})]
})
# Invoice in 2017 for company_1, with taxes
cls.move_sales_3 = cls.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': cls.partner_a.id,
'invoice_date': '2017-01-01',
'payment_reference': 'ref345',
'journal_id': cls.company_data['default_journal_sale'].id,
'invoice_line_ids': [Command.create({
'quantity': 1,
'price_unit': 1500.0,
'account_id': cls.company_data['default_account_revenue'].id,
'tax_ids': [cls.test_tax.id],
})],
})
cls.move_sales_3.action_post()
cls.move_payment_0 = cls.env['account.payment'].create({
'amount': 370,
'partner_id': cls.partner_a.id,
'payment_reference': 'PBNK1/2017/00000001',
'payment_type': 'inbound',
'destination_account_id': cls.company_data['default_account_revenue'].id,
'date': '2017-01-01'
})
cls.move_payment_0.action_post()
def _filter_tax_section_lines(self, lines, exclude):
def filter_condition(line):
markup = self.report._get_markup(line.id)
return exclude ^ (isinstance(markup, str) and markup.startswith('tax_report_section'))
return list(filter(filter_condition, lines))
def assert_journal_vals_for_export(self, report, options, actual_journal_vals, expected_journals_data):
self.assertEqual(len(actual_journal_vals), len(expected_journals_data))
for actual_item, expected_item in zip(actual_journal_vals, expected_journals_data):
# Check the columns
if 'columns' in expected_item:
self.assertEqual(expected_item['columns'], [col['label'] for col in actual_item['columns']])
# Check the lines
if 'lines' in expected_item:
self.assertEqual(len(expected_item['lines']), len(actual_item['lines']))
for expected_line, actual_line in zip(expected_item['lines'], actual_item['lines']):
self.assertDictEqual(expected_line, {expected_key: actual_line.get(expected_key, {}).get('data') for expected_key in expected_line})
def test_journal_lines(self):
"""
Check the journal report lines for the journal of type sale within the first month of 2017
"""
options_2016 = self._generate_options(self.report, '2016-01-01', '2016-01-31', default_options={'unfold_all': True, 'show_payment_lines': False})
lines_2016 = self.report._get_lines(options_2016)
self.assertLinesValues(
self._filter_tax_section_lines(lines_2016, True),
[ 0, 3, 4, 5],
[
('Name', '', '', ''),
('Bank', 100, 100, ''),
('101401 Bank', 100, 0, 100),
('400000 Product Sales', 0, 100, -100),
],
options_2016,
)
tax_summary_lines_2016 = self._filter_tax_section_lines(lines_2016, False)
self.assertFalse(tax_summary_lines_2016)
options_2017 = self._generate_options(self.report, '2017-01-01', '2017-01-31', default_options={'unfold_all': True, 'show_payment_lines': False})
lines_2017 = self.report._get_lines(options_2017)
self.assertLinesValues(
self._filter_tax_section_lines(lines_2017, True),
[ 0, 3, 4, 5],
[
('Name', '', '', ''),
('Sales', 7150, 7150, ''),
('121000 Accounts Receivable', 7150, 0, 7150),
('400000 Product Sales', 0, 7150, -7150),
('Bank', 200, 200, ''),
('101401 Bank', 200, 0, 200),
('400000 Product Sales', 0, 200, -200),
],
options_2017,
)
tax_summary_lines_2017 = self._filter_tax_section_lines(lines_2017, False)
tax_tag = self.tax_report.line_ids.expression_ids._get_matching_tags()
self.assertDictEqual(
tax_summary_lines_2017[0].get_custom()['tax_grid_summary_lines'],
{'US': {'c10': {
'tag_ids': tax_tag.ids,
'balance': '$\xa0150.00',
'balance_no_format': 150.0,
'+': '$\xa0150.00',
'+_no_format': 150.0,
'-': '$\xa00.00',
'-_no_format': 0.0,
'impact': '$\xa0150.00',
}}}
)
self.assertEqual(tax_summary_lines_2017[1].name, "Global Tax Summary")
self.assertDictEqual(
tax_summary_lines_2017[2].get_custom()['tax_grid_summary_lines'],
{'US': {'c10': {
'tag_ids': tax_tag.ids,
'balance': '$\xa0150.00',
'balance_no_format': 150.0,
'+': '$\xa0150.00',
'+_no_format': 150.0,
'-': '$\xa00.00',
'-_no_format': 0.0,
'impact': '$\xa0150.00',
}}}
)
options_global = self._generate_options(self.report, '2016-01-01', '2017-01-31', default_options={'unfold_all': True, 'show_payment_lines': False})
lines_global = self.report._get_lines(options_global)
self.assertLinesValues(
self._filter_tax_section_lines(lines_global, True),
[ 0, 3, 4, 5],
[
('Name', '', '', ''),
('Sales', 7150, 7150, ''),
('121000 Accounts Receivable', 7150, 0, 7150),
('400000 Product Sales', 0, 7150, -7150),
('Bank', 300, 300, ''),
('101401 Bank', 300, 0, 300),
('400000 Product Sales', 0, 300, -300),
],
options_global,
)
tax_summary_lines_global = self._filter_tax_section_lines(lines_global, False)
self.assertDictEqual(
tax_summary_lines_global[0].get_custom()['tax_grid_summary_lines'],
{'US': {'c10': {
'tag_ids': tax_tag.ids,
'balance': '$\xa0150.00',
'balance_no_format': 150.0,
'+': '$\xa0150.00',
'+_no_format': 150.0,
'-': '$\xa00.00',
'-_no_format': 0.0,
'impact': '$\xa0150.00',
}}}
)
self.assertEqual(tax_summary_lines_global[1].name, "Global Tax Summary")
self.assertDictEqual(
tax_summary_lines_global[2].get_custom()['tax_grid_summary_lines'],
{'US': {'c10': {
'tag_ids': tax_tag.ids,
'balance': '$\xa0150.00',
'balance_no_format': 150.0,
'+': '$\xa0150.00',
'+_no_format': 150.0,
'-': '$\xa00.00',
'-_no_format': 0.0,
'impact': '$\xa0150.00',
}}}
)
def test_show_payment_lines_option(self):
"""
Check the journal report lines of the default bank journal with payments included
"""
options_no_payment = self._generate_options(self.report, '2017-01-01', '2017-01-31', default_options={'unfold_all': True, 'show_payment_lines': False})
outstanding_account_code = self.env['account.payment']._get_outstanding_account(payment_type='inbound').display_name
self.assertLinesValues(
self._filter_tax_section_lines(self.report._get_lines(options_no_payment), True),
[ 0, 3, 4, 5],
[
('Name', '', '', ''),
('Sales', 7150, 7150, ''),
('121000 Accounts Receivable', 7150, 0, 7150),
('400000 Product Sales', 0, 7150, -7150),
('Bank', 200, 200, ''),
('101401 Bank', 200, 0, 200),
('400000 Product Sales', 0, 200, -200),
],
options_no_payment,
)
options_show_payment = self._generate_options(self.report, '2017-01-01', '2017-01-31', default_options={'unfold_all': True, 'show_payment_lines': True})
self.assertLinesValues(
self._filter_tax_section_lines(self.report._get_lines(options_show_payment), True),
[ 0, 3, 4, 5],
[
('Name', '', '', ''),
('Sales', 7150, 7150, ''),
('121000 Accounts Receivable', 7150, 0, 7150),
('400000 Product Sales', 0, 7150, -7150),
('Bank', 570, 570, ''),
('101401 Bank', 200, 0, 200),
(outstanding_account_code, 370, 0, 370),
('400000 Product Sales', 0, 570, -570),
],
options_show_payment,
)
def test_document_data_basic(self):
"""
Check that the data generated by the document data generator is valid
"""
options = self._generate_options(self.report, '2017-01-01', '2017-01-31', default_options={'show_payment_lines': False})
journal_report_handler = self.env[self.report.custom_handler_model_name]
move_2_pref = self.move_sales_2.payment_reference
self.assert_journal_vals_for_export(
self.report,
options,
journal_report_handler._generate_document_data_for_export(self.report, options, 'pdf')['journals_vals'],
[
{
'id': self.default_sale_journal.id,
'columns': ['document', 'account_label', 'name', 'debit', 'credit', 'taxes', 'tax_grids'],
'lines': [
{'name': 'partner_a ref123', 'debit': '$\xa03,000.00', 'credit': '$\xa00.00'},
{'name': 'ref123', 'debit': '$\xa00.00', 'credit': '$\xa03,000.00'},
{'name': 'partner_a ref234', 'debit': '$\xa01,500.00', 'credit': '$\xa00.00'},
{'name': 'ref234', 'debit': '$\xa00.00', 'credit': '$\xa01,500.00'},
{'currency_id': self.other_currency.id, 'amount': 3000}, # Special line for multicurrency
{'name': f'partner_a {move_2_pref}', 'debit': '$\xa01,000.00', 'credit': '$\xa00.00'},
{'name': move_2_pref, 'debit': '$\xa00.00', 'credit': '$\xa01,000.00'},
{'currency_id': self.other_currency.id, 'amount': 2000}, # Special line for multicurrency
{'name': 'partner_a ref345', 'debit': '$\xa01,650.00', 'credit': '$\xa00.00'},
{'name': 'ref345', 'debit': '$\xa00.00', 'credit': '$\xa01,500.00', 'taxes': 'T: Tax 10%'},
{'name': 'Tax 10%', 'debit': '$\xa00.00', 'credit': '$\xa0150.00', 'taxes': 'B: $\xa0-1,500.00'},
{}, # Empty line
{'name': 'Total', 'debit': '$\xa07,150.00', 'credit': '$\xa07,150.00'},
],
},
{
'id': self.default_bank_journal.id,
'columns': ['document', 'account_label', 'name', 'debit', 'credit', 'balance'],
'lines': [
{'name': 'Starting Balance', 'balance': '$\xa0100.00'},
{'name': '2017_1_2', 'debit': '$\xa00.00', 'credit': '$\xa0200.00', 'balance': '$\xa0300.00'},
{}, # Empty line
{'name': 'Total', 'debit': None, 'credit': None, 'balance': '$\xa0300.00'},
],
},
],
)
def test_document_data_for_bank_journal_with_show_payment_option(self):
"""
Check that show payment affect the result of the bank journal data when this filter is changed
"""
options = self._generate_options(self.report, '2017-01-01', '2017-01-31', default_options={'show_payment_lines': True})
journal_report_handler = self.env[self.report.custom_handler_model_name]
move_2_pref = self.move_sales_2.payment_reference
self.assert_journal_vals_for_export(
self.report,
options,
journal_report_handler._generate_document_data_for_export(self.report, options, 'pdf')['journals_vals'],
[
{
'id': self.default_sale_journal.id,
'columns': ['document', 'account_label', 'name', 'debit', 'credit', 'taxes', 'tax_grids'],
'lines': [
{'name': 'partner_a ref123', 'debit': '$\xa03,000.00', 'credit': '$\xa00.00'},
{'name': 'ref123', 'debit': '$\xa00.00', 'credit': '$\xa03,000.00'},
{'name': 'partner_a ref234', 'debit': '$\xa01,500.00', 'credit': '$\xa00.00'},
{'name': 'ref234', 'debit': '$\xa00.00', 'credit': '$\xa01,500.00'},
{'currency_id': self.other_currency.id, 'amount': 3000}, # Special line for multicurrency
{'name': f'partner_a {move_2_pref}', 'debit': '$\xa01,000.00', 'credit': '$\xa00.00'},
{'name': move_2_pref, 'debit': '$\xa00.00', 'credit': '$\xa01,000.00'},
{'currency_id': self.other_currency.id, 'amount': 2000}, # Special line for multicurrency
{'name': 'partner_a ref345', 'debit': '$\xa01,650.00', 'credit': '$\xa00.00'},
{'name': 'ref345', 'debit': '$\xa00.00', 'credit': '$\xa01,500.00', 'taxes': 'T: Tax 10%'},
{'name': 'Tax 10%', 'debit': '$\xa00.00', 'credit': '$\xa0150.00', 'taxes': 'B: $\xa0-1,500.00'},
{}, # Empty line
{'name': 'Total', 'debit': '$\xa07,150.00', 'credit': '$\xa07,150.00'},
],
},
{
'id': self.default_bank_journal.id,
'columns': ['document', 'account_label', 'name', 'debit', 'credit', 'balance'],
'lines': [
{'name': 'Starting Balance', 'balance': '$\xa0100.00'},
{'name': '2017_1_2', 'debit': '$\xa00.00', 'credit': '$\xa0200.00', 'balance': '$\xa0300.00'},
# Payment
{'name': 'Manual Payment', 'debit': '$\xa0370.00', 'credit': '$\xa00.00', 'balance': None},
{'name': 'Manual Payment', 'debit': '$\xa00.00', 'credit': '$\xa0370.00', 'balance': None},
{}, # Empty line
{'name': 'Total', 'debit': None, 'credit': None, 'balance': '$\xa0300.00'},
],
},
],
)
def test_document_data_for_bank_multicurrency(self):
"""
Test that data from bank journal can support multi currency bank moves
"""
options = self._generate_options(self.report, '2017-01-01', '2017-01-31', default_options={'show_payment_lines': True})
journal_report_handler = self.env[self.report.custom_handler_model_name]
self.assert_journal_vals_for_export(
self.report,
options,
list(filter(lambda x: x['id'] == self.default_bank_journal.id, journal_report_handler._generate_document_data_for_export(self.report, options, 'pdf')['journals_vals'])),
[
{
'id': self.default_bank_journal.id,
'columns': ['document', 'account_label', 'name', 'debit', 'credit', 'balance'],
'lines': [
{'name': 'Starting Balance', 'balance': '$\xa0100.00'},
{'name': '2017_1_2', 'debit': '$\xa00.00', 'credit': '$\xa0200.00', 'balance': '$\xa0300.00'},
# Payment
{'name': 'Manual Payment', 'debit': '$\xa0370.00', 'credit': '$\xa00.00', 'balance': None},
{'name': 'Manual Payment', 'debit': '$\xa00.00', 'credit': '$\xa0370.00', 'balance': None},
{}, # Empty line
{'name': 'Total', 'debit': None, 'credit': None, 'balance': '$\xa0300.00'},
]
}
]
)
new_bank_move = self.env['account.move'].create({
'move_type': 'entry',
'date': '2017-01-01',
'journal_id': self.company_data['default_journal_bank'].id,
'currency_id': self.other_currency.id,
'line_ids': [
Command.create({
'debit': 100.0,
'credit': 0.0,
'name': '2017_1_3',
'account_id': self.liquidity_account.id,
'currency_id': self.other_currency.id,
'amount_currency': 200
}),
Command.create({
'debit': 0.0,
'credit': 100.0,
'name': '2017_1_4',
'account_id': self.company_data['default_account_revenue'].id,
'currency_id': self.other_currency.id,
'amount_currency': -200
}),
],
})
new_bank_move.action_post()
self.assert_journal_vals_for_export(
self.report,
options,
list(filter(lambda x: x['id'] == self.default_bank_journal.id, journal_report_handler._generate_document_data_for_export(self.report, options, 'pdf')['journals_vals'])),
[
{
'id': self.default_bank_journal.id,
'columns': ['document', 'account_label', 'name', 'debit', 'credit', 'balance', 'amount_currency'],
'lines': [
{'name': 'Starting Balance', 'balance': '$\xa0100.00'},
{'name': '2017_1_2', 'debit': '$\xa00.00', 'credit': '$\xa0200.00', 'balance': '$\xa0300.00'},
{'name': '2017_1_4', 'debit': '$\xa00.00', 'credit': '$\xa0100.00', 'balance': '$\xa0400.00', 'amount_currency': '200.000\xa0€'},
# Payment --
{'name': 'Manual Payment', 'debit': '$\xa0370.00', 'credit': '$\xa00.00', 'balance': None},
{'name': 'Manual Payment', 'debit': '$\xa00.00', 'credit': '$\xa0370.00', 'balance': None},
{}, # Empty line
{'name': 'Total', 'debit': None, 'credit': None, 'balance': '$\xa0400.00'}
],
},
],
)
def test_global_tax_summary_rounding_unit(self):
""" Test that Global Tax Summary applies rounding filter correctly. """
report = self.env.ref('account_reports.journal_report')
options = self._generate_options(report, '2017-01-01', '2017-01-31')
options['unfold_all'] = True
# Get tax summary lines with default formatting
lines = report._get_lines(options)
client_lines = [l.as_dict() for l in lines]
tax_lines = list(filter(lambda line: line.get('is_tax_section_line'), client_lines))
default_balance = tax_lines[0]['tax_grid_summary_lines']['US']['c10']['+']
self.assertEqual(default_balance, '$\xa0150.00') # Default: $150.00
# Test with thousands rounding unit, call via dispatch_report_action like the frontend does
options['rounding_unit'] = 'thousands'
thousands_client_lines = [l.as_dict() for l in report.dispatch_report_action(options, 'format_column_values_from_client', client_lines)]
tax_lines = list(filter(lambda line: line.get('is_tax_section_line'), thousands_client_lines))
thousands_balance = tax_lines[0]['tax_grid_summary_lines']['US']['c10']['+']
self.assertEqual(thousands_balance, '$\xa00k') # Thousands: $0k (150/1000 = 0.15 rounded to 0)

View File

@@ -0,0 +1,60 @@
from unittest.mock import patch
from odoo.tests import tagged
from odoo.tests.common import freeze_time
from odoo.addons.account_reports.tests.common import TestAccountReportsCommon
@freeze_time('2024-01-01')
@tagged('post_install', '-at_install')
class TestKpiProvider(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.company.write({
'vat': '38972223422',
'phone': '555-555-5555',
'email': 'test@example.com'
})
# The kpi are fetched for all companies, disregarding any access rules. We need to make sure no other company in the database
# contains return types that could interfere with the test.
cls.env['account.return'].sudo().search([]).active = False
cls.return_types = cls.env['account.return.type'].create([
{'name': 'Return with a report without a root report',
'report_id': cls.env.ref('account.generic_tax_report').id,
'deadline_start_date': '2024-01-01'},
{'name': 'Return with a root report',
'report_id': cls.env.ref('account_reports.followup_report').id,
'deadline_start_date': '2024-01-01'},
{'name': 'Return without a report',
'deadline_start_date': '2024-01-01'},
])
def generate_all_returns(account_return_type, country_code, main_company, tax_unit=None, return_types=None):
for return_type in cls.return_types:
return_type._try_create_returns_for_fiscal_year(main_company, tax_unit)
with patch.object(cls.registry['account.return.type'], '_generate_all_returns', generate_all_returns):
cls.env.company.account_opening_date = '2024-01-01'
def test_kpi_summary(self):
self.assertCountEqual(self.env['kpi.provider'].get_account_reports_kpi_summary(), [
{'id': 'account_return.account_generic_tax_report',
'name': 'Generic Tax report',
'type': 'return_status',
'value': 'to_do'},
{'id': 'account_return.account_reports_followup_report',
'name': 'Open Items',
'type': 'return_status',
'value': 'to_do'},
{'id': 'account_return.return_without_a_report',
'name': 'Return without a report',
'type': 'return_status',
'value': 'to_do'},
])

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,224 @@
# pylint: disable=C0326
from datetime import date
from .common import TestAccountReportsCommon
from odoo import fields
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestPartnerLedgerSnapshots(TestAccountReportsCommon):
@classmethod
def setUpClass(cls):
super().setUpClass()
for company in cls.env.companies:
assert not company.hard_lock_date # Make sure we crash if the common test setup changes in the future
company.fiscalyear_lock_date = None
company.tax_lock_date = None
# The snapshots' serialized options embed company-dependent values (e.g. the exchange journals domain);
# like the cron, evaluate everything on a single company.
cls.env = cls.env(context=dict(cls.env.context, allowed_company_ids=cls.company_data['company'].ids))
# Only the partner ledger should generate snapshots in these tests
cls.report = cls.env.ref('account_reports.partner_ledger_report')
cls.env['account.report'].search([('id', '!=', cls.report.id)]).enable_snapshots = False
# Entries in 2016, forming the initial balances of the 2017 report
cls.move_2016_a = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-01-01'),
'journal_id': cls.company_data['default_journal_misc'].id,
'line_ids': [
(0, 0, {'debit': 100.0, 'credit': 0.0, 'name': '2016_a_1', 'account_id': cls.company_data['default_account_receivable'].id, 'partner_id': cls.partner_a.id}),
(0, 0, {'debit': 0.0, 'credit': 300.0, 'name': '2016_a_2', 'account_id': cls.company_data['default_account_receivable'].id, 'partner_id': cls.partner_b.id}),
(0, 0, {'debit': 200.0, 'credit': 0.0, 'name': '2016_a_3', 'account_id': cls.company_data['default_account_revenue'].id}),
],
})
# A trade line without partner, ending up in the 'Unknown Partner' group
cls.move_2016_b = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2016-06-01'),
'journal_id': cls.company_data['default_journal_misc'].id,
'line_ids': [
(0, 0, {'debit': 0.0, 'credit': 150.0, 'name': '2016_b_1', 'account_id': cls.company_data['default_account_receivable'].id}),
(0, 0, {'debit': 150.0, 'credit': 0.0, 'name': '2016_b_2', 'account_id': cls.company_data['default_account_revenue'].id}),
],
})
# Entry in 2017, inside the reported period
cls.move_2017 = cls.env['account.move'].create({
'move_type': 'entry',
'date': fields.Date.from_string('2017-01-01'),
'journal_id': cls.company_data['default_journal_misc'].id,
'line_ids': [
(0, 0, {'debit': 1000.0, 'credit': 0.0, 'name': '2017_1', 'account_id': cls.company_data['default_account_receivable'].id, 'partner_id': cls.partner_a.id}),
(0, 0, {'debit': 0.0, 'credit': 1000.0, 'name': '2017_2', 'account_id': cls.company_data['default_account_revenue'].id}),
],
})
(cls.move_2016_a + cls.move_2016_b + cls.move_2017).action_post()
cls._cleanup_snapshot_cron_triggers()
def _get_partner_ledger_snapshots(self):
return self.env['account.report.snapshot'].sudo().search([('report_id', '=', self.report.id)]).sorted(lambda snapshot: snapshot.groupby or '')
def test_partner_ledger_snapshot_lifecycle(self):
""" The partner ledger's initial balances must be snapshotted per partner when a lock date is set, and give
the exact same report content as a full computation.
"""
options = self._generate_options(self.report, '2017-01-01', '2017-12-31')
# Without any snapshot
self.assertFalse(self._get_partner_ledger_snapshots())
self.assertLinesValues(
self.report._get_lines(options),
# Name Balance
[ 0, 9],
[
('Partner Ledger', 650.0),
('partner_a', 1100.0),
('partner_b', -300.0),
('Unknown Partner', -150.0),
('Total Partner Ledger', 650.0),
],
options,
)
# Snapshots are created at the lock date, for both the line totals and its first groupby level
self.env.company.fiscalyear_lock_date = '2016-12-31'
self._run_snapshot_crons()
snapshots = self._get_partner_ledger_snapshots()
self.assertEqual(
[(snapshot.groupby, snapshot.date, snapshot.engine_func) for snapshot in snapshots],
[
(False, date(2016, 12, 31), '_report_engine_partner_ledger_initial_balance'),
('partner_id', date(2016, 12, 31), '_report_engine_partner_ledger_initial_balance'),
],
)
# Rendering now goes through the snapshots, and must give the exact same values as the full computation
self.assertLinesValues(
self.report._get_lines(options),
# Name Balance
[ 0, 9],
[
('Partner Ledger', 650.0),
('partner_a', 1100.0),
('partner_b', -300.0),
('Unknown Partner', -150.0),
('Total Partner Ledger', 650.0),
],
options,
)
# Corrupting partner_a's snapshot must move its reported balance, proving the initial balance really comes
# from the snapshot instead of being recomputed.
partner_snapshot = snapshots.filtered(lambda snapshot: snapshot.groupby == 'partner_id')
partner_snapshot.result = {
expression_ids: [
[grouping_key, {**group_values, 'init_balance': group_values['init_balance'] + 11.0 if grouping_key == self.partner_a.id else group_values['init_balance']}]
for grouping_key, group_values in formula_result
]
for expression_ids, formula_result in partner_snapshot.result.items()
}
self.assertLinesValues(
self.report._get_lines(options),
# Name Balance
[ 0, 9],
[
('Partner Ledger', 650.0),
('partner_a', 1111.0),
('partner_b', -300.0),
('Unknown Partner', -150.0),
('Total Partner Ledger', 650.0),
],
options,
)
# Lowering the lock date garbage collects the corrupted snapshots (new ones are regenerated at the new
# lock date, covering an empty period), and the correct values come back
self.env.company.fiscalyear_lock_date = '2015-12-31'
self._run_snapshot_crons()
self.assertTrue(all(snapshot.date == date(2015, 12, 31) for snapshot in self._get_partner_ledger_snapshots()))
self.assertLinesValues(
self.report._get_lines(options),
# Name Balance
[ 0, 9],
[
('Partner Ledger', 650.0),
('partner_a', 1100.0),
('partner_b', -300.0),
('Unknown Partner', -150.0),
('Total Partner Ledger', 650.0),
],
options,
)
def test_partner_ledger_snapshot_no_partner_reconciled(self):
""" Reconciling a partner-less line with a line belonging to a partner moves its amounts to that partner,
even when the lines are in a locked, snapshotted period.
"""
options = self._generate_options(self.report, '2017-01-01', '2017-12-31')
self.env.company.fiscalyear_lock_date = '2016-12-31'
self._run_snapshot_crons()
snapshots_before = self._get_partner_ledger_snapshots()
self.assertEqual(len(snapshots_before), 2)
self.assertLinesValues(
self.report._get_lines(options),
# Name Balance
[ 0, 9],
[
('Partner Ledger', 650.0),
('partner_a', 1100.0),
('partner_b', -300.0),
('Unknown Partner', -150.0),
('Total Partner Ledger', 650.0),
],
options,
)
# Reconcile the 2016 partner-less receivable line with partner_a's 2016 receivable line
no_partner_line = self.move_2016_b.line_ids.filtered(lambda line: line.name == '2016_b_1')
partner_a_line = self.move_2016_a.line_ids.filtered(lambda line: line.name == '2016_a_1')
(no_partner_line + partner_a_line).reconcile()
# 100.0 of that unallocated credit now belongs to partner_a: it pays their 2016 receivable, lowering their
# balance to the 1000.0 of 2017, and only the unreconciled remainder stays under 'Unknown Partner'. The
# total is unchanged, the amount having merely moved between the two groups.
self.assertLinesValues(
self.report._get_lines(options),
# Name Balance
[ 0, 9],
[
('Partner Ledger', 650.0),
('partner_a', 1000.0),
('partner_b', -300.0),
('Unknown Partner', -50.0),
('Total Partner Ledger', 650.0),
],
options,
)
# The snapshots themselves are still there, unchanged
self.assertEqual(self._get_partner_ledger_snapshots(), snapshots_before)
def test_partner_ledger_snapshot_partner_merge_garbage_collection(self):
""" Merging partners rewrites the partner of the move lines without lock date protection; all snapshots
grouped by partner must then be regenerated.
"""
self.env.company.fiscalyear_lock_date = '2016-12-31'
self._run_snapshot_crons()
self.assertEqual(len(self._get_partner_ledger_snapshots()), 2)
dummy_partner_1, dummy_partner_2 = self.env['res.partner'].create([{'name': 'dummy 1'}, {'name': 'dummy 2'}])
self.env['base.partner.merge.automatic.wizard']._merge((dummy_partner_1 + dummy_partner_2).ids, dummy_partner_1)
# Only the snapshots grouped on the partners are garbage collected; the ones of the line totals are kept
remaining_snapshots = self._get_partner_ledger_snapshots()
self.assertEqual(remaining_snapshots.mapped('groupby'), [False])

View File

@@ -0,0 +1,786 @@
# pylint: disable=C0326
from .common import TestAccountReportsCommon
from odoo import Command
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestReconciliationReport(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.other_currency = cls.setup_other_currency('EUR')
cls.other_currency_2 = cls.setup_other_currency('GBP', rates=[('2015-12-31', 10.0), ('2016-12-31', 20.0)])
def test_reconciliation_report_single_currency(self):
"""
Tests the impact of positive/negative payments/statements on the reconciliation report in a single-currency
environment.
"""
bank_journal = self.env['account.journal'].create({
'name': 'Bank',
'code': 'BNKKK',
'type': 'bank',
'company_id': self.company_data['company'].id,
})
# ==== Payments ====
self.inbound_payment_method_line.journal_id = bank_journal.id
self.outbound_payment_method_line.journal_id = bank_journal.id
payments = self.env['account.payment'].create([
{
'amount': 600.0,
'payment_type': 'inbound',
'partner_type': 'customer',
'date': '2015-01-01',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'payment_method_line_id': self.inbound_payment_method_line.id,
},
{
'amount': 500.0,
'payment_type': 'outbound',
'partner_type': 'supplier',
'date': '2015-01-01',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'payment_method_line_id': self.outbound_payment_method_line.id,
},
{
'amount': 100.0,
'payment_type': 'inbound',
'partner_type': 'customer',
'date': '2015-01-02',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'payment_method_line_id': self.inbound_payment_method_line.id,
},
{
'amount': 200.0,
'payment_type': 'inbound',
'partner_type': 'customer',
'date': '2015-01-03',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'payment_method_line_id': self.inbound_payment_method_line.id,
},
{
'amount': 300.0,
'payment_type': 'outbound',
'partner_type': 'supplier',
'date': '2015-01-04',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'payment_method_line_id': self.outbound_payment_method_line.id,
},
{
'amount': 400.0,
'payment_type': 'outbound',
'partner_type': 'supplier',
'date': '2015-01-05',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'payment_method_line_id': self.outbound_payment_method_line.id,
},
])
payments.action_post()
# ==== Misc ====
self.env['account.move'].create({
'journal_id': bank_journal.id,
'date': '2014-12-31',
'line_ids': [
(0, 0, {
'name': 'Source',
'debit': 1000,
'credit': 0,
'account_id': bank_journal.default_account_id.id,
}),
(0, 0, {
'name': 'Destination',
'debit': 0,
'credit': 1000,
'account_id': self.company_data['default_account_expense'].id,
}),
]
}).action_post()
# ==== Statements ====
self.env['account.bank.statement'].create({
'name': 'statement_1',
'date': '2015-01-01',
'balance_start': 1000.0,
'balance_end_real': 1100.0,
'line_ids': [
Command.create({'payment_ref': 'line_1', 'amount': 600.0, 'date': '2015-01-01', 'journal_id': bank_journal.id}),
Command.create({'payment_ref': 'line_2', 'amount': -500.0, 'date': '2015-01-01', 'journal_id': bank_journal.id}),
],
})
statement_2 = self.env['account.bank.statement'].with_context(auto_statement_processing=True).create({
'name': 'statement_2',
'date': '2015-01-05',
'balance_start': 1100.0,
'balance_end_real': - 200.0,
'journal_id': bank_journal.id,
'line_ids': [
Command.create({'payment_ref': 'line_1', 'amount': 100.0, 'date': '2015-01-02', 'partner_id': self.partner_a.id, 'journal_id': bank_journal.id}),
Command.create({'payment_ref': 'line_2', 'amount': 200.0, 'date': '2015-01-03', 'journal_id': bank_journal.id}),
Command.create({'payment_ref': 'line_3', 'amount': -300.0, 'date': '2015-01-04', 'partner_id': self.partner_a.id, 'journal_id': bank_journal.id}),
Command.create({'payment_ref': 'line_4', 'amount': -400.0, 'date': '2015-01-05', 'journal_id': bank_journal.id}),
],
})
# ==== Reconciliation ====
st_line = statement_2.line_ids.filtered(lambda line: line.payment_ref == 'line_2')
payment_4 = payments[3]
payment_line = payment_4.move_id.line_ids.filtered(lambda line: line.account_id == payment_4.payment_method_line_id.payment_account_id)
st_line.set_line_bank_statement_line(payment_line.id)
# ==== Report ====
report = self.env.ref('account_reports.bank_reconciliation_report').with_context(
active_id=bank_journal.id,
active_model=bank_journal._name
)
account_name = bank_journal.default_account_id.display_name
options = self._generate_options(report, '2015-01-01', '2015-01-31')
options['unfold_all'] = True
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount
[ 0, 1, 2, 3],
[
(account_name, '', '', ''),
('Opening Bank Balance as of January 01 2015', '', '', 1000.0),
('Reconciled Transactions', '', '', 0.0),
('Receipts', '', '', 300.0),
('BNKKK/2015/00004', '01/03/2015', 'line_2', 200.0),
('BNKKK/2015/00003', '01/02/2015', 'line_1', 100.0),
('Total Receipts', '', '', 300.0),
('Payments', '', '', -300.0),
('BNKKK/2015/00005', '01/04/2015', 'line_3', -300.0),
('Total Payments', '', '', -300.0),
('Total Reconciled Transactions', '', '', 0.0),
('Unreconciled Transactions', '', '', -300.0),
('Receipts', '', '', 600.0),
('BNKKK/2015/00001', '01/01/2015', 'line_1', 600.0),
('Total Receipts', '', '', 600.0),
('Payments', '', '', -900.0),
('BNKKK/2015/00006', '01/05/2015', 'line_4', -400.0),
('BNKKK/2015/00002', '01/01/2015', 'line_2', -500.0),
('Total Payments', '', '', -900.0),
('Total Unreconciled Transactions', '', '', -300.0),
('Misc. operations', '', '', 0.0),
('Calculated Ending Bank Balance as of January 31 2015', '', '', 700.0),
('Ending General Ledger Balance as of January 31 2015', '', '', 700.0),
('Outstanding Receipts/Payments', '', '', -300.0),
('(+) Outstanding Receipts', '', '', 600.0),
('PBNKKK/2015/00001', '01/01/2015', '', 600.0),
('Total (+) Outstanding Receipts', '', '', 600.0),
('(-) Outstanding Payments', '', '', -900.0),
('PBNKKK/2015/00006', '01/05/2015', '', -400.0),
('PBNKKK/2015/00002', '01/01/2015', '', -500.0),
('Total (-) Outstanding Payments', '', '', -900.0),
('Total Outstanding Receipts/Payments', '', '', -300.0),
],
options,
)
options = self._generate_options(report, '2014-12-01', '2014-12-31')
options['unfold_all'] = True
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount
[ 0, 1, 2, 3],
[
(account_name, '', '', ''),
('Opening Bank Balance as of December 01 2014', '', '', 0.0),
('Reconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Reconciled Transactions', '', '', 0.0),
('Unreconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Unreconciled Transactions', '', '', 0.0),
('Misc. operations', '', '', 1000.0),
('BNKKK/2014/00001', '12/31/2014', '', 1000.0),
('Total Misc. operations', '', '', 1000.0),
('Calculated Ending Bank Balance as of December 31 2014', '', '', 1000.0),
('Ending General Ledger Balance as of December 31 2014', '', '', 1000.0),
('Outstanding Receipts/Payments', '', '', 0.0),
('(+) Outstanding Receipts', '', '', 0.0),
('(-) Outstanding Payments', '', '', 0.0),
('Total Outstanding Receipts/Payments', '', '', 0.0),
],
options,
)
def test_reconciliation_report_multi_currencies(self):
""" Tests the management of multi-currencies in the reconciliation report. """
self.env.user.group_ids |= self.env.ref('base.group_multi_currency')
self.env.user.group_ids |= self.env.ref('base.group_no_one')
company_currency = self.company_data['currency'] # USD
journal_currency = self.other_currency # EUR
choco_currency = self.other_currency_2 # GBP
# ==== Journal with a foreign currency ====
bank_journal = self.env['account.journal'].create({
'name': 'Bank',
'code': 'BNKKK',
'type': 'bank',
'company_id': self.company_data['company'].id,
'currency_id': journal_currency.id
})
# ==== Statement ====
bank_statement = self.env['account.bank.statement'].create({
'name': 'statement',
'line_ids': [
# Transaction in the company currency.
(0, 0, {
'payment_ref': 'line_1',
'date': '2016-01-01',
'amount': 100.0,
'journal_id': bank_journal.id,
'amount_currency': 50.01,
'foreign_currency_id': company_currency.id,
}),
# Transaction in a third currency.
(0, 0, {
'payment_ref': 'line_3',
'date': '2016-01-01',
'amount': 100.0,
'journal_id': bank_journal.id,
'amount_currency': 999.99,
'foreign_currency_id': choco_currency.id,
}),
],
})
# Partially reconcile the suspense amount associated with each bank statement line
suspense_account = bank_journal.suspense_account_id
other_account = bank_journal.company_id.default_cash_difference_income_account_id
# the first is in company currency
bank_move_1 = bank_statement.line_ids[0].move_id
bank_move_1_suspense_line = bank_move_1.line_ids.filtered(lambda l: l.account_id == suspense_account)
bank_move_1.button_draft()
bank_move_1.write({'line_ids': [
Command.create({'account_id': other_account.id, 'credit': 10.00}),
Command.update(bank_move_1_suspense_line.id, {'credit': 40.01}),
]})
bank_move_1.action_post()
# the second is in neither company nor journal currency
bank_move_2 = bank_statement.line_ids[1].move_id
bank_move_2_suspense_line = bank_move_2.line_ids.filtered(lambda l: l.account_id == suspense_account)
bank_move_2.button_draft()
bank_move_2.write({'line_ids': [
Command.create({
'account_id': other_account.id,
'currency_id': bank_move_2_suspense_line.currency_id.id,
'credit': 3.33,
'amount_currency': -99.99
}),
Command.update(bank_move_2_suspense_line.id, {
'credit': 30.0,
'amount_currency': -900.0
}),
]})
bank_move_2.action_post()
# ==== Payments ====
self.inbound_payment_method_line.journal_id = bank_journal.id
# Payment in the company's currency.
payment_1 = self.env['account.payment'].create({
'amount': 1000.0,
'payment_type': 'inbound',
'partner_type': 'customer',
'date': '2016-01-01',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'currency_id': company_currency.id,
'payment_method_line_id': self.inbound_payment_method_line.id,
})
# Payment in the same foreign currency as the journal.
payment_2 = self.env['account.payment'].create({
'amount': 2000.0,
'payment_type': 'inbound',
'partner_type': 'customer',
'date': '2016-01-01',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'currency_id': journal_currency.id,
'payment_method_line_id': self.inbound_payment_method_line.id,
})
# Payment in a third foreign currency.
payment_3 = self.env['account.payment'].create({
'amount': 3000.0,
'payment_type': 'inbound',
'partner_type': 'customer',
'date': '2016-01-01',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
'currency_id': choco_currency.id,
'payment_method_line_id': self.inbound_payment_method_line.id,
})
(payment_1 + payment_2 + payment_3).action_post()
# ==== Misc Entry ====
move = self.env['account.move'].create({
'journal_id': self.company_data['default_journal_misc'].id,
'date': '2016-01-01',
'line_ids': [
Command.create({
'name': 'Line1',
'debit': 100,
'credit': 0,
'amount_currency': 200,
'account_id': bank_journal.default_account_id.id,
'currency_id': journal_currency.id
}),
Command.create({
'name': 'Line2',
'debit': 0,
'credit': 100,
'account_id': other_account.id,
}),
]
})
move.action_post()
# ==== Report ====
report = self.env.ref('account_reports.bank_reconciliation_report').with_context(
active_id=bank_journal.id,
active_model=bank_journal._name
)
account_name = bank_journal.default_account_id.display_name
with self.debug_mode():
options = self._generate_options(report, '2016-01-01', '2016-01-31')
options['unfold_all'] = True
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount Currency Amount
[ 0, 1, 2, 3, 4],
[
(account_name, '', '', '', ''),
('Opening Bank Balance as of January 01 2016', '', '', '', 0.0),
('Reconciled Transactions', '', '', '', 30.0),
('Receipts', '', '', '', 30.0),
('BNKKK/2016/00002', '01/01/2016', 'line_3', '£\xa099.99', 10.0),
('BNKKK/2016/00001', '01/01/2016', 'line_1', '$\xa010.00', 20.0),
('Total Receipts', '', '', '', 30.0),
('Payments', '', '', '', 0.0),
('Total Reconciled Transactions', '', '', '', 30.0),
('Unreconciled Transactions', '', '', '', 170.0),
('Receipts', '', '', '', 170.0),
('BNKKK/2016/00002', '01/01/2016', 'line_3', '£\xa0900.00', 90.0),
('BNKKK/2016/00001', '01/01/2016', 'line_1', '$\xa040.01', 80.0),
('Total Receipts', '', '', '', 170.0),
('Payments', '', '', '', 0.0),
('Total Unreconciled Transactions', '', '', '', 170.0),
('Misc. operations', '', '', '', 200.0),
('MISC/2016/01/0001', '01/01/2016', '', '', 200.0),
('Total Misc. operations', '', '', '', 200.0),
('Calculated Ending Bank Balance as of January 31 2016', '', '', '', 400.0),
('Ending General Ledger Balance as of January 31 2016', '', '', '', 400.0),
('Outstanding Receipts/Payments', '', '', '', 5900.0),
('(+) Outstanding Receipts', '', '', '', 5900.0),
('PBNKKK/2016/00003', '01/01/2016', '', '£\xa03,000.00', 900.0),
('PBNKKK/2016/00002', '01/01/2016', '', '', 2000.0),
('PBNKKK/2016/00001', '01/01/2016', '', '$\xa01,000.00', 3000.0),
('Total (+) Outstanding Receipts', '', '', '', 5900.0),
('(-) Outstanding Payments', '', '', '', 0.0),
('Total Outstanding Receipts/Payments', '', '', '', 5900.0),
],
options,
currency_map={4: {'currency': journal_currency}},
)
def test_reconciliation_change_date(self):
"""
Tests that openeing/ending balance and transactions are correct with change in report date options..
"""
bank_journal = self.company_data['default_journal_bank']
statement = self.env['account.bank.statement'].create({
'name': 'statement_1',
'date': '2019-01-10',
'balance_start': 1000.0,
'balance_end_real': 1130.0,
'line_ids': [
(0, 0, {'payment_ref': 'line_1', 'amount': 10.0, 'date': '2019-01-01', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_2', 'amount': 20.0, 'date': '2019-01-02', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_3', 'amount': 30.0, 'date': '2019-01-03', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_4', 'amount': -40.0, 'date': '2019-01-04', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_5', 'amount': 50.0, 'date': '2019-01-05', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_6', 'amount': 60.0, 'date': '2019-01-06', 'journal_id': bank_journal.id}),
],
})
# This will allow to test if the balance of the bank account is changed
statement['balance_end_real'] = 1140.0
payment = self.env['account.payment'].create({
'amount': 1000.0,
'payment_type': 'inbound',
'partner_type': 'customer',
'date': '2019-01-03',
'journal_id': bank_journal.id,
'partner_id': self.partner_a.id,
})
payment.action_post()
report = self.env.ref('account_reports.bank_reconciliation_report').with_context(
active_id=bank_journal.id,
active_model='account.journal'
)
account_name = bank_journal.default_account_id.display_name
options = self._generate_options(report, '2019-01-01', '2019-01-02')
options['unfold_all'] = True
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount
[ 0, 1, 2, 3],
[
(account_name, '', '', ''),
('Opening Bank Balance as of January 01 2019', '', '', 1000.0),
('Reconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Reconciled Transactions', '', '', 0.0),
('Unreconciled Transactions', '', '', 30.0),
('Receipts', '', '', 30.0),
('BNK1/2019/00002', '01/02/2019', 'line_2', 20.0),
('BNK1/2019/00001', '01/01/2019', 'line_1', 10.0),
('Total Receipts', '', '', 30.0),
('Payments', '', '', 0.0),
('Total Unreconciled Transactions', '', '', 30.0),
('Misc. operations', '', '', 0.0),
('Calculated Ending Bank Balance as of January 02 2019', '', '', 1030.0),
('Ending General Ledger Balance as of January 02 2019', '', '', 30.0),
('Outstanding Receipts/Payments', '', '', 0.0),
('(+) Outstanding Receipts', '', '', 0.0),
('(-) Outstanding Payments', '', '', 0.0),
('Total Outstanding Receipts/Payments', '', '', 0.0),
],
options,
)
options = self._generate_options(report, '2019-01-01', '2019-01-31')
options['unfold_all'] = True
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount
[ 0, 1, 2, 3],
[
(account_name, '', '', ''),
('Opening Bank Balance as of January 01 2019', '', '', 1000.0),
('Reconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Reconciled Transactions', '', '', 0.0),
('Unreconciled Transactions', '', '', 130.0),
('Receipts', '', '', 170.0),
('BNK1/2019/00006', '01/06/2019', 'line_6', 60.0),
('BNK1/2019/00005', '01/05/2019', 'line_5', 50.0),
('BNK1/2019/00003', '01/03/2019', 'line_3', 30.0),
('BNK1/2019/00002', '01/02/2019', 'line_2', 20.0),
('BNK1/2019/00001', '01/01/2019', 'line_1', 10.0),
('Total Receipts', '', '', 170.0),
('Payments', '', '', -40.0),
('BNK1/2019/00004', '01/04/2019', 'line_4', -40.0),
('Total Payments', '', '', -40.0),
('Total Unreconciled Transactions', '', '', 130.0),
('Misc. operations', '', '', 0.0),
('Calculated Ending Bank Balance as of January 31 2019', '', '', 1130.0),
('Ending General Ledger Balance as of January 31 2019', '', '', 130.0),
('Outstanding Receipts/Payments', '', '', 1000.0),
('(+) Outstanding Receipts', '', '', 1000.0),
('PBNK1/2019/00001', '01/03/2019', '', 1000.0),
('Total (+) Outstanding Receipts', '', '', 1000.0),
('(-) Outstanding Payments', '', '', 0.0),
('Total Outstanding Receipts/Payments', '', '', 1000.0),
],
options,
)
def test_reconciliation_report_non_statement_payment(self):
"""
Test that moves not linked to a bank statement/payment but linked for example to expenses are all showing in the
report
"""
bank_journal = self.env['account.journal'].create({
'name': 'Bank',
'code': 'BNKKK',
'type': 'bank',
'company_id': self.company_data['company'].id,
})
bank_journal.inbound_payment_method_line_ids.payment_account_id = self.inbound_payment_method_line.payment_account_id
# ==== Misc ====
self.env['account.move'].create({
'journal_id': bank_journal.id,
'date': '2014-12-31',
'line_ids': [
(0, 0, {
'name': 'Source',
'debit': 800,
'credit': 0,
'account_id': self.company_data['default_account_expense'].id,
}),
(0, 0, {
'name': 'Destination',
'debit': 0,
'credit': 800,
'account_id': self.inbound_payment_method_line.payment_account_id.id,
}),
]
}).action_post()
self.env['account.move'].create({
'journal_id': bank_journal.id,
'date': '2015-12-31',
'line_ids': [
(0, 0, {
'name': 'Source',
'debit': 500,
'credit': 0,
'account_id': self.company_data['default_account_expense'].id,
}),
(0, 0, {
'name': 'Destination',
'debit': 0,
'credit': 500,
'account_id': self.inbound_payment_method_line.payment_account_id.id,
}),
]
}).action_post()
# ==== Report ====
report = self.env.ref('account_reports.bank_reconciliation_report').with_context(
active_id=bank_journal.id,
active_model='account.journal'
)
account_name = bank_journal.default_account_id.display_name
options = self._generate_options(report, '2016-01-02', '2016-01-02')
options['unfold_all'] = True
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount
[ 0, 1, 2, 3],
[
(account_name, '', '', ''),
('Opening Bank Balance as of January 02 2016', '', '', 0.0),
('Reconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Reconciled Transactions', '', '', 0.0),
('Unreconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Unreconciled Transactions', '', '', 0.0),
('Misc. operations', '', '', 0.0),
('Calculated Ending Bank Balance as of January 02 2016', '', '', 0.0),
('Ending General Ledger Balance as of January 02 2016', '', '', 0.0),
('Outstanding Receipts/Payments', '', '', -1300.0),
('(+) Outstanding Receipts', '', '', 0.0),
('(-) Outstanding Payments', '', '', -1300.0),
('BNKKK/2015/00001', '12/31/2015', '', -500.0),
('BNKKK/2014/00001', '12/31/2014', '', -800.0),
('Total (-) Outstanding Payments', '', '', -1300.0),
('Total Outstanding Receipts/Payments', '', '', -1300.0),
],
options,
)
def test_reconciliation_report_delete_statement(self):
""" This test will do a basic flow where we create a statement and then we delete it to see how the report react"""
bank_journal = self.company_data['default_journal_bank']
statement = self.env['account.bank.statement'].create({
'name': 'statement_1',
'date': '2019-01-10',
'balance_start': 1000.0,
'balance_end_real': 1130.0,
'line_ids': [
(0, 0, {'payment_ref': 'line_1', 'amount': 10.0, 'date': '2018-12-31', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_2', 'amount': 20.0, 'date': '2019-01-02', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_3', 'amount': 30.0, 'date': '2019-01-03', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_4', 'amount': -40.0, 'date': '2019-01-04', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_5', 'amount': 50.0, 'date': '2019-01-05', 'journal_id': bank_journal.id}),
(0, 0, {'payment_ref': 'line_6', 'amount': 60.0, 'date': '2019-01-06', 'journal_id': bank_journal.id}),
],
})
report = self.env.ref('account_reports.bank_reconciliation_report').with_context(
active_id=bank_journal.id,
active_model='account.journal'
)
account_name = bank_journal.default_account_id.display_name
options = self._generate_options(report, '2019-01-01', '2019-01-12')
options['unfold_all'] = True
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount
[ 0, 1, 2, 3],
[
(account_name, '', '', ''),
('Opening Bank Balance as of January 01 2019', '', '', 1010.0),
('Reconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Reconciled Transactions', '', '', 0.0),
('Unreconciled Transactions', '', '', 120.0),
('Receipts', '', '', 160.0),
('BNK1/2019/00005', '01/06/2019', 'line_6', 60.0),
('BNK1/2019/00004', '01/05/2019', 'line_5', 50.0),
('BNK1/2019/00002', '01/03/2019', 'line_3', 30.0),
('BNK1/2019/00001', '01/02/2019', 'line_2', 20.0),
('Total Receipts', '', '', 160.0),
('Payments', '', '', -40.0),
('BNK1/2019/00003', '01/04/2019', 'line_4', -40.0),
('Total Payments', '', '', -40.0),
('Total Unreconciled Transactions', '', '', 120.0),
('Misc. operations', '', '', 0.0),
('Calculated Ending Bank Balance as of January 12 2019', '', '', 1130.0),
('Ending General Ledger Balance as of January 12 2019', '', '', 130.0),
('Outstanding Receipts/Payments', '', '', 0.0),
('(+) Outstanding Receipts', '', '', 0.0),
('(-) Outstanding Payments', '', '', 0.0),
('Total Outstanding Receipts/Payments', '', '', 0.0),
],
options,
)
statement.unlink()
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount
[ 0, 1, 2, 3],
[
(account_name, '', '', ''),
('Opening Bank Balance as of January 01 2019', '', '', 10.0),
('Reconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Reconciled Transactions', '', '', 0.0),
('Unreconciled Transactions', '', '', 120.0),
('Receipts', '', '', 160.0),
('BNK1/2019/00005', '01/06/2019', 'line_6', 60.0),
('BNK1/2019/00004', '01/05/2019', 'line_5', 50.0),
('BNK1/2019/00002', '01/03/2019', 'line_3', 30.0),
('BNK1/2019/00001', '01/02/2019', 'line_2', 20.0),
('Total Receipts', '', '', 160.0),
('Payments', '', '', -40.0),
('BNK1/2019/00003', '01/04/2019', 'line_4', -40.0),
('Total Payments', '', '', -40.0),
('Total Unreconciled Transactions', '', '', 120.0),
('Misc. operations', '', '', 0.0),
('Calculated Ending Bank Balance as of January 12 2019', '', '', 130.0),
('Ending General Ledger Balance as of January 12 2019', '', '', 130.0),
('Outstanding Receipts/Payments', '', '', 0.0),
('(+) Outstanding Receipts', '', '', 0.0),
('(-) Outstanding Payments', '', '', 0.0),
('Total Outstanding Receipts/Payments', '', '', 0.0),
],
options,
)
def test_reconciliation_report_exchange_entry(self):
""" This test will check that misc entries reported in the exchange journal
do not figure in the report
"""
bank_journal = self.company_data['default_journal_bank']
exchange_journal = self.env.company.currency_exchange_journal_id
move_a = self.env['account.move'].create({
'journal_id': exchange_journal.id,
'move_type': 'entry',
'date': '2019-01-01',
'line_ids': [
Command.create({
'name': 'line_a_1',
'account_id': bank_journal.default_account_id.id,
'debit': 1000.0,
'credit': 0.0,
}),
Command.create({
'name': 'line_a_2',
'account_id': self.company_data['default_account_expense'].id,
'debit': 0.0,
'credit': 1000.0,
}),
]
})
move_a.action_post()
report = self.env.ref('account_reports.bank_reconciliation_report').with_context(
active_id=bank_journal.id,
active_model='account.journal'
)
account_name = bank_journal.default_account_id.display_name
options = self._generate_options(report, '2019-01-01', '2019-01-12')
lines = report._get_lines(options)
self.assertLinesValues(
lines,
# Name Date Label Amount
[ 0, 1, 2, 3],
[
(account_name, '', '', ''),
('Opening Bank Balance as of January 01 2019', '', '', 0.0),
('Reconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Reconciled Transactions', '', '', 0.0),
('Unreconciled Transactions', '', '', 0.0),
('Receipts', '', '', 0.0),
('Payments', '', '', 0.0),
('Total Unreconciled Transactions', '', '', 0.0),
('Misc. operations', '', '', 0.0),
('Calculated Ending Bank Balance as of January 12 2019', '', '', 0.0),
('Ending General Ledger Balance as of January 12 2019', '', '', 1000.0),
('Outstanding Receipts/Payments', '', '', 0.0),
('(+) Outstanding Receipts', '', '', 0.0),
('(-) Outstanding Payments', '', '', 0.0),
('Total Outstanding Receipts/Payments', '', '', 0.0),
],
options,
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,226 @@
# -*- coding: utf-8 -*-
# pylint: disable=C0326
from os import getenv
from freezegun import freeze_time
from unittest import skipIf
from unittest.mock import patch
from odoo.addons.account.tests.common import AccountTestInvoicingHttpCommon
from odoo import Command
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestReportSections(AccountTestInvoicingHttpCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.section_1 = cls.env['account.report'].create({
'name': "Section 1",
'filter_journals': True,
'column_ids': [
Command.create({
'name': "Column 1",
'expression_label': 'col1',
}),
],
'line_ids': [
Command.create({
'name': 'Section 1 line',
'expression_ids': [
Command.create({
'label': 'col1',
'engine': 'tax_tags',
'formula': 'tag1_1',
}),
],
}),
],
})
cls.section_2 = cls.env['account.report'].create({
'name': "Section 2",
'filter_period_comparison': True,
'column_ids': [
Command.create({
'name': "Column 1",
'expression_label': 'col1',
}),
Command.create({
'name': "Column 2",
'expression_label': 'col2',
}),
],
'line_ids': [
Command.create({
'name': 'Section 2 line',
'expression_ids': [
Command.create({
'label': 'col1',
'engine': 'tax_tags',
'formula': 'tag2_1',
}),
Command.create({
'label': 'col2',
'engine': 'tax_tags',
'formula': 'tag2_2',
})
],
}),
],
})
cls.composite_report = cls.env['account.report'].create({
'name': "Test Sections",
'section_report_ids': [Command.set((cls.section_1 + cls.section_2).ids)],
})
cls.basic_return_type = cls.env['account.return.type'].create({
'name': 'Test return type',
'report_id': cls.composite_report.id,
'deadline_start_date': '2024-01-01',
'states_workflow': 'generic_state_tax_report',
'tax_payable_account_id': cls.company_data['default_tax_account_payable'].id,
'tax_receivable_account_id': cls.company_data['default_tax_account_receivable'].id,
})
def test_sections_options_report_selection_variant(self):
# Set a fictive country on the company ; making sure no variant is available for it, whatever the modules installed.
self.env.company.account_fiscal_country_id = self.env['res.country'].create({
'name': "Discworld",
'code': 'YY',
})
generic_tax_report = self.env.ref('account.generic_tax_report')
self.composite_report.root_report_id = generic_tax_report
# Open root report
options = generic_tax_report.get_options({})
self.assertEqual(options['variants_source_id'], generic_tax_report.id, "The root report should be the variants source.")
self.assertEqual(options['sections_source_id'], generic_tax_report.id, "No variant is selected; the root report should be chosen.")
self.assertEqual(options['selected_variant_id'], generic_tax_report.id, "No variant is selected; the root report should be chosen.")
self.assertEqual(options['report_id'], generic_tax_report.id, "No variant is selected; the root report should be chosen.")
# Select the variant
options = generic_tax_report.get_options({**options, 'selected_variant_id': self.composite_report.id})
self.assertEqual(options['variants_source_id'], generic_tax_report.id, "The root report should be the variants source.")
self.assertEqual(options['sections_source_id'], self.composite_report.id, "The selected variant should be the sections source.")
self.assertEqual(options['selected_section_id'], self.section_1.id, "Selecting the composite variant should select its first section.")
self.assertEqual(options['report_id'], self.section_1.id, "Selecting the composite variant should open its first section.")
# Select the section
options = generic_tax_report.get_options({**options, 'selected_section_id': self.section_2.id})
self.assertEqual(options['variants_source_id'], generic_tax_report.id, "The root report should be the variants source.")
self.assertEqual(options['sections_source_id'], self.composite_report.id, "The selected variant should be the sections source.")
self.assertEqual(options['selected_section_id'], self.section_2.id, "Section 2 should be selected.")
self.assertEqual(options['report_id'], self.section_2.id, "Selecting the second section from the first one should open it.")
def test_sections_options_report_selection_root(self):
# Open the report
options = self.composite_report.get_options({})
self.assertEqual(options['variants_source_id'], self.composite_report.id, "The root report should be the variants source.")
self.assertEqual(options['sections_source_id'], self.composite_report.id, "The root report should be the sections source.")
self.assertEqual(options['selected_section_id'], self.section_1.id, "Opening the composite report should select its first section.")
self.assertEqual(options['report_id'], self.section_1.id, "Opening the composite report should open its first section.")
# Select the section
options = self.composite_report.get_options({**options, 'selected_section_id': self.section_2.id})
self.assertEqual(options['variants_source_id'], self.composite_report.id, "The root report should be the variants source.")
self.assertEqual(options['sections_source_id'], self.composite_report.id, "The root report should be the sections source.")
self.assertEqual(options['selected_section_id'], self.section_2.id, "Section 2 should be selected.")
self.assertEqual(options['report_id'], self.section_2.id, "Selecting the second section from the first one should open it.")
@skipIf(getenv("ODOO_FAKETIME_TEST_MODE"), "Faketime mode doesn't play well with interval selection in the report filter")
def test_sections_tour(self):
def patched_init_options_custom(report, options, previous_options):
# Emulates a custom handler modifying the export buttons
if report == self.composite_report:
options['buttons'][0]['name'] = 'composite_report_custom_button'
# Setup the reports
generic_tax_report = self.env.ref('account.generic_tax_report')
self.composite_report.root_report_id = generic_tax_report
self.section_1.root_report_id = generic_tax_report # First section is a variant of the root report, to increase test coverage
# Rewriting the root report recomputes filter_journal ; re-enable it
self.section_1.filter_journals = True
with patch.object(type(self.env['account.report']), '_init_options_custom', patched_init_options_custom):
self.start_tour("/odoo/action-account_reports.action_account_report_gt", 'account_reports_sections', login=self.env.user.login)
def test_exported_xlsx_unique_names(self):
composite_report = self.env['account.report'].create({
'name': "Composite",
})
for i in range(1, 13):
self.env['account.report'].create({
'name': "Comprehensive Monthly Analysis Report Q%d" % i,
'section_main_report_ids': [Command.set([composite_report.id])],
})
composite_report.export_to_xlsx(composite_report.get_options({}))
@freeze_time('2024-11-24')
def test_tax_return_with_section_report(self):
tax_return = self.env['account.return'].create({
'name': "Tax return",
'type_id': self.basic_return_type.id,
'company_id': self.env.company.id,
'date_from': '2024-01-01',
'date_to': '2024-01-31',
})
tax_tag = self.env['account.account.tag'].search([('name', '=', 'tag1_1')])
invoice_previous_period = self.env['account.move'].create({
'partner_id': self.partner.id,
'move_type': 'out_invoice',
'date': '2024-01-15',
'invoice_date': '2024-01-15',
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'quantity': 1,
'price_unit': 1000,
})
],
})
invoice_current_period = self.env['account.move'].create({
'partner_id': self.partner.id,
'move_type': 'out_invoice',
'invoice_line_ids': [
Command.create({
'product_id': self.product_a.id,
'quantity': 1,
'price_unit': 20000,
})
],
})
for invoice in (invoice_previous_period | invoice_current_period):
invoice.action_post()
# We manually add this tax_tag, so the line will be counted in the Section 1 report
invoice.invoice_line_ids.tax_tag_ids = [tax_tag.id]
# To be sure we will compute amount_to_pay
tax_return.is_tax_return = True
tax_return.action_submit()
self.assertEqual(tax_return.total_amount_to_pay, 150)
def test_composite_report_with_journal_report_pdf_export(self):
"""
Test that exporting a composite report containing a journal report to PDF
works correctly.
"""
journal_report = self.env.ref('account_reports.journal_report')
composite_with_journal = self.env['account.report'].create({
'name': 'Test Composite with Journal Report',
'section_report_ids': [Command.set([journal_report.id])],
})
options = composite_with_journal.get_options({})
result = composite_with_journal.export_to_pdf(options)
self.assertTrue(result.get('file_content'), 'PDF should be generated successfully')
self.assertEqual(result.get('file_type'), 'pdf', 'File type should be PDF')

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,370 @@
# -*- coding: utf-8 -*-
# pylint: disable=C0326
import json
from unittest.mock import patch
from .common import TestAccountReportsCommon
from odoo import fields, Command
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestTaxReportCarryover(TestAccountReportsCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
# necessary to ensure successful return checks
cls.company_data['company'].write({
'vat': 'US12345671',
'phone': '123456789',
'email': 'test@gmail.com',
})
cls.company_1 = cls.company_data['company']
cls.company_2 = cls.company_data_2['company']
cls.company_2.currency_id = cls.company_1.currency_id
cls.company_1.account_return_periodicity = cls.company_2.account_return_periodicity = 'year'
cls.company_1.write({
'vat': '38972223422',
'phone': '555-555-5555',
'email': 'test@example.com',
})
cls.company_2.write({
'vat': '38972223423',
'phone': '666-666-6666',
'email': 'test2@example.com',
})
cls.report = cls.env['account.report'].create({
'name': 'Test report',
'country_id': cls.company_1.account_fiscal_country_id.id,
'root_report_id': cls.env.ref("account.generic_tax_report").id,
'column_ids': [Command.create({'name': 'Balance', 'sequence': 1, 'expression_label': 'balance'})],
})
cls.report_line = cls.env['account.report.line'].create({
'name': 'Test carryover',
'code': 'test_carryover',
'report_id': cls.report.id,
'sequence': 1,
'expression_ids': [
Command.create({
'label': 'tag',
'engine': 'domain',
'formula': [('account_id.account_type', '=', 'expense')],
'subformula': 'sum',
}),
Command.create({
'label': '_applied_carryover_balance',
'engine': 'external',
'formula': 'most_recent',
'date_scope': 'previous_return_period',
}),
Command.create({
'label': 'balance_unbound',
'engine': 'aggregation',
'formula': 'test_carryover.tag + test_carryover._applied_carryover_balance',
}),
Command.create({
'label': '_carryover_balance',
'engine': 'aggregation',
'formula': 'test_carryover.balance_unbound',
'subformula': 'if_below(EUR(0))',
}),
Command.create({
'label': 'balance',
'engine': 'aggregation',
'formula': 'test_carryover.balance_unbound',
'subformula': 'if_above(EUR(0))',
}),
],
})
cls.tax_return_type = cls.env['account.return.type'].create({
'name': "The Return of the King",
'report_id': cls.report.id,
'tax_payable_account_id': cls.company_data['default_tax_account_payable'].id,
'tax_receivable_account_id': cls.company_data['default_tax_account_receivable'].id,
})
def test_tax_report_carry_over(self):
move = self.env['account.move'].create({
'move_type': 'entry',
'date': '2021-03-01',
'line_ids': [
Command.create({
'debit': 0.0,
'credit': 1000.0,
'name': '2021_03_01',
'account_id': self.company_data['default_account_expense'].id
}),
Command.create({
'debit': 1000.0,
'credit': 0.0,
'name': '2021_03_01',
'account_id': self.company_data['default_account_payable'].id
}),
],
})
move.action_post()
self.env.flush_all()
tax_return = self.env['account.return'].create({
'name': "Tax return",
'type_id': self.tax_return_type.id,
'company_id': self.env.company.id,
'date_from': '2021-01-01',
'date_to': '2021-12-31',
})
with self.allow_pdf_render():
tax_return.action_submit()
# There should be an external value of -1000.0
external_value = self.env['account.report.external.value'].search([('company_id', '=', self.company_1.id)])
self.assertEqual(external_value.target_report_expression_label, '_applied_carryover_balance')
self.assertEqual(external_value.date, fields.Date.from_string('2021-12-31'))
self.assertEqual(external_value.value, -1000.0)
# There should be no value in the report since there is a carryover
options = self._generate_options(self.report, '2021-01-01', '2021-12-31')
lines = self.report._get_lines(options)
self.assertLinesValues(
lines,
# Name Balance
[ 0, 1],
[
('Test carryover', 0.0),
],
options,
)
# There should be a carryover pop-up of value -1000.0
info_popup_data = json.loads(lines[0].columns[0].info_popup_data)
self.assertEqual(info_popup_data['carryover'], '-1,000.00')
# The carry over should be applied on the next period
options = self._generate_options(self.report, '2022-01-01', '2022-12-31')
lines = self.report._get_lines(options)
self.assertLinesValues(
lines,
# Name Balance
[ 0, 1],
[
('Test carryover', 0.0),
],
options,
)
info_popup_data = json.loads(lines[0].columns[0].info_popup_data)
self.assertEqual(info_popup_data['carryover'], '-1,000.00')
self.assertEqual(info_popup_data['applied_carryover'], '-1,000.00')
def test_tax_report_carry_over_tax_unit(self):
tax_unit = self.env['account.tax.unit'].create({
'name': 'Test tax unit',
'country_id': self.company_1.account_fiscal_country_id.id,
'vat': 'DW1234567890',
'company_ids': [Command.set([self.company_1.id, self.company_2.id])],
'main_company_id': self.company_1.id,
})
move_company_1 = self.env['account.move'].with_company(self.company_1).create({
'move_type': 'entry',
'date': '2021-03-01',
'line_ids': [
Command.create({
'debit': 0.0,
'credit': 1000.0,
'name': '2021_03_01',
'account_id': self.company_data['default_account_expense'].id
}),
Command.create({
'debit': 1000.0,
'credit': 0.0,
'name': '2021_03_01',
'account_id': self.company_data['default_account_payable'].id
}),
],
})
move_company_1.action_post()
move_company_2 = self.env['account.move'].with_company(self.company_2).create({
'move_type': 'entry',
'date': '2021-03-01',
'line_ids': [
Command.create({
'debit': 2000.0,
'credit': 0.0,
'name': '2021_03_01',
'account_id': self.company_data_2['default_account_expense'].id
}),
Command.create({
'debit': 0.0,
'credit': 2000.0,
'name': '2021_03_01',
'account_id': self.company_data_2['default_account_payable'].id
}),
],
})
move_company_2.action_post()
self.env.flush_all()
# There should be no external value for company 1 at this point
external_value_company_1 = self.env['account.report.external.value'].search_count([('company_id', '=', self.company_1.id)])
self.assertEqual(external_value_company_1, 0)
# Closes both companies
tax_return = self.env['account.return'].create({
'name': "Tax return",
'type_id': self.tax_return_type.id,
'company_id': self.company_1.id,
'tax_unit_id': tax_unit.id,
'date_from': '2021-01-01',
'date_to': '2021-12-31',
})
with self.allow_pdf_render():
tax_return.action_submit()
self.assertTrue(all(move.state == 'posted' for move in tax_return.closing_move_ids))
self.assertEqual(len(tax_return.closing_move_ids), 2, "There should be one closing per company in the tax unit")
self.assertTrue(all(closing.state == 'posted' for closing in tax_return.closing_move_ids), "Posting the main company's closing should post every other closing of this unit")
# There should be two external value for company_1: -1000.0 and 1000.0
external_value_company_1 = self.env['account.report.external.value'].search([('company_id', '=', self.company_1.id)])
external_value_company_1 = sorted(external_value_company_1, key=lambda x: x.value) # To make sure they are always in the same order
self.assertEqual(external_value_company_1[0].target_report_expression_label, '_applied_carryover_balance')
self.assertEqual(external_value_company_1[0].date, fields.Date.from_string('2021-12-31'))
self.assertEqual(external_value_company_1[0].value, -1000.0)
self.assertEqual(external_value_company_1[1].target_report_expression_label, '_applied_carryover_balance')
self.assertEqual(external_value_company_1[1].date, fields.Date.from_string('2021-12-31'))
self.assertEqual(external_value_company_1[1].value, 1000.0)
# There should be no external value for company_2
external_value_company_2 = self.env['account.report.external.value'].search_count([('company_id', '=', self.company_2.id)])
self.assertEqual(external_value_company_2, 0)
# TAX UNIT REPORT (current period)
# ==============================================================================================================
# There should be a value of 1000.0 in the report since the sum of the balance of both companies is positive,
# there is no carryover
options = self._generate_options(self.report, '2021-01-01', '2021-12-31')
lines_tax_unit = self.report._get_lines(options)
self.assertLinesValues(
lines_tax_unit,
# Name Balance
[ 0, 1],
[
('Test carryover', 1000.0),
],
options,
)
# There should be no carryover pop-up
self.assertFalse(lines_tax_unit[0].columns[0].info_popup_data)
# COMPANY 1 REPORT (current period)
# ==============================================================================================================
# There should be no value in the report since there is a carryover
report_company_1 = self.report.with_context(allowed_company_ids=self.company_1.ids)
options = self._generate_options(report_company_1, '2021-01-01', '2021-12-31')
lines_company_1 = report_company_1._get_lines(options)
self.assertLinesValues(
lines_company_1,
# Name Balance
[ 0, 1],
[
('Test carryover', 0.0),
],
options,
)
# There should be a carryover pop-up
info_popup_data = json.loads(lines_company_1[0].columns[0].info_popup_data)
self.assertEqual(info_popup_data['carryover'], '-1,000.00')
# COMPANY 2 REPORT (current period)
# ==============================================================================================================
# There should be a value of 2000.0 in the report since there is no carryover
report_company_2 = self.report.with_context(allowed_company_ids=self.company_2.ids)
options = self._generate_options(report_company_2, '2021-01-01', '2021-12-31')
lines_company_2 = report_company_2._get_lines(options)
self.assertLinesValues(
lines_company_2,
# Name Balance
[ 0, 1],
[
('Test carryover', 2000.0),
],
options,
)
# There should be no carryover pop-up
self.assertFalse(lines_company_2[0].columns[0].info_popup_data)
# TAX UNIT REPORT (next period)
# ==============================================================================================================
options = self._generate_options(self.report, '2022-01-01', '2022-12-31')
lines_tax_unit = self.report._get_lines(options)
self.assertLinesValues(
lines_tax_unit,
# Name Balance
[ 0, 1],
[
('Test carryover', 0.0),
],
options,
)
# There should be no carryover pop-up
self.assertFalse(lines_tax_unit[0].columns[0].info_popup_data)
# COMPANY 1 REPORT (next period)
# ==============================================================================================================
report_company_1 = self.report.with_context(allowed_company_ids=self.company_1.ids)
options = self._generate_options(report_company_1, '2022-01-01', '2022-12-31')
lines_company_1 = report_company_1._get_lines(options)
self.assertLinesValues(
lines_company_1,
# Name Balance
[ 0, 1],
[
('Test carryover', 0.0),
],
options,
)
self.assertFalse(lines_company_1[0].columns[0].info_popup_data)
# COMPANY 2 REPORT (next period)
# ==============================================================================================================
report_company_2 = self.report.with_context(allowed_company_ids=self.company_2.ids)
options = self._generate_options(report_company_2, '2022-01-01', '2022-12-31')
lines_company_2 = report_company_2._get_lines(options)
self.assertLinesValues(lines_company_2,
# Name Balance
[ 0, 1],
[
('Test carryover', 0.0),
],
options,
)
# There should be no carryover pop-up
self.assertFalse(lines_company_2[0].columns[0].info_popup_data)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import Command, fields
from odoo.tests import tagged
from odoo.addons.account.tests.common import AccountTestInvoicingHttpCommon
@tagged('post_install', '-at_install')
class TestTourAccountReports(AccountTestInvoicingHttpCommon):
_test_user_groups = None # FIXME list needed groups
@classmethod
def setUpClass(cls):
super().setUpClass()
today = fields.Date.today()
previous_year = fields.Date.from_string('%s-%s-01' % (today.year - 1, today.month))
cls.out_invoice_current_year = cls.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': cls.partner_a.id,
'invoice_date': today,
'date': today,
'invoice_line_ids': [
Command.create({'name': 'line1', 'price_unit': 100.0}),
],
})
cls.out_invoice_current_year.action_post()
cls.out_invoice_previous_year = cls.env['account.move'].create({
'move_type': 'out_invoice',
'partner_id': cls.partner_a.id,
'invoice_date': previous_year,
'date': previous_year,
'invoice_line_ids': [
Command.create({'name': 'line1', 'price_unit': 500.0}),
],
})
cls.out_invoice_previous_year.action_post()
def test_tour_account_reports(self):
self.start_tour("/odoo/action-account_reports.action_account_report_pl", 'account_reports_widgets', login=self.env.user.login)

File diff suppressed because it is too large Load Diff